diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000..2d1fe75 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"gbot"},"name":"gbot-marketplace","plugins":[{"category":"Productivity","name":"gbot","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./artifact","source":"local"}}]} diff --git a/.changeset/clean-pugs-dream.md b/.changeset/clean-pugs-dream.md new file mode 100644 index 0000000..477ec4c --- /dev/null +++ b/.changeset/clean-pugs-dream.md @@ -0,0 +1,5 @@ +--- +"grok-bot-cli": patch +--- + +Ship generated host marketplaces and the complete Agent Bundle artifact in the GitHub repository so Codex, Claude Code, and Cursor can install it without a local build. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..cb65abf --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","name":"gbot-marketplace","owner":{"name":"gbot"},"plugins":[{"author":{"name":"Zack Jackson","url":"https://github.com/ScriptedAlchemy"},"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","homepage":"https://github.com/ScriptedAlchemy/grok-bot-cli#readme","keywords":["grok","grok-bot","grokbot","gbot","cursor","ai-agents","automation","terminal","cli","agent-bundle"],"license":"MIT","name":"gbot","repository":"https://github.com/ScriptedAlchemy/grok-bot-cli","source":"./artifact","version":"0.9.0"}]} diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json new file mode 100644 index 0000000..2930584 --- /dev/null +++ b/.cursor-plugin/marketplace.json @@ -0,0 +1 @@ +{"name":"gbot-marketplace","owner":{"name":"gbot"},"plugins":[{"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","name":"gbot","source":"./artifact"}]} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d524747..f7dced2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,11 @@ jobs: - name: Install dependencies run: npm ci + - name: Validate committed distribution + run: | + npm run validate:artifact + node --test test/release-config.test.js + - name: Validate, build, typecheck, and test run: npm run check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f9858ad..da22d4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -67,6 +67,8 @@ jobs: github-token: ${{ secrets.GITHUB_TOKEN }} publish-script: npm run release pr-title: Release packages + push-with-git-cli: true + version-script: npm run release:version # Green must mean published. Once no changesets are pending, the version # in package.json is the one that should be on npm, whether this run diff --git a/.gitignore b/.gitignore index 1aeef5b..18e51f5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ node_modules/ .worktrees/ dist/ -artifact/ .agent-bundle/ .env .env.* diff --git a/README.md b/README.md index 977fec0..3fedc9a 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,20 @@ Codex conversation, and managed bridge tools, plus a `talk-to-grok-bot` skill. The tools bundle this repository's gateway client and worker, so the installed plugin does not need `gbot` on `PATH`. +Install the committed bundle directly from GitHub without cloning or building it: + +```sh +codex plugin marketplace add ScriptedAlchemy/grok-bot-cli +codex plugin add gbot@gbot-marketplace + +claude plugin marketplace add ScriptedAlchemy/grok-bot-cli +claude plugin install gbot@gbot-marketplace +``` + +Cursor users can add `https://github.com/ScriptedAlchemy/grok-bot-cli` as a +marketplace repository from Customize → Plugins. The repository-root host +marketplaces all point at the committed `artifact/` bundle. + Install the bundled host projections from the same npm package: ```sh diff --git a/agent-bundle.config.ts b/agent-bundle.config.ts index eaf57ab..4c91312 100644 --- a/agent-bundle.config.ts +++ b/agent-bundle.config.ts @@ -6,7 +6,7 @@ export default defineConfig({ }, lib: false, marketplace: true, - output: { distPath: 'artifact' }, + output: { distPath: 'artifact', repositoryMarketplace: true }, plugin: { description: 'Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.', diff --git a/artifact/.agents/plugins/marketplace.json b/artifact/.agents/plugins/marketplace.json new file mode 100644 index 0000000..644a007 --- /dev/null +++ b/artifact/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"gbot"},"name":"gbot-marketplace","plugins":[{"category":"Productivity","name":"gbot","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/artifact/.claude-plugin/marketplace.json b/artifact/.claude-plugin/marketplace.json new file mode 100644 index 0000000..82f2093 --- /dev/null +++ b/artifact/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","name":"gbot-marketplace","owner":{"name":"gbot"},"plugins":[{"author":{"name":"Zack Jackson","url":"https://github.com/ScriptedAlchemy"},"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","homepage":"https://github.com/ScriptedAlchemy/grok-bot-cli#readme","keywords":["grok","grok-bot","grokbot","gbot","cursor","ai-agents","automation","terminal","cli","agent-bundle"],"license":"MIT","name":"gbot","repository":"https://github.com/ScriptedAlchemy/grok-bot-cli","source":"./","version":"0.9.0"}]} diff --git a/artifact/.claude-plugin/plugin.json b/artifact/.claude-plugin/plugin.json new file mode 100644 index 0000000..8cc697a --- /dev/null +++ b/artifact/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"gbot"},"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","name":"gbot","version":"0.9.0"} diff --git a/artifact/.codex-plugin/mcp.json b/artifact/.codex-plugin/mcp.json new file mode 100644 index 0000000..18bb5a3 --- /dev/null +++ b/artifact/.codex-plugin/mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"grok-bot":{"args":["./mcp/mcp-grok-bot-b8c2461e.mjs"],"command":"node","cwd":"./","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"./"},"type":"stdio"}}} diff --git a/artifact/.codex-plugin/plugin.json b/artifact/.codex-plugin/plugin.json new file mode 100644 index 0000000..cd2f0e1 --- /dev/null +++ b/artifact/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"Zack Jackson","url":"https://github.com/ScriptedAlchemy"},"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","homepage":"https://github.com/ScriptedAlchemy/grok-bot-cli#readme","interface":{"capabilities":["mcp","skills"],"category":"Productivity","defaultPrompt":["Help me use gbot."],"developerName":"gbot","displayName":"gbot","longDescription":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","shortDescription":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links."},"keywords":["grok","grok-bot","grokbot","gbot","cursor","ai-agents","automation","terminal","cli","agent-bundle"],"license":"MIT","mcpServers":"./.codex-plugin/mcp.json","name":"gbot","repository":"https://github.com/ScriptedAlchemy/grok-bot-cli","skills":"./skills/","version":"0.9.0"} diff --git a/artifact/.cursor-plugin/marketplace.json b/artifact/.cursor-plugin/marketplace.json new file mode 100644 index 0000000..5de5de2 --- /dev/null +++ b/artifact/.cursor-plugin/marketplace.json @@ -0,0 +1 @@ +{"name":"gbot-marketplace","owner":{"name":"gbot"},"plugins":[{"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","name":"gbot","source":"./"}]} diff --git a/artifact/.cursor-plugin/mcp.json b/artifact/.cursor-plugin/mcp.json new file mode 100644 index 0000000..f497537 --- /dev/null +++ b/artifact/.cursor-plugin/mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"grok-bot":{"args":["${CURSOR_PLUGIN_ROOT}/mcp/mcp-grok-bot-b8c2461e.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CURSOR_PLUGIN_ROOT}"}}}} diff --git a/artifact/.cursor-plugin/plugin.json b/artifact/.cursor-plugin/plugin.json new file mode 100644 index 0000000..a353355 --- /dev/null +++ b/artifact/.cursor-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"Zack Jackson"},"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","displayName":"gbot","homepage":"https://github.com/ScriptedAlchemy/grok-bot-cli#readme","keywords":["grok","grok-bot","grokbot","gbot","cursor","ai-agents","automation","terminal","cli","agent-bundle"],"license":"MIT","mcpServers":"./.cursor-plugin/mcp.json","name":"gbot","repository":"https://github.com/ScriptedAlchemy/grok-bot-cli","skills":"./skills/","version":"0.9.0"} diff --git a/artifact/.mcp.json b/artifact/.mcp.json new file mode 100644 index 0000000..94f210d --- /dev/null +++ b/artifact/.mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"grok-bot":{"args":["${CLAUDE_PLUGIN_ROOT}/mcp/mcp-grok-bot-b8c2461e.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CLAUDE_PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/artifact/INSTALL.md b/artifact/INSTALL.md new file mode 100644 index 0000000..118890f --- /dev/null +++ b/artifact/INSTALL.md @@ -0,0 +1,274 @@ +# Install gbot + +Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links. + +Version: `0.9.0` + +Run these commands from this bundle directory. The bundle is self-contained: every command below is +a host command or the bundled installer, and nothing requires the `agent-bundle` CLI. Where that CLI is +mentioned it is optional and automates the same steps. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install gbot@gbot-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. + +### Reinstall after a same-version rebuild + +`claude plugin update` is version-gated: when the bundle content changed but `version` did not, +it reports the plugin is already at the latest version and leaves the cached copy stale. +Uninstall and install again instead (`--keep-data` preserves the plugin's persistent data): + +```sh +claude plugin uninstall gbot@gbot-marketplace --scope user --keep-data +claude plugin marketplace add ./ +claude plugin install gbot@gbot-marketplace --scope user +``` + +With the optional `agent-bundle` CLI, `agent-bundle install claude --from ./` runs this sequence +automatically when the installed copy has the same version but a different content hash; `--replace` +(alias `--force`) forces it. + +### Uninstall + +```sh +claude plugin uninstall gbot@gbot-marketplace --scope user --keep-data +``` + +Match the scope the plugin was installed with (`user`, `project`, or `local`). `--keep-data` keeps durable +runtime state (Claude orphans the cached copy, `state/` included, for its ~14-day grace period); omit it to +remove `~/.claude/plugins/data//` immediately. + +The marketplace `gbot-marketplace` stays registered. Remove it only when nothing else installs from it: +`plugin marketplace remove` applies to every scope and every project, and `claude plugin list` shows only +the current project, so also check `~/.claude/plugins/installed_plugins.json` (under `$CLAUDE_CONFIG_DIR` +when set), where Claude records every scope of every install. The optional `agent-bundle uninstall claude` +below performs that inventory before it removes anything. + +```sh +claude plugin marketplace remove gbot-marketplace +``` + +With the optional `agent-bundle` CLI, `agent-bundle uninstall claude --from ./ --plan` prints exactly what +would be removed and `agent-bundle uninstall claude --from ./` reverses the recorded registrations. +`agent-bundle install claude` records a receipt at `~/.claude/agent-bundle/receipts/gbot.gbot-marketplace.user.json` +(or under `$CLAUDE_CONFIG_DIR`; `user` is the install scope, pass `--scope project` or `--scope local` to match +a scoped install), and `uninstall` consumes it, running the two commands above in order and retaining the +marketplace while any other plugin, scope, or project still installs from it. Durable runtime state +is kept by default; `--purge-data --confirm-purge` removes `state/` and `~/.claude/plugins/data//` +immediately. A missing receipt or a cached copy that no longer matches it is refused unless `--force`; a +second run is a `not-installed` no-op. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add gbot@gbot-marketplace +``` + +### Reinstall after a same-version rebuild + +`codex plugin add` re-copies the marketplace snapshot and keeps plugin settings in `config.toml`. +`codex plugin remove` deletes that settings subtree, including nested MCP overrides, so a same-version +refresh is add-only: + +```sh +codex plugin marketplace add ./ +codex plugin add gbot@gbot-marketplace +``` + +Native add resets a plugin-level `enabled = false` to `true`. +The native plugin CLI has no qualified settings-preserving update API, so the optional +`agent-bundle install` refuses replacement when `plugin list --json` reports `enabled: false` +or omits `enabled` (`AB7004`) and leaves that install unchanged. Enable the plugin in Codex first, then rerun. + +With the optional `agent-bundle` CLI, `agent-bundle install codex --from ./` runs this sequence +automatically when the installed copy has the same version but a different content hash; `--replace` +(alias `--force`) forces it. + +### Uninstall + +```sh +codex plugin remove gbot@gbot-marketplace +``` + +Codex 0.147.0 deletes the cached plugin tree, `state/` included, on `plugin remove` and has no keep-data +option. + +The marketplace `gbot-marketplace` stays registered. Remove it only when nothing else installs from it: +`codex plugin list` shows every other plugin from it. + +```sh +codex plugin marketplace remove gbot-marketplace +``` + +With the optional `agent-bundle` CLI, `agent-bundle uninstall codex --from ./ --plan` prints exactly what +would be removed and `agent-bundle uninstall codex --from ./` reverses the recorded registrations. +`agent-bundle install codex` records a receipt at `~/.codex/agent-bundle/receipts/gbot.gbot-marketplace.user.json` (or +under `$CODEX_HOME`), and `uninstall` consumes it, running the two commands above in order. `--keep-data` +cannot preserve durable state on Codex; the result says so (`unavailable`). A missing receipt or a cached +copy that no longer matches it is refused unless `--force`; a second run is a `not-installed` no-op. + +## Cursor + +Cursor has no non-interactive plugin install command. The bundled installer supports two delivery modes. + +### Local plugin (default) + +```sh +node ./install.mjs +``` + +It safe-copies the bundle to `~/.cursor/plugins/local/gbot`. Restart Cursor or run +`Developer: Reload Window` after installation. Cursor loads rules, skills, MCP servers, and the +manifest-declared `hooks/hooks.json` from that directory; plugin hooks run from the plugin root with +`${CURSOR_PLUGIN_ROOT}` substituted and need no `~/.cursor/hooks.json` entry. + +### Reinstall after a same-version rebuild + +The installer writes an install receipt (`.agent-bundle-install.json`: plugin, version, content hash, +owned files) beside the plugin manifest. Re-running `node ./install.mjs` on an identical artifact +is a no-op that says so. When the installed copy has the same version but different content, the +installer replaces its owned files in place and leaves runtime state (`state/`) untouched: + +```sh +node ./install.mjs # same-version content drift of a receipt-managed copy is replaced +node ./install.mjs --replace # also replace a different installed version, or adopt a pre-receipt copy +``` + +`--force` is an alias for `--replace`. A directory that is not an agent-bundle install of this +plugin is always refused with an installed-versus-artifact content-hash comparison; remove it +manually. The optional `agent-bundle` CLI applies the same policy through +`agent-bundle install cursor --from ./ [--replace]`. + +### Uninstall + +```sh +node ./install.mjs --uninstall --plan # print exactly what would be removed +node ./install.mjs --uninstall # remove the receipt-owned files; keep state/ +node ./install.mjs --uninstall --purge-data --confirm-purge # also remove durable runtime state +node ./install.mjs --uninstall --mode marketplace # remove a staged marketplace repository +``` + +Uninstall removes exactly what the receipt owns: the listed files, the directories the installer +created (including `~/.cursor/plugins/local` when the installer made it), and nothing else. Durable +runtime state under `state/` (state kernel, notices journal) — and, for an Agent Plugins pack with a stdio +server, the `~/.cursor/agent-bundle/plugin-data/` directory the receipt records as `PLUGIN_DATA` — is kept +unless `--purge-data --confirm-purge` is passed (a kept data directory leaves a remnant receipt behind so a later +purge still finds it; an empty one is pruned); unowned files are left in place and listed. A supported older +receipt with no recorded state location retains the current environment's default as unproven; a keep-data run +cannot turn that observation into later purge authority. A directory without a receipt is refused unless +`--force` (which removes a pre-receipt legacy copy by its inventory); owned content that no longer matches +the receipt is refused unless `--force`; a directory that is not this plugin's install is always refused. +A second run is a `Not installed` no-op. With the optional `agent-bundle` CLI, +`agent-bundle uninstall cursor --from ./ [--mode marketplace]` applies the same policy, and +`agent-bundle doctor --from ./` shows the lifecycle stage (placed, registered, enabled, active) with +unobservable stages typed `unavailable`. + +### Marketplace plugin + +```sh +node ./install.mjs --mode marketplace +``` + +It stages a committed Git repository at `~/.cursor/agent-bundle/marketplaces/gbot` whose +`.cursor-plugin/marketplace.json` lists this plugin, then prints the exact Cursor step: Customize -> Plugins -> +"Add Plugins from Local Repository" -> select that directory -> Install. Cursor then shows the plugin as a +marketplace install (not "local") and manages it from Customize. `git` must be on PATH. Verify in Cursor: +Customize -> Plugins lists the plugin, and its files appear under `~/.cursor/plugins/cache`. The optional +`agent-bundle` CLI performs the same check with `agent-bundle doctor --host cursor`. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` + +### Other recorded clients + +Each line below is pinned to that client's own documentation on the date shown, and names only the +paths this build actually wrote. Recognizing a document and running what it configures are separate: +`mcp` records that the client reads the emitted `mcp.json` as MCP configuration, while `placeholders` +records that it expands the reserved `${PLUGIN_ROOT}` / `${PLUGIN_DATA}` and provides them to the +process it spawns. A client can do the first without the second, and then a plugin-relative server +is configured but not runnable there. + +- **Antigravity** (docs retrieved 2026-09-06; no product or CLI version is published on any page) loads nothing from this bundle as published. Not loaded: manifest, skills, mcp, placeholders, hooks. +- **Cascade (Devin Desktop)** (docs.devin.ai/desktop retrieved 2026-09-06; Windsurf renamed to Devin Desktop, Cascade documented as the legacy agent beside the Devin Local agent) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `cp -R skills/ .agents/skills/`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: the emitted package root is not a Cascade discovery root; each skill directory is copied into .windsurf/skills/, ~/.codeium/windsurf/skills/, or .agents/skills/ before Cascade sees it, and the copy is what loads. +- **Cline** (@cline/cli 0.0.13 exercised 2026-09-06; docs.cline.bot retrieved 2026-09-06 (@cline/sdk 0.0.82)) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `cp -R skills/ ~/.cline/skills/`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: the skill tree must be copied into one of Cline's own roots; the emitted package is not a Cline install unit, and no CLI verb in @cline/cli 0.0.13 performs the copy. +- **CodeWhale** (Hmbown/CodeWhale main 19d34a5fb6c07b34e0b7234beb74a1cf1969efb4, docs retrieved 2026-09-06 (native Agent Plugins v1.0.0 support since v0.9.4)) loads this bundle as one plugin. Reads: `mcp.json`, `plugin.json`, `skills`. Install: `/plugin install ./`. Not loaded: placeholders, hooks. + - Partial `mcp`: 2026-09-06: CodeWhale narrows the standard at the plugin boundary. Its env rule — "Local stdio environment entries must use exact ${SOURCE_ENV} references" — rejects an emitted env value that is anything other than one whole variable reference. A remote server emitted into mcp.json is narrower still: the URL must be HTTPS (or explicit loopback HTTP) with no user information, query, or fragment, a literal header is rejected in favor of CodeWhale's own env_headers or bearer_token_env_var keys, redirects must stay on the reviewed origin, and the bundle must declare exactly the normalized endpoint host set in capabilities.network_hosts. That declaration rides in extensions["net.codewhale"], which this projection writes only when the author authors portable.extensions; a remote server emitted without it is a validation error, and "an active bundle must be … free of validation errors", so the whole bundle stays inactive there until the author declares the matching host set. +- **GitHub Copilot CLI** (@github/copilot 1.0.83, installed and exercised 2026-09-06) loads this bundle as one plugin. Reads: `plugin.json`, `skills`. Install: `copilot plugin install `. Not loaded: hooks. This build also writes `.mcp.json`, which it uses for mcp instead. A root that also carries `.plugin/plugin.json` uses it for manifest and still reads the rest. +- **Devin CLI** (Agent Plugins 1.0.0; docs retrieved 2026-09-06, plugins documented as closed beta) loads this bundle as one plugin, but this build also writes `.claude-plugin/plugin.json`, which it reads as the plugin instead. +- **Gemini CLI** (@google/gemini-cli 0.58.0, installed and exercised 2026-09-06) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `gemini skills install /skills/`. Not loaded: manifest, mcp, placeholders, hooks. +- **Grok Build** (xai-org/grok-build main 72a61251fcffb464bcc687aeb5a998e5a98ec0c9, docs retrieved 2026-09-06) loads the components it recognizes without reading the manifest. Reads: `skills`. Install from a marketplace (no local-directory install is verified for this artifact): `grok plugin install --trust`. Not loaded: manifest, mcp, placeholders, hooks. +- **Hermes Agent** (hermes-agent.nousresearch.com developer guide retrieved 2026-09-06; no version is printed on the page) loads this bundle as one plugin. Reads: `mcp.json`, `plugin.json`, `skills`. Install from a Git repository (no local-directory install is verified for this artifact): `hermes plugins install / --no-enable`. Not loaded: hooks. + - Partial `manifest`: 2026-09-06: the validation rule set is not published: the page never states that the manifest root is treated as closed or what happens to an unknown root key. + - Partial `placeholders`: 2026-09-06: the expansion sites are unpublished — the page does not say whether ${PLUGIN_ROOT} and ${PLUGIN_DATA} are expanded in args, env values, and cwd as §9.1 requires, only that the variables are provided. +- **JetBrains Junie** (junie.jetbrains.com/docs retrieved 2026-09-06, agent-skills page dated 01 September 2026; no CLI version is published on the page) loads the components it recognizes without reading the manifest. Reads: `skills`. Register: `junie --skill-location /skills`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: the emitted skills/ root is not a default location, so it loads only once registered with --skill-location or the skill-locations config field, and "if a project-level and a user-level skills have the same name, the user-level skill will be skipped". +- **Kiro (Powers)** (kiro.dev/docs/powers pages updated September 2, 2026 and August 4, 2026, retrieved 2026-09-06) loads this bundle as one plugin. Reads: `mcp.json`, `plugin.json`, `skills`. Install: `Powers panel -> Add Custom Power -> Import power from a folder -> select -> Install`. Not loaded: placeholders, hooks. + - Partial `manifest`: 2026-09-06: Kiro's "Required fields" table additionally requires version, description, author, and keywords, where the canonical schema requires only $schema and name — so a bundle that declares no portable author or keywords metadata does not meet Kiro's tightened manifest, and Kiro publishes no validation-error behavior to say what happens then. + - Partial `mcp`: 2026-09-06: only stdio is documented for a power's mcp.json; no Kiro page states that a streamable-http server in that file is read, so an emitted remote server is unproven there. +- **OpenClaw** (Agent Plugins 1.0.0; docs retrieved 2026-09-06) loads this bundle as one plugin, but this build also writes `.claude-plugin/plugin.json`, which it reads as the plugin instead. +- **OpenCode** (opencode-ai 1.18.29 exercised 2026-09-06; opencode.ai/docs retrieved 2026-09-06) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `cp -R skills/ .agents/skills/`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: the skill tree must be copied into one of OpenCode's own roots; the emitted package as a whole is not an OpenCode install unit, and skill names must be unique across all roots ("Ensure skill names are unique across all locations"). +- **Pi** (@mariozechner/pi-coding-agent 0.73.1 installed from npm 2026-09-07; packaged docs/skills.md and docs/packages.md read from that release) loads the components it recognizes without reading the manifest. Reads: `skills`. Register: `pi --skill /skills`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-07: the emitted skills/ root is not one of the scanned default roots, so it loads only when it is named with --skill or added to the `skills` settings array; discovery inside it is recursive once named. +- **Qoder CLI** (docs retrieved 2026-09-06; no CLI version is published on any page) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `qoder plugins install --scope user`. Not loaded: manifest, placeholders, hooks. This build also writes `.mcp.json`, which it uses for mcp instead. +- **Swival** (docs retrieved 2026-09-06; no product version is published on the documentation pages) loads the components it recognizes without reading the manifest. Reads: `skills`. Register: `swival --skills-dir /skills ""`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: the emitted skills/ root is not a default location, so it loads only once registered with --skills-dir or the swival.toml skills_dir field, and it loses by name to the default roots: "If the same skill name exists in multiple locations, the first one in the precedence order wins", with .swival/skills/ and .agents/skills/ ahead of --skills-dir paths. A registered tree outside the project resolves as external, which Swival adds "as read-only roots". +- **VS Code (Copilot agent plugins)** (code.visualstudio.com/docs/agent-customization/agent-plugins, page footer 9/2/2026, retrieved 2026-09-06) loads this bundle as one plugin. Reads: `mcp.json`, `plugin.json`, `skills`. Register: `"chat.pluginLocations": { "": true }`. Not loaded: placeholders, hooks. +- **Zed Agent** (zed.dev/docs retrieved 2026-09-06; no page publishes a version or last-updated date) loads the components it recognizes without reading the manifest. Reads: `skills`. Install: `cp -R skills/ ~/.agents/skills/`. Not loaded: manifest, mcp, placeholders, hooks. + - Partial `skills`: 2026-09-06: only the skill folders load, one copy at a time, and the catalog is capped — "50KB catalog budget… Skills that don't fit are dropped from the catalog with a warning in the UI" — so a large emitted skill set is not guaranteed to be wholly visible. + +### Cursor placeholder expansion + +Cursor 3.18.25 spawns the stdio servers of an Agent Plugins package without expanding +`${PLUGIN_ROOT}` / `${PLUGIN_DATA}` in `args`, `env` values, or `cwd`, without providing the +reserved `PLUGIN_ROOT` / `PLUGIN_DATA` variables (spec §9.1), with an omitted `cwd` defaulting to +the home directory, and with plugin-relative `./` commands resolved against the workspace folder +(spec §7.2.1). The installer therefore rewrites `mcp.json` in the Cursor copy only: the plugin root +becomes `~/.cursor/plugins/local/`, the data directory `~/.cursor/agent-bundle/plugin-data/` +(created by the installer), an omitted `cwd` becomes the plugin root, `./` commands resolve against +it, and every stdio server gains `PLUGIN_ROOT` / `PLUGIN_DATA` in its environment. The bundle itself +stays spec-conformant; the pre-expansion document is kept in `.agent-bundle-install.json` (`cursorExpansion`), +and the optional `agent-bundle doctor --host cursor` verifies the expanded paths (`AB7326`). Nothing is changed for +other clients; the recorded clients above name which of them expand the placeholders themselves. + +### Reinstall after a same-version rebuild + +The installer records an install receipt (`.agent-bundle-install.json`) and replaces its owned files in +place when the same version was rebuilt with different content; runtime state (`state/`) is never +touched. Pass `--replace` (alias `--force`) to replace a different installed version or to adopt a +copy installed before receipts existed. Foreign directories are refused with a content-hash +comparison. For a client that manages its own copy, remove and re-add the plugin through that client +when only content changed at the same version. + +### Uninstall + +```sh +node ./install.mjs --uninstall --plan # print exactly what would be removed +node ./install.mjs --uninstall # remove the receipt-owned files; keep state/ +node ./install.mjs --uninstall --purge-data --confirm-purge # also remove durable runtime state +``` + +Uninstall removes exactly what the receipt owns (files, installer-created directories) and keeps +durable runtime state under `state/` (and the recorded `PLUGIN_DATA` directory of an Agent Plugins pack) +unless `--purge-data --confirm-purge` is passed. A missing +receipt or modified owned content is refused unless `--force`; foreign directories are always refused. diff --git a/artifact/agent-bundle.compile-evidence.json b/artifact/agent-bundle.compile-evidence.json new file mode 100644 index 0000000..92aa812 --- /dev/null +++ b/artifact/agent-bundle.compile-evidence.json @@ -0,0 +1 @@ +{"assets":[{"externals":[{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"async_hooks","userRequest":"async_hooks"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"crypto","userRequest":"crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/736.js","node_modules/@agent-bundle/runtime/dist/index.js"],"kind":"builtin","request":"node:async_hooks","userRequest":"node:async_hooks"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/302.js"],"kind":"builtin","request":"node:buffer","userRequest":"node:buffer"},{"externalType":"module","issuers":["src/cli/codex/bridge/run.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:child_process","userRequest":"node:child_process"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/gateway.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:crypto","userRequest":"node:crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/conversation.js","src/core/desktop-shim.js","src/core/history.js","src/core/store.js"],"kind":"builtin","request":"node:fs","userRequest":"node:fs"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/40.js","src/cli/skills/add.tsx","src/core/relay/managed.js"],"kind":"builtin","request":"node:fs/promises","userRequest":"node:fs/promises"},{"externalType":"module","issuers":["src/core/codex-bridge.js","src/core/relay/control.js"],"kind":"builtin","request":"node:net","userRequest":"node:net"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/history.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:os","userRequest":"node:os"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/cli/skills/add.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/history.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:path","userRequest":"node:path"},{"externalType":"module","issuers":["src/core/history.js"],"kind":"builtin","request":"node:readline","userRequest":"node:readline"},{"externalType":"module","issuers":["src/core/relay/control.js"],"kind":"builtin","request":"node:string_decoder","userRequest":"node:string_decoder"},{"externalType":"module","issuers":[".agent-bundle-virtual/bin-gbot-flight-entry.mjs","src/core/relay/managed.js"],"kind":"builtin","request":"node:url","userRequest":"node:url"},{"externalType":"module","issuers":[".agent-bundle-virtual/bin-gbot-flight-entry.mjs"],"kind":"builtin","request":"node:worker_threads","userRequest":"node:worker_threads"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"stream","userRequest":"stream"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"util","userRequest":"util"}],"packages":["@agent-bundle/runtime","effect","react","react-dom","react-server-dom-rspack","rsc-markdown-stream","zod"],"path":"bin/gbot-flight.mjs","sha256":"814c0708905947e1d703498c2d36b554eff6753ca74da23122845b61182301fd"},{"externals":[{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/736.js","node_modules/@agent-bundle/runtime/dist/index.js"],"kind":"builtin","request":"node:async_hooks","userRequest":"node:async_hooks"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/302.js"],"kind":"builtin","request":"node:buffer","userRequest":"node:buffer"},{"externalType":"module","issuers":["src/cli/codex/bridge/run.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:child_process","userRequest":"node:child_process"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/agent-bundle/dist/667~1.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/gateway.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:crypto","userRequest":"node:crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/agent-bundle/dist/launch-env.js","node_modules/agent-bundle/dist/terminal-capability.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/conversation.js","src/core/desktop-shim.js","src/core/history.js","src/core/store.js"],"kind":"builtin","request":"node:fs","userRequest":"node:fs"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/40.js","node_modules/agent-bundle/dist/667~1.js","src/cli/skills/add.tsx","src/core/relay/managed.js"],"kind":"builtin","request":"node:fs/promises","userRequest":"node:fs/promises"},{"externalType":"module","issuers":["src/core/codex-bridge.js","src/core/relay/control.js"],"kind":"builtin","request":"node:net","userRequest":"node:net"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/history.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:os","userRequest":"node:os"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/agent-bundle/dist/launch-env.js","src/cli/skills/add.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/history.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:path","userRequest":"node:path"},{"externalType":"module","issuers":["src/core/history.js"],"kind":"builtin","request":"node:readline","userRequest":"node:readline"},{"externalType":"module","issuers":["src/core/relay/control.js"],"kind":"builtin","request":"node:string_decoder","userRequest":"node:string_decoder"},{"externalType":"module","issuers":[".agent-bundle-virtual/bin-gbot-0.mjs",".agent-bundle-virtual/bin-gbot-entry.mjs","src/core/relay/managed.js"],"kind":"builtin","request":"node:url","userRequest":"node:url"},{"externalType":"module","issuers":[".agent-bundle-virtual/bin-gbot-entry.mjs"],"kind":"builtin","request":"node:worker_threads","userRequest":"node:worker_threads"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js"],"kind":"builtin","request":"util","userRequest":"util"}],"packages":["@agent-bundle/runtime","agent-bundle","effect","react","react-dom","react-server-dom-rspack","rsc-markdown-stream","zod"],"path":"bin/gbot.mjs","sha256":"af6f18e83e884b1edd5d4c8290838f46908d239d22bf86927de7376ec88f5f2f"},{"externals":[{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"async_hooks","userRequest":"async_hooks"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"crypto","userRequest":"crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/736.js","node_modules/@agent-bundle/runtime/dist/index.js"],"kind":"builtin","request":"node:async_hooks","userRequest":"node:async_hooks"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/302.js"],"kind":"builtin","request":"node:buffer","userRequest":"node:buffer"},{"externalType":"module","issuers":["src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:child_process","userRequest":"node:child_process"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/gateway.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:crypto","userRequest":"node:crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/conversation.js","src/core/desktop-shim.js","src/core/store.js"],"kind":"builtin","request":"node:fs","userRequest":"node:fs"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/40.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:fs/promises","userRequest":"node:fs/promises"},{"externalType":"module","issuers":["src/core/codex-bridge.js","src/core/relay/control.js"],"kind":"builtin","request":"node:net","userRequest":"node:net"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:os","userRequest":"node:os"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:path","userRequest":"node:path"},{"externalType":"module","issuers":["src/core/relay/control.js"],"kind":"builtin","request":"node:string_decoder","userRequest":"node:string_decoder"},{"externalType":"module","issuers":[".agent-bundle-virtual/mcp-grok-bot-b8c2461e-flight-entry.mjs","src/core/relay/managed.js"],"kind":"builtin","request":"node:url","userRequest":"node:url"},{"externalType":"module","issuers":[".agent-bundle-virtual/mcp-grok-bot-b8c2461e-flight-entry.mjs"],"kind":"builtin","request":"node:worker_threads","userRequest":"node:worker_threads"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"stream","userRequest":"stream"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"],"kind":"builtin","request":"util","userRequest":"util"}],"packages":["@agent-bundle/runtime","agent-bundle","effect","react","react-dom","react-server-dom-rspack","rsc-markdown-stream","zod"],"path":"mcp/mcp-grok-bot-b8c2461e-flight.mjs","sha256":"8e1f5447c6aa03da02c6cc1dcfea6ede06e0a7ac5d2196fe1d52d4ed5970e9dd"},{"externals":[{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/736.js","node_modules/@agent-bundle/runtime/dist/index.js"],"kind":"builtin","request":"node:async_hooks","userRequest":"node:async_hooks"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/302.js"],"kind":"builtin","request":"node:buffer","userRequest":"node:buffer"},{"externalType":"module","issuers":["src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:child_process","userRequest":"node:child_process"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/@agent-bundle/runtime/dist/lineage.js","node_modules/agent-bundle/dist/667~1.js","node_modules/agent-bundle/dist/mcp-server-runtime.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/gateway.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:crypto","userRequest":"node:crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/agent-bundle/dist/launch-env.js","node_modules/agent-bundle/dist/terminal-capability.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/conversation.js","src/core/desktop-shim.js","src/core/store.js"],"kind":"builtin","request":"node:fs","userRequest":"node:fs"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/40.js","node_modules/agent-bundle/dist/667~1.js","src/core/relay/managed.js"],"kind":"builtin","request":"node:fs/promises","userRequest":"node:fs/promises"},{"externalType":"module","issuers":["src/core/codex-bridge.js","src/core/relay/control.js"],"kind":"builtin","request":"node:net","userRequest":"node:net"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:os","userRequest":"node:os"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/49.js","node_modules/agent-bundle/dist/launch-env.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:path","userRequest":"node:path"},{"externalType":"module","issuers":["node_modules/@modelcontextprotocol/server/dist/shimsNode.mjs"],"kind":"builtin","request":"node:process","userRequest":"node:process"},{"externalType":"module","issuers":["src/core/relay/control.js"],"kind":"builtin","request":"node:string_decoder","userRequest":"node:string_decoder"},{"externalType":"module","issuers":[".agent-bundle-virtual/mcp-grok-bot-b8c2461e-1.mjs",".agent-bundle-virtual/mcp-grok-bot-b8c2461e-2.mjs","src/core/relay/managed.js"],"kind":"builtin","request":"node:url","userRequest":"node:url"},{"externalType":"module","issuers":["node_modules/agent-bundle/dist/mcp-server-runtime.js"],"kind":"builtin","request":"node:worker_threads","userRequest":"node:worker_threads"},{"externalType":"node-commonjs","issuers":["node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js","node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js"],"kind":"builtin","request":"util","userRequest":"util"}],"packages":["@agent-bundle/runtime","@modelcontextprotocol/core","@modelcontextprotocol/server","agent-bundle","effect","react","react-dom","react-server-dom-rspack","rsc-markdown-stream","zod"],"path":"mcp/mcp-grok-bot-b8c2461e.mjs","sha256":"db4bab649091f44a29bf1bfb55e2ef15a68ab80a18ed993415f89f1d51977bd7"},{"externals":[{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/state.js"],"kind":"builtin","request":"node:assert/strict","userRequest":"node:assert/strict"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/736.js"],"kind":"builtin","request":"node:async_hooks","userRequest":"node:async_hooks"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/302.js"],"kind":"builtin","request":"node:buffer","userRequest":"node:buffer"},{"externalType":"module","issuers":["src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js"],"kind":"builtin","request":"node:child_process","userRequest":"node:child_process"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/state/sqlite.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/gateway.js","src/core/relay/codex.js","src/core/relay/control.js","src/core/relay/engine.js","src/core/relay/profile.js","src/core/relay/records.js","src/core/relay/state.js","src/core/store.js"],"kind":"builtin","request":"node:crypto","userRequest":"node:crypto"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/state/sqlite.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/conversation.js","src/core/desktop-shim.js","src/core/relay/codex.js","src/core/store.js"],"kind":"builtin","request":"node:fs","userRequest":"node:fs"},{"externalType":"module","issuers":["src/core/relay/ownership.js","src/core/relay/state.js","src/core/relay/worker.js"],"kind":"builtin","request":"node:fs/promises","userRequest":"node:fs/promises"},{"externalType":"module","issuers":["src/core/codex-bridge.js","src/core/relay/control.js","src/core/relay/ownership.js","src/core/relay/worker.js"],"kind":"builtin","request":"node:net","userRequest":"node:net"},{"externalType":"module","issuers":["src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/engine.js","src/core/relay/profile.js","src/core/store.js"],"kind":"builtin","request":"node:os","userRequest":"node:os"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/state/sqlite.js","src/core/app-session.js","src/core/codex-bridge.js","src/core/desktop-shim.js","src/core/relay/engine.js","src/core/relay/ownership.js","src/core/relay/profile.js","src/core/relay/state.js","src/core/store.js"],"kind":"builtin","request":"node:path","userRequest":"node:path"},{"externalType":"import","issuers":["src/core/relay/ownership.js"],"kind":"builtin","request":"node:sqlite","userRequest":"node:sqlite"},{"externalType":"module","issuers":["node_modules/@agent-bundle/runtime/dist/state/sqlite.js"],"kind":"builtin","request":"node:sqlite","userRequest":"node:sqlite"},{"externalType":"module","issuers":["src/core/relay/control.js","src/core/relay/worker.js"],"kind":"builtin","request":"node:string_decoder","userRequest":"node:string_decoder"}],"packages":["@agent-bundle/runtime","effect","react","zod"],"path":"scripts/gbot-relay.mjs","sha256":"ca34a124ea75ee0e4fbff64fa4bd907865335cb303526c070bd29ad1048dfb1e"}],"coverage":{"rewritable":false,"unobserved":["import()","require()","require.resolve(…)","createRequire(…)(…)","import.meta.resolve(…)"]},"policy":{"name":"closed-world-externals","revision":1},"producer":{"name":"agent-bundle","rspack":"2.2.4","version":"0.2.1"}} diff --git a/artifact/agent-bundle.manifest.json b/artifact/agent-bundle.manifest.json new file mode 100644 index 0000000..9d32b9b --- /dev/null +++ b/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"application":{"description":"Message Grok Bot from Codex, Claude Code, and Cursor, with managed automatic replies and explicit Codex conversation links.","id":"plugin:gbot","name":"gbot","version":"0.9.0"},"compiler":{"adapters":[{"adapterRevision":"1.28.0","host":"claude","observedVersion":"2.1.260","schemas":[{"name":"hooks","revision":"2.1.260","sha256":"0cdfc5eb5201f2c3091768559ac82f4c563ccb1b7bce7a39d5f99e5f404654cb"},{"name":"lsp","revision":"2.1.260","sha256":"b4419c5d857267c7e2b21e3e1eb98b4fdc302c87109007190d3258e6ba7096e4"},{"name":"marketplace","revision":"2.1.260","sha256":"31ee4cc43ba5ce2be248030a69da2d31171550b2cc51c1fcb9f788a8ab92783d"},{"name":"mcp","revision":"2.1.260","sha256":"edd4770e41d6aee5beae1ff918d33139613a243e454ecbd52b72fa824be4a662"},{"name":"monitors","revision":"2.1.260","sha256":"6378d94b51fb7c784eaee178237008a03da0f889d0520d57486784954a1d484c"},{"name":"plugin","revision":"2.1.260","sha256":"2a976091b81ad07ae8eca57f6f9c5749efeba17fa089a0c12b6ca84d6e70f118"},{"name":"settings","revision":"2.1.260","sha256":"2bbca553621dbf9433a9b7d1ff7952543a368434f2d999a4e4e360b95b6d4c3d"},{"name":"theme","revision":"2.1.260","sha256":"9931264e6f5a1d4b3b854ce7a17d602c9ba1b57cc1991f1d3991b316eaa81ac2"}]},{"adapterRevision":"1.13.0","host":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"fbccce3ade39e1b077fcb440e60260de6e811e8c2d222b2ae0fe8fe47706b470"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"074c6c71966a3e6560ccbceb8d82ec6a40cb1eccee2f2d863fb4ef1e2276a814"}]},{"adapterRevision":"1.13.0","host":"cursor","observedVersion":"2026-08-28","schemas":[{"name":"hooks","revision":"2026-08-28","sha256":"06154b7afa0861df462130b988912b897e7ccf962b8dd20c09193100bcde5d81"},{"name":"marketplace","revision":"2026-08-28","sha256":"1aae96a24c2796419933bc8bfe3a1255394e7199c35740b36325e0ce6dbc253d"},{"name":"mcp","revision":"2026-08-28","sha256":"f3fa4615afefe004c4fbcc09e635d890df0f1ec0cb39540feab72cbd3a31d844"},{"name":"plugin","revision":"2026-08-28","sha256":"a393b758901803fcf5cfe0d77bda8a83e987d32c3377dfce2d9edf445af884ed"}]},{"adapterRevision":"1.10.0","host":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"producer":{"name":"agent-bundle","version":"0.2.1"},"project":{"configDigest":"888dd04deb2d2ea8e35639dd53deba7140f0f0f0be781f50dc29cf63945e0159","configPath":"agent-bundle.config.ts","modelDigest":"e32c0b87d992979b6850b86182c8e2dbb23a72f96872f939466d1b85a5b72ef9","packageName":"grok-bot-cli","packageVersion":"0.9.0","revision":"6a932849b0e244d8ab641641506d9f67e1c2de2b634189720532f9be37dc19bb","sourceInputs":[{"executable":false,"path":".changeset/clean-pugs-dream.md","sha256":"9e5518cbc2979fa3ed5939def562f5c3630434ff01a5069e1de15729b9e6a9a5"},{"executable":false,"path":".changeset/config.json","sha256":"0a97ce5d0488bada887ee9ea3726edecc727454b7da0294f1b5fe4947f48ee7c"},{"executable":false,"path":".changeset/README.md","sha256":"495bd4805f8362853bce99689c1cd75db8c475dfa38930619d2e197d7554db27"},{"executable":false,"path":".github/workflows/changeset.yml","sha256":"293f8c43e3d9806f92f4ab3f242f1ecfc65988f73fd6fcf13fbff6f8533a827c"},{"executable":false,"path":".github/workflows/ci.yml","sha256":"0157614be1e712cbe461c6df3a74db3eda502ac9f19e2a983971a13bc1a14d9b"},{"executable":false,"path":".github/workflows/release.yml","sha256":"cb78aed6074c8eb8938bd97f7d70bc3f57b8d303dea28344830229c6ebc2f1f0"},{"executable":false,"path":".gitignore","sha256":"3e8fdb390e0a40ebc680e14f015cfc607d92061f174dcea0c559ecad0da5058e"},{"executable":false,"path":".npmrc","sha256":"d83f12f7ebebf59d1d17bc1a800e1de5c96791ea8155406d43a5b59aeabdaaf8"},{"executable":false,"path":"agent-bundle.config.ts","sha256":"888dd04deb2d2ea8e35639dd53deba7140f0f0f0be781f50dc29cf63945e0159"},{"executable":false,"path":"AGENTS.md","sha256":"e18ce90a031c533e7226789b97f6bce4aa7994b672544e0f425d20cc3bc15d29"},{"executable":false,"path":"CHANGELOG.md","sha256":"b657e7ee4f8992d678ffe62ac748db2e3752bb3e0b01a787861667a9e4ad5dd7"},{"executable":false,"path":"demo/grok-bot-cli-demo.gif","sha256":"0fe01e15fd2abbbc5cc3313e42931d404d3a320764e22fdcfb995f1a45dd73cd"},{"executable":false,"path":"demo/grok-bot-cli-demo.mp4","sha256":"b6ed66e43616674096c2f0a4a4da46fe4693c681833eab013f872a66b9ff933c"},{"executable":false,"path":"docs/codex-busy-threads.md","sha256":"2c3f292e39582f1aa431aeb2a0732c433bb167be9a6d1df2a04a8064cce47e76"},{"executable":false,"path":"docs/codex-duplex-architecture.md","sha256":"792f1be8bad508b042c5813c1fc3b7ea5ac87032803227830666727306e55fa2"},{"executable":false,"path":"docs/verification/2026-09-15-duplex.md","sha256":"c7d97f709a3c2d851c0a24690321bbda161ec925b4143a456b9951e174bf75df"},{"executable":false,"path":"LICENSE","sha256":"bc48c8a0f6b6e45842e574c79a6b955fe683ed13f48a50cc08bcccdb1a59fe59"},{"executable":false,"path":"package-lock.json","sha256":"16bc2bd5c891cfae1cea0bafe50b599396d3115cd2fd1f5f1cae1085a2ca3459"},{"executable":false,"path":"package.json","sha256":"c0f88e48436c0c130a872a8df4ec6af58f3cca6bb35a62d4cd7c21ac711b9cc1"},{"executable":false,"path":"README.md","sha256":"754b0438d4f973e9dfe755b56a4dfe29d65328a97be607f1790caac2413d57b0"},{"executable":false,"path":"renovate.json","sha256":"e80b4e42a3043bc12fa0640db4bac392d2bf770acf841360d7c8ceeeac2ec1a9"},{"executable":false,"path":"rstest.route-unit.config.ts","sha256":"7286e20dc3d4162673e7c3dfe824db00307e1fda178410f23044a97286d141f2"},{"executable":false,"path":"scripts/run-unit-tests.mjs","sha256":"58feb44330add2a4b04b3e8871bca0fa39ff48ed98e2f8295fb40af93c8e94d3"},{"executable":false,"path":"src/cli/_shared.ts","sha256":"555210759d9b2e2e60a01452c137abd73bad42bfab8b2311b66a3ab97f4ee5e9"},{"executable":false,"path":"src/cli/approvals/list.tsx","sha256":"8d21320b6cd9d6b2a266fd30196b8a439960f865a6f0a5dacf5845d64ed7388c"},{"executable":false,"path":"src/cli/approvals/respond.tsx","sha256":"7d9fe6e641deb08f444684733daac6da47fb472d90ed0e9ff77892f376a87255"},{"executable":false,"path":"src/cli/bots/create.tsx","sha256":"9f7a73a0595b642dd77f008ad596bcafd00fc5846ec1abff2ce62819d983eb84"},{"executable":false,"path":"src/cli/bots/delete.tsx","sha256":"126b53ac1da4a657f22d1a6770ddbab2cc66715c811de0873d50016bbe39cbf2"},{"executable":false,"path":"src/cli/bots/get.tsx","sha256":"f0c752a3b498819083a8ee5aa918d275727f1cc94d8774d8c84ac74db66e8a71"},{"executable":false,"path":"src/cli/bots/list.tsx","sha256":"21c0f7e39005860dfc2514b71f745bb4cab29d409ef2cff26f8759bb0fd261c1"},{"executable":false,"path":"src/cli/bots/update.tsx","sha256":"33b7f5aafbf931cf3cb5ecf423a76dacd09adb117a7d5490050639ae7f4210dd"},{"executable":false,"path":"src/cli/codex/bridge/respond.tsx","sha256":"9d3a6af4904af6e44583dfb4ef317b3fe1045a78e765fc27406eaca9bcadcd13"},{"executable":false,"path":"src/cli/codex/bridge/run.tsx","sha256":"a49d334bebb00db62ad2c54370a47ec2c9119b4c07eb6ba11fc4bba4dd8e4217"},{"executable":false,"path":"src/cli/codex/bridge/start.tsx","sha256":"9e423cf5d65168606f6235baa2bcd127eb949647f7a4dee284d75f831474524d"},{"executable":false,"path":"src/cli/codex/bridge/status.tsx","sha256":"c801f69080985c87025429fb136487acdfac093acb07241b3417ea9a83915a18"},{"executable":false,"path":"src/cli/codex/bridge/stop.tsx","sha256":"6710e298a21d124c442d5aa1a3744280e5cd4df93213797f2ea3c0654174184a"},{"executable":false,"path":"src/cli/codex/desktop-shim.tsx","sha256":"fa3d88d11895bc4a15700bd590c055aa392b2b0e0c1185c52da233a23589aba0"},{"executable":false,"path":"src/cli/codex/list-threads.tsx","sha256":"4419b29c5bc56f019e2835e3c8dbf4bc72291150900cfe2b8781a94c1482fe0f"},{"executable":false,"path":"src/cli/codex/queue.tsx","sha256":"7993ac5b827042cd95041775b183fde2d112b5ba7d5c82098e778a44e473826d"},{"executable":false,"path":"src/cli/codex/send.tsx","sha256":"6848001878471439bcc35a2c40010ecf0e57e61087879b1f4d6abb1be19e7924"},{"executable":false,"path":"src/cli/codex/status.tsx","sha256":"b8c31001cb2892c1bfccf502f9776ee06998eac4fc0356f92936fa2c34f272d8"},{"executable":false,"path":"src/cli/codex/wait.tsx","sha256":"c2ec45e5907e27ff0ab1885eceb2d62c33485b8d61f44ef871a24e7a7e8473ca"},{"executable":false,"path":"src/cli/codex/watch.tsx","sha256":"3280f42d15941cfd00b3727d9e271972c39165bd28db8f56acca5664d777cb4d"},{"executable":false,"path":"src/cli/doctor.tsx","sha256":"c30ce4e57fe707d36de29700abf5a2c56834bb4fb3adf2a70bb1089b4150ddc8"},{"executable":false,"path":"src/cli/groups/add.tsx","sha256":"2a5de115852f0ca6a6638300bd5006862a02a2f1e2f527b6fd680f610c1d777a"},{"executable":false,"path":"src/cli/groups/create.tsx","sha256":"da3f2539f338063daf51b80d86c27b2752f0e4a0334078d11508e27981590fa3"},{"executable":false,"path":"src/cli/groups/delete.tsx","sha256":"2d4e91113a2c24cefefcfd464513918791592b5e8734a4ef901eabe42c9c7289"},{"executable":false,"path":"src/cli/groups/get.tsx","sha256":"efed88fb3ab7292d60d6532f1f966f784ba3376b7826c9f3e5028467f86241e9"},{"executable":false,"path":"src/cli/groups/list.tsx","sha256":"f3cd229d41dd389b767447a04267700ab2293eae87a878f7d88149cb5798f4a6"},{"executable":false,"path":"src/cli/groups/members.tsx","sha256":"9b9eaecb65ea995006eff1b24a287110d16bf4830a0b0d07221c2f1317853641"},{"executable":false,"path":"src/cli/groups/remove.tsx","sha256":"96dd85d1b9732681ce9dc126ac3ae562d3f287f4c28e36b9a8f8c301dc93f63d"},{"executable":false,"path":"src/cli/groups/set.tsx","sha256":"4f9d90db612f14ddbb6d2afa5e45b66f044aed661ff95415e567e1be3b6108c6"},{"executable":false,"path":"src/cli/groups/update.tsx","sha256":"f44305815ddb6e27286f97ef68c04cfa5548acd5f04b1aba10ee7ce3cdbfc851"},{"executable":false,"path":"src/cli/history.tsx","sha256":"5151b48113b4ba0516bacabfabcd48e3256ead807c34d914deb84f31ded0b062"},{"executable":false,"path":"src/cli/send.tsx","sha256":"fd16790cfcde1c15328c3979acc0664112d5cf40d3f00a24da906e00dd63153e"},{"executable":false,"path":"src/cli/skills/add.tsx","sha256":"fbde237d172c026d7912174e705c03cbc9d74dad7806fc58c6ceb43127c69ba6"},{"executable":false,"path":"src/cli/skills/list.tsx","sha256":"34f255687c69aaf598a1dc54220453b57c46ed9ab4a168648d9c7eca6535ebae"},{"executable":false,"path":"src/cli/skills/remove.tsx","sha256":"21662c80a62f276c2dfd840a328e9665c0c5f63959a239d4dd877372c46f60d0"},{"executable":false,"path":"src/cli/thread.tsx","sha256":"29ab775936fa2987cb789754a44888fc52bdaad07180c5471122dda508cfd0c2"},{"executable":false,"path":"src/core/app-session.js","sha256":"2b2eb53ec3f4c7ea0dccf269fa9720af6f1ce36b8ca36e889d2bb271a092717d"},{"executable":false,"path":"src/core/codex-bridge.js","sha256":"02a0127f935a8c83d85ce1cf434d1a6fbecb3271ec3cd1c744b9175d2a5b88bb"},{"executable":false,"path":"src/core/codex/contract.js","sha256":"96e80f91c323df150d08a477abe6697b287cd7a1b11e98d17cb15f682fa46012"},{"executable":false,"path":"src/core/codex/conversation.js","sha256":"2eb3dc85807c4889e72e18a82ebfe7ea6d43a114ed961a06f970a593a6785983"},{"executable":false,"path":"src/core/codex/routes.ts","sha256":"bc220bf4111305e7fcaf46756b531ac2aabc1d12c87f89184ba5f670b11229ab"},{"executable":false,"path":"src/core/commands.js","sha256":"3ad8fafb86744a57992da93ad838ade0e9acb1b7ca09b829cefadbf2781be0c9"},{"executable":false,"path":"src/core/desktop-shim-bridge.js","sha256":"58f3f39b8527adf58f57313e02e34322b203b8c38d1acfbad419a8b9af214443"},{"executable":false,"path":"src/core/desktop-shim.js","sha256":"500b8617bade6fa1a9c395826e197892fb864067044cac80ab025849f8fd6f82"},{"executable":false,"path":"src/core/format.js","sha256":"83ee15f73a87ef24b75f7782f3b61dd4ef4cc1f2e01e38cdf19825b805fab3be"},{"executable":false,"path":"src/core/gateway.js","sha256":"3a4f838ee423600d29e05f58060dcaf81cdcea4ac93b36dd6108363ac24bc606"},{"executable":false,"path":"src/core/grok-approval-routes.ts","sha256":"a33daa4d05e0c2594c795bd7654c22f3e1003e4aaad41cd70034d03651dd01f9"},{"executable":false,"path":"src/core/grok-approvals.js","sha256":"6b651a65bdd17241dd5b7a01d94a318ece9356c1c9b965b0578e08250d74e8fe"},{"executable":false,"path":"src/core/headers.js","sha256":"e229f2826ebdfb52949dab500798c0fa8a5ff7c4e63de91a63103bf45d2ae3cc"},{"executable":false,"path":"src/core/history.js","sha256":"38ca8e8f8dcd2ad42952c424ea9f00be5972d8751e4c0ac87214171903d82d89"},{"executable":false,"path":"src/core/relay/codex.js","sha256":"827f4d209c0681d4ed973ef41e0b2264e64c38a43aecef279efe53713b129f0e"},{"executable":false,"path":"src/core/relay/completion.js","sha256":"9d1a47f92716d1ccc7c4f44d92a580084f3b622c6ac0f20c6391be81abeb56e4"},{"executable":false,"path":"src/core/relay/control.js","sha256":"3645540f9f799b8742e0d5782b6324454a1486a780f6cb97260b96ef62411771"},{"executable":false,"path":"src/core/relay/engine.js","sha256":"205dd43b337439a56c7b1521b2603679ebc7fd3b2da430f8a477f83549efd453"},{"executable":false,"path":"src/core/relay/intake.js","sha256":"b31146fe3c9edd2f09323a454687403666591b6c12483a55b07ac610d2e3610a"},{"executable":false,"path":"src/core/relay/interactions.js","sha256":"6b576ed3a5b6659bc17e384d26e40d6ccb41b118b3a91cf5c902e9758ccbc1b1"},{"executable":false,"path":"src/core/relay/managed.js","sha256":"dbe03ed964bd09739e580de73b7e9f90508062fa2e53b8244c6ca7f78fc7a60d"},{"executable":false,"path":"src/core/relay/ownership.js","sha256":"74805f04f6a8bc02b2951614c4814aa42f54aaa3abca027a2413ed5a54814caf"},{"executable":false,"path":"src/core/relay/profile.js","sha256":"3347d1d493d3470d82722468d31571464d8e11aa0b4deac5bda75f574078dfe5"},{"executable":false,"path":"src/core/relay/records.js","sha256":"c6ffc479436282348a491e0f18b1b0e2944deb0619e025484ab6a8d25ec3c2c5"},{"executable":false,"path":"src/core/relay/routes.ts","sha256":"0e00c45a87cea0af5faa7e21a681371708e88140659747bd8a068a8dd10eccc8"},{"executable":false,"path":"src/core/relay/state.js","sha256":"f803d955619387306852a2965a75afc26804a982309dd04c9564e5ae31d638d2"},{"executable":false,"path":"src/core/relay/worker.js","sha256":"4176ad91872f36f7ea6565d9f30d23d9d7a80ef27d7af975af760457132ba148"},{"executable":false,"path":"src/core/store.js","sha256":"caefeeebf686cecd37ef19585ef0a5d3acba9dbf1564fe128c3afe4de067305c"},{"executable":false,"path":"src/core/transcript.js","sha256":"0355f0978d2d126b90858e3f661130243fc4730ee81ba13080af1dfa39d8b081"},{"executable":false,"path":"src/core/url-policy.js","sha256":"62bf6d3c8af1f5840d5e2d682d8f2e52fcbfbee6695728b47ed31816f1736089"},{"executable":false,"path":"src/gbot-install.ts","sha256":"e3c833d7662610e70e65232e541017229fb9a049eacee0bdf31e2c33c6ab7189"},{"executable":false,"path":"src/gbot.ts","sha256":"c89a37b764956ceacb2917a991a6d82d987ed8d8e453c8d553485bbd7f3edcc0"},{"executable":false,"path":"src/mcp/grok-bot/tools/codex_send.tsx","sha256":"59d6ecff2d64247013d78e38372601591c083816ff6475dfa31d77b7d3ad29ca"},{"executable":false,"path":"src/mcp/grok-bot/tools/codex_threads.tsx","sha256":"7f1377fcb0cc14c43b47584094350596e77dcddaf835975e42b7caa7d2739bdd"},{"executable":false,"path":"src/mcp/grok-bot/tools/codex_wait.tsx","sha256":"fe1601ba242c82bdc34963caea4eb8aa7c9a9bc1fbb14ea16622a502674cf102"},{"executable":false,"path":"src/mcp/grok-bot/tools/codex_watch.tsx","sha256":"1471575be5e16426e6386ce14dbbc7950717056ae51e75d985e2f79cb4de0e17"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_bridge_start.tsx","sha256":"c75c5c8a30ec43709a4d32baa8c3bc9796595381bb04fd2499ca30cd515c5a0b"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_bridge_status.tsx","sha256":"486ce643b35cfa2eabf78f0deeabce7198adc66133669eec630e1d12206ad642"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_bridge_stop.tsx","sha256":"371428a6e4b4e1312dd95d9681c29e765aec55e65d80d7c474535df838a43457"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_codex_respond.tsx","sha256":"030e9c2081ed4ed40732b098c929022af3083f609f10934b35e1f428d33ae637"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_grok_approvals.tsx","sha256":"17f164acdc48d6bc79a4c5044c7082760dd2a1646e5b56f6bff54c53fed96451"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_grok_respond.tsx","sha256":"41964bb8cf0eb0f8493afa1dde16cd94c4f589d1a7e410577d1ed63ec4648542"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_send.tsx","sha256":"2101d279a0e6bda2d57ba3da5366411df460a95692d4e64a1096880a89121d9a"},{"executable":false,"path":"src/mcp/grok-bot/tools/gbot_thread.tsx","sha256":"ef4aefec7243efaad18335e8508c7c17af0cd9b0f8a4b3693a7af9f666807fd6"},{"executable":false,"path":"src/scripts/gbot-relay.ts","sha256":"6690e316189ed8ebba43ea67a495338c927e4c0c21a9f896b7b2fecc8c6eb656"},{"executable":false,"path":"src/skills/talk-to-grok-bot/SKILL.md","sha256":"c671dd4a6bc29defa919fffeacf105420000e287ee727217c4baea968b3834a7"},{"executable":false,"path":"test/app-session.test.js","sha256":"0756b691703dd8c84bf0823f2afab16c6b158398e4ce6be229db6f459a0bbdb1"},{"executable":false,"path":"test/codex-bridge.test.js","sha256":"4ca47489c5794390c97d286ead62c2465abaa7125b16b924bff6e9e68a3e6a46"},{"executable":false,"path":"test/codex-contract.test.js","sha256":"926c7609679d8b6ac3b568d56ba5efa20df86d016a9031f085d19adbfb0e9064"},{"executable":false,"path":"test/codex-conversation.test.js","sha256":"c11559a8c0206982d506bcb018f9421085b8fb17ed82a6b255faf276a30f3a69"},{"executable":false,"path":"test/codex-session.test.js","sha256":"b39fe6afe0784b16e37b208089279dea01095d33e06ae26a1b60871796c7738a"},{"executable":false,"path":"test/codex-surfaces.test.js","sha256":"56d1b6550cc69d462a05e892cf82aa6a41495857b753215104e03207db514c81"},{"executable":false,"path":"test/connect-gateway.test.js","sha256":"5fabd87640b39e75c218300ca6be278268f248f3ff75e8cb72f9fade9eb0f7f3"},{"executable":false,"path":"test/desktop-shim.test.js","sha256":"89fb6c38a5fca5d41a96434cf9e8d51ae1d9992cf4f7930df0cc5840ef985705"},{"executable":false,"path":"test/doctor.test.js","sha256":"9685885df9e7363d3e077d246b1a17803c8899e9613b4a4d52ee4b9275e20694"},{"executable":false,"path":"test/gateway-groups.test.js","sha256":"14e227453e3e28c7cb60f91dba55733834c023ce9a914e40e22c68c899512bdc"},{"executable":false,"path":"test/gateway-send.test.js","sha256":"d059166153dde975f457e4e8c32ea08b0fc857b58fd48eab7da1959638e4fb05"},{"executable":false,"path":"test/gateway-skills.test.js","sha256":"feed62a884d1b7d12e358a27d73fb5587bcf761d4867ab1755d8bc34a4380069"},{"executable":false,"path":"test/gateway.test.js","sha256":"e5a7acd7ae347c82ef1e2a6000562767168e56d6f9d86aca8da46141731d1309"},{"executable":false,"path":"test/grok-approvals.test.js","sha256":"5ad4c548060a08dbe57949ab5ae240383fdb1709cd3694a909f5e1354fee3f73"},{"executable":false,"path":"test/helpers/codex-server.js","sha256":"432b4570601e94cf08c4861133d328404a97066642edb7ec0dbc314411a4d848"},{"executable":false,"path":"test/history.test.js","sha256":"eac4811f1b12d427df66996f33dd46bc3cbe31fc9fa030b3f32c571d5379f8dd"},{"executable":false,"path":"test/host-tool-inventory.test.js","sha256":"ce09bec4efcfac6860ab9defc5f32590c70ed81b664b1ba5346c167259b2be9e"},{"executable":false,"path":"test/pr69-integration.test.js","sha256":"a5dc99c11e2d3fcf18233c595f9c28301e5939f4b3657125eb3f970df2598840"},{"executable":false,"path":"test/relay-auth-recovery.test.js","sha256":"399c064f550fe33e166187a51da527728a97946d213377c8fcc8231378f5bbab"},{"executable":false,"path":"test/relay-codex.test.js","sha256":"43cb313e748e187f798a8a0bce5a01cce9ba360a52985b05ecededee9ad10581"},{"executable":false,"path":"test/relay-completion.test.js","sha256":"a8cc2402f82ce4b458074eafd32c8fa18f7ced7d85fdb6b7fa68f7b18b6a8c2e"},{"executable":false,"path":"test/relay-engine.test.js","sha256":"a3e7e4a63ec82014eec83b91d003ac89295d1f0ac3807bcf39071e4334bf2680"},{"executable":false,"path":"test/relay-gateway-lifecycle.test.js","sha256":"e16e7a34f7b6bb07965003e3018aa3a43ff192602db1c177bec9b6268fddb78b"},{"executable":false,"path":"test/relay-interactions.test.js","sha256":"83d70b1a813923fc6bae02b18d328107d0d04a6a761ab73b2051e3d114c7eaa5"},{"executable":false,"path":"test/relay-lifecycle.test.js","sha256":"e90130e1f609839bfd3f74c3edc333a22f37fe20dcde0146daa8d497133da4b7"},{"executable":false,"path":"test/relay-state.test.js","sha256":"c9143d5fa150b1ebcef9d515e161e25af3370b71eaf800a7b2bb1da1678b0bd3"},{"executable":false,"path":"test/relay-surfaces.test.js","sha256":"ba17ac4f1ffc02d4e06cd73eda143422a3d4d2f750630af9ed4e828dc9d7d2be"},{"executable":false,"path":"test/relay-worker.test.js","sha256":"6bd1bdaaaae59997132f289f822b6c4b8c9616c268fb2b45861e03f697c08197"},{"executable":false,"path":"test/release-config.test.js","sha256":"5d5dadb0bc6c201557fcff19fbeca02d385b1dd9e0a97bd2640c0a38693a5573"},{"executable":false,"path":"test/store.test.js","sha256":"5d4ae4295287539ef4b7f98d0ca0cd42a931a3c7b25b092fbd2b8f1a08ca4bac"},{"executable":false,"path":"test/test-runner.test.js","sha256":"966ff3b67edb8e1f03b50120d4d820ab0f871121e9b359609e73faae8446454f"},{"executable":false,"path":"test/transcript.test.js","sha256":"28795d9cc8e42653ac430d18e17ff1e6bc2feb1b7935fe5c69b336d58e1793ae"},{"executable":false,"path":"test/url-policy.test.js","sha256":"dacfe322e0cbff178c0d67a5f76b6bd8d9fef14aa57c09c697eb69fa0019629c"},{"executable":false,"path":"tests/route-unit/tools.test.ts","sha256":"942349e51cc56dac903625be3b43b3a54f3b2b7e25410b0e56ebd3f185e93549"},{"executable":false,"path":"tsconfig.json","sha256":"fa2ced6d1721e8280a6aed615717cffcef25f6e2d16e15889b2be2a9df4fc226"}]},"provenance":[{"path":".agents/plugins/marketplace.json","sourceInputs":["agent-bundle.config.ts"]},{"path":".claude-plugin/marketplace.json","sourceInputs":["agent-bundle.config.ts","package.json"]},{"path":".claude-plugin/plugin.json","sourceInputs":["agent-bundle.config.ts","src/mcp/grok-bot/tools/codex_send.tsx","src/skills/talk-to-grok-bot/SKILL.md"]},{"path":".codex-plugin/mcp.json","sourceInputs":["agent-bundle.config.ts","src/mcp/grok-bot/tools/codex_send.tsx"]},{"path":".codex-plugin/plugin.json","sourceInputs":["agent-bundle.config.ts","package.json","src/mcp/grok-bot/tools/codex_send.tsx","src/skills/talk-to-grok-bot/SKILL.md"]},{"path":".cursor-plugin/marketplace.json","sourceInputs":["agent-bundle.config.ts"]},{"path":".cursor-plugin/mcp.json","sourceInputs":["agent-bundle.config.ts","src/mcp/grok-bot/tools/codex_send.tsx"]},{"path":".cursor-plugin/plugin.json","sourceInputs":["agent-bundle.config.ts","package.json","src/mcp/grok-bot/tools/codex_send.tsx","src/skills/talk-to-grok-bot/SKILL.md"]},{"path":".mcp.json","sourceInputs":["agent-bundle.config.ts","src/mcp/grok-bot/tools/codex_send.tsx"]},{"path":"agent-bundle.compile-evidence.json","sourceInputs":["agent-bundle.config.ts"]},{"path":"bin/gbot-flight.mjs","sourceInputs":["agent-bundle.config.ts","package.json","src/cli/_shared.ts","src/cli/approvals/list.tsx","src/cli/approvals/respond.tsx","src/cli/bots/create.tsx","src/cli/bots/delete.tsx","src/cli/bots/get.tsx","src/cli/bots/list.tsx","src/cli/bots/update.tsx","src/cli/codex/bridge/respond.tsx","src/cli/codex/bridge/run.tsx","src/cli/codex/bridge/start.tsx","src/cli/codex/bridge/status.tsx","src/cli/codex/bridge/stop.tsx","src/cli/codex/desktop-shim.tsx","src/cli/codex/list-threads.tsx","src/cli/codex/queue.tsx","src/cli/codex/send.tsx","src/cli/codex/status.tsx","src/cli/codex/wait.tsx","src/cli/codex/watch.tsx","src/cli/doctor.tsx","src/cli/groups/add.tsx","src/cli/groups/create.tsx","src/cli/groups/delete.tsx","src/cli/groups/get.tsx","src/cli/groups/list.tsx","src/cli/groups/members.tsx","src/cli/groups/remove.tsx","src/cli/groups/set.tsx","src/cli/groups/update.tsx","src/cli/history.tsx","src/cli/send.tsx","src/cli/skills/add.tsx","src/cli/skills/list.tsx","src/cli/skills/remove.tsx","src/cli/thread.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/contract.js","src/core/codex/conversation.js","src/core/codex/routes.ts","src/core/commands.js","src/core/desktop-shim-bridge.js","src/core/desktop-shim.js","src/core/format.js","src/core/gateway.js","src/core/grok-approval-routes.ts","src/core/grok-approvals.js","src/core/headers.js","src/core/history.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/relay/routes.ts","src/core/store.js","src/core/transcript.js","src/core/url-policy.js","src/gbot.ts"]},{"path":"bin/gbot.mjs","sourceInputs":["agent-bundle.config.ts","package.json","src/cli/_shared.ts","src/cli/approvals/list.tsx","src/cli/approvals/respond.tsx","src/cli/bots/create.tsx","src/cli/bots/delete.tsx","src/cli/bots/get.tsx","src/cli/bots/list.tsx","src/cli/bots/update.tsx","src/cli/codex/bridge/respond.tsx","src/cli/codex/bridge/run.tsx","src/cli/codex/bridge/start.tsx","src/cli/codex/bridge/status.tsx","src/cli/codex/bridge/stop.tsx","src/cli/codex/desktop-shim.tsx","src/cli/codex/list-threads.tsx","src/cli/codex/queue.tsx","src/cli/codex/send.tsx","src/cli/codex/status.tsx","src/cli/codex/wait.tsx","src/cli/codex/watch.tsx","src/cli/doctor.tsx","src/cli/groups/add.tsx","src/cli/groups/create.tsx","src/cli/groups/delete.tsx","src/cli/groups/get.tsx","src/cli/groups/list.tsx","src/cli/groups/members.tsx","src/cli/groups/remove.tsx","src/cli/groups/set.tsx","src/cli/groups/update.tsx","src/cli/history.tsx","src/cli/send.tsx","src/cli/skills/add.tsx","src/cli/skills/list.tsx","src/cli/skills/remove.tsx","src/cli/thread.tsx","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/contract.js","src/core/codex/conversation.js","src/core/codex/routes.ts","src/core/commands.js","src/core/desktop-shim-bridge.js","src/core/desktop-shim.js","src/core/format.js","src/core/gateway.js","src/core/grok-approval-routes.ts","src/core/grok-approvals.js","src/core/headers.js","src/core/history.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/relay/routes.ts","src/core/store.js","src/core/transcript.js","src/core/url-policy.js","src/gbot.ts"]},{"path":"INSTALL.md","sourceInputs":["agent-bundle.config.ts"]},{"path":"install.mjs","sourceInputs":["agent-bundle.config.ts"]},{"path":"mcp.json","sourceInputs":["src/mcp/grok-bot/tools/codex_send.tsx"]},{"path":"mcp/mcp-grok-bot-b8c2461e-flight.mjs","sourceInputs":["package.json","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/contract.js","src/core/codex/conversation.js","src/core/codex/routes.ts","src/core/desktop-shim-bridge.js","src/core/desktop-shim.js","src/core/gateway.js","src/core/grok-approval-routes.ts","src/core/grok-approvals.js","src/core/headers.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/relay/routes.ts","src/core/store.js","src/core/transcript.js","src/core/url-policy.js","src/gbot.ts","src/mcp/grok-bot/tools/codex_send.tsx","src/mcp/grok-bot/tools/codex_threads.tsx","src/mcp/grok-bot/tools/codex_wait.tsx","src/mcp/grok-bot/tools/codex_watch.tsx","src/mcp/grok-bot/tools/gbot_bridge_start.tsx","src/mcp/grok-bot/tools/gbot_bridge_status.tsx","src/mcp/grok-bot/tools/gbot_bridge_stop.tsx","src/mcp/grok-bot/tools/gbot_codex_respond.tsx","src/mcp/grok-bot/tools/gbot_grok_approvals.tsx","src/mcp/grok-bot/tools/gbot_grok_respond.tsx","src/mcp/grok-bot/tools/gbot_send.tsx","src/mcp/grok-bot/tools/gbot_thread.tsx"]},{"path":"mcp/mcp-grok-bot-b8c2461e.mjs","sourceInputs":["package.json","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/contract.js","src/core/codex/conversation.js","src/core/codex/routes.ts","src/core/desktop-shim-bridge.js","src/core/desktop-shim.js","src/core/gateway.js","src/core/grok-approval-routes.ts","src/core/grok-approvals.js","src/core/headers.js","src/core/relay/control.js","src/core/relay/managed.js","src/core/relay/profile.js","src/core/relay/routes.ts","src/core/store.js","src/core/transcript.js","src/core/url-policy.js","src/gbot.ts","src/mcp/grok-bot/tools/codex_send.tsx","src/mcp/grok-bot/tools/codex_threads.tsx","src/mcp/grok-bot/tools/codex_wait.tsx","src/mcp/grok-bot/tools/codex_watch.tsx","src/mcp/grok-bot/tools/gbot_bridge_start.tsx","src/mcp/grok-bot/tools/gbot_bridge_status.tsx","src/mcp/grok-bot/tools/gbot_bridge_stop.tsx","src/mcp/grok-bot/tools/gbot_codex_respond.tsx","src/mcp/grok-bot/tools/gbot_grok_approvals.tsx","src/mcp/grok-bot/tools/gbot_grok_respond.tsx","src/mcp/grok-bot/tools/gbot_send.tsx","src/mcp/grok-bot/tools/gbot_thread.tsx"]},{"path":"plugin.json","sourceInputs":["agent-bundle.config.ts","package.json"]},{"path":"scripts/gbot-relay.mjs","sourceInputs":["package.json","src/core/app-session.js","src/core/codex-bridge.js","src/core/codex/contract.js","src/core/codex/conversation.js","src/core/desktop-shim-bridge.js","src/core/desktop-shim.js","src/core/gateway.js","src/core/grok-approvals.js","src/core/headers.js","src/core/relay/codex.js","src/core/relay/completion.js","src/core/relay/control.js","src/core/relay/engine.js","src/core/relay/intake.js","src/core/relay/interactions.js","src/core/relay/ownership.js","src/core/relay/profile.js","src/core/relay/records.js","src/core/relay/state.js","src/core/relay/worker.js","src/core/store.js","src/core/transcript.js","src/core/url-policy.js","src/scripts/gbot-relay.ts"]},{"path":"skills/talk-to-grok-bot/SKILL.md","sourceInputs":["src/skills/talk-to-grok-bot/SKILL.md"]}],"recordVersion":1,"validation":{"artifact":{"status":"passed"},"projections":[{"host":"claude","status":"passed"},{"host":"codex","status":"passed"},{"host":"cursor","status":"passed"},{"host":"portable","status":"passed"}],"source":{"status":"passed"}}},"distribution":{"channels":["local","npm"],"install":{"instructions":"INSTALL.md","script":"install.mjs"},"payloads":[]},"executables":{"bins":[{"hosts":["claude","codex","cursor","portable"],"name":"gbot","path":"bin/gbot.mjs","worker":"bin/gbot-flight.mjs"}],"hooks":[],"mcpServers":[{"apps":[],"hosts":["claude","codex","cursor","portable"],"id":"mcp:grok-bot","kind":"compiled","launch":{"args":[],"entry":"mcp/mcp-grok-bot-b8c2461e.mjs","env":{},"worker":"mcp/mcp-grok-bot-b8c2461e-flight.mjs"},"name":"grok-bot","transport":"stdio"}],"scripts":[{"hosts":["claude","codex","cursor","portable"],"id":"script:gbot-relay","mode":"bundle","name":"gbot-relay","path":"scripts/gbot-relay.mjs"}]},"files":[{"bytes":225,"kind":"generated","path":".agents/plugins/marketplace.json","sha256":"54d575719e003eb71ba2d7fb7379e12098243e701646e0ca83dba38ef2a78b1d"},{"bytes":729,"kind":"generated","path":".claude-plugin/marketplace.json","sha256":"c34ad145efb7252e387cb66825a2c7f28b71ec1199cc21b7a62e68f5eaf00c33"},{"bytes":199,"kind":"generated","path":".claude-plugin/plugin.json","sha256":"9f3c3ac18c027af51dec5571612a8cc1d77f4b590c216111be7ebb0a0395fce1"},{"bytes":156,"kind":"generated","path":".codex-plugin/mcp.json","sha256":"4b442017d0d30ec207cef7a4e5d2cd9dca246080008633459a27e3a5f2f7935b"},{"bytes":1015,"kind":"generated","path":".codex-plugin/plugin.json","sha256":"7089ffedb7a06970382f659207146f601723d412a0dcf81981d047557e0e04ec"},{"bytes":234,"kind":"generated","path":".cursor-plugin/marketplace.json","sha256":"c7f1a63855c76dd4680fa34c81b7e1170bb47be9bf1399dc8583b2d2d89eb9a0"},{"bytes":169,"kind":"generated","path":".cursor-plugin/mcp.json","sha256":"95c87d0f2ed3a4f6df7d0e519454b1234672eca030db3b8cd8776ef0f35dee74"},{"bytes":551,"kind":"generated","path":".cursor-plugin/plugin.json","sha256":"94693dbd9ecc58995dbb3581f8e5edfd62ea2db0e15ae49711775b4cf20f0338"},{"bytes":184,"kind":"generated","path":".mcp.json","sha256":"2539f66ffcb1c98a365f078c63122a1c25b7c7625f91314467843bde7628907b"},{"bytes":19841,"kind":"generated","path":"agent-bundle.compile-evidence.json","sha256":"36d1fe1f40b7e837cb7bc805c47014afd918f838a54931995f4d33516ad5f714"},{"bytes":1300907,"kind":"bundle","path":"bin/gbot-flight.mjs","sha256":"814c0708905947e1d703498c2d36b554eff6753ca74da23122845b61182301fd"},{"bytes":3162304,"kind":"bundle","mode":493,"path":"bin/gbot.mjs","sha256":"af6f18e83e884b1edd5d4c8290838f46908d239d22bf86927de7376ec88f5f2f"},{"bytes":22341,"kind":"generated","path":"INSTALL.md","sha256":"87d945aba4d2267bdd1e79be12c4c87842feb07e3cd394f69cb8ffa663b65632"},{"bytes":84117,"kind":"generated","path":"install.mjs","sha256":"761805b045027f6b226d1f91c5cb4229f6b20323d82f3f2c391490e09f8b8f53"},{"bytes":246,"kind":"generated","path":"mcp.json","sha256":"c06a01fa851792f42e0cc807a444e454c3ea2fd164dc1c2adef455acc93879e2"},{"bytes":1201808,"kind":"bundle","path":"mcp/mcp-grok-bot-b8c2461e-flight.mjs","sha256":"8e1f5447c6aa03da02c6cc1dcfea6ede06e0a7ac5d2196fe1d52d4ed5970e9dd"},{"bytes":4056758,"kind":"bundle","path":"mcp/mcp-grok-bot-b8c2461e.mjs","sha256":"db4bab649091f44a29bf1bfb55e2ef15a68ab80a18ed993415f89f1d51977bd7"},{"bytes":582,"kind":"generated","path":"plugin.json","sha256":"b623c1b69dd4674341091a90c634656f1460d08b0f051668f35c92232f89cbc0"},{"bytes":2108374,"kind":"bundle","path":"scripts/gbot-relay.mjs","sha256":"ca34a124ea75ee0e4fbff64fa4bd907865335cb303526c070bd29ad1048dfb1e"},{"bytes":7468,"kind":"copy","path":"skills/talk-to-grok-bot/SKILL.md","sha256":"c671dd4a6bc29defa919fffeacf105420000e287ee727217c4baea968b3834a7"}],"manifestVersion":6,"projections":[{"builtInHost":"claude","documents":{"marketplace":".claude-plugin/marketplace.json","mcp":".mcp.json","plugin":".claude-plugin/plugin.json"},"host":"claude","marketplace":{"name":"gbot-marketplace"}},{"builtInHost":"codex","documents":{"marketplace":".agents/plugins/marketplace.json","mcp":".codex-plugin/mcp.json","plugin":".codex-plugin/plugin.json"},"host":"codex","marketplace":{"name":"gbot-marketplace"}},{"builtInHost":"cursor","documents":{"marketplace":".cursor-plugin/marketplace.json","mcp":".cursor-plugin/mcp.json","plugin":".cursor-plugin/plugin.json"},"host":"cursor","marketplace":{"name":"gbot-marketplace"}},{"builtInHost":"portable","documents":{"mcp":"mcp.json","plugin":"plugin.json"},"host":"portable"}],"routes":{"cli":{"commands":[{"aliases":[],"description":"List current Grok approval cards (latest 200 entries).","exitCode":"zero","options":[{"key":"target","kind":"string","option":"target","positional":0,"repeated":false,"required":true}],"path":["approvals","list"],"routeId":"cli:approvals/list"},{"aliases":[],"description":"Explicit user decision: accept a Grok request once or decline; never grant persistent permissions.","exitCode":"zero","options":[{"choices":["accept","decline"],"key":"decision","kind":"enum","option":"decision","repeated":false,"required":true},{"key":"entryId","kind":"string","option":"entry-id","repeated":false,"required":true},{"key":"requestId","kind":"string","option":"request-id","repeated":false,"required":true},{"key":"target","kind":"string","option":"target","repeated":false,"required":true}],"path":["approvals","respond"],"routeId":"cli:approvals/respond"},{"aliases":[],"description":"Create a Grok Bot bot.","exitCode":"zero","options":[{"key":"avatarColor","kind":"string","option":"avatar-color","repeated":false,"required":false},{"key":"avatarShape","kind":"string","option":"avatar-shape","repeated":false,"required":false},{"key":"description","kind":"string","option":"description","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"name","kind":"string","option":"name","repeated":false,"required":true},{"key":"title","kind":"string","option":"title","repeated":false,"required":false}],"path":["bots","create"],"routeId":"cli:bots/create"},{"aliases":[],"description":"Delete a bot or group by id or name.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Bot or group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true}],"path":["bots","delete"],"routeId":"cli:bots/delete"},{"aliases":[],"description":"Show one bot or group by id or name.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Bot or group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true}],"path":["bots","get"],"routeId":"cli:bots/get"},{"aliases":[],"description":"List Grok Bot bots (not groups).","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false}],"path":["bots","list"],"routeId":"cli:bots/list"},{"aliases":[],"description":"Update a bot or group profile.","exitCode":"zero","options":[{"key":"avatarColor","kind":"string","option":"avatar-color","repeated":false,"required":false},{"key":"avatarShape","kind":"string","option":"avatar-shape","repeated":false,"required":false},{"key":"description","kind":"string","option":"description","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"hidden","kind":"string","option":"hidden","repeated":false,"required":false},{"key":"name","kind":"string","option":"name","repeated":false,"required":false},{"key":"notify","kind":"string","option":"notify","repeated":false,"required":false},{"description":"Bot or group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true},{"key":"title","kind":"string","option":"title","repeated":false,"required":false}],"path":["bots","update"],"routeId":"cli:bots/update"},{"aliases":[],"description":"Managed Grok/Codex bridge respond.","exitCode":"result","options":[{"description":"JSON object mapping each advertised question ID to {\"answers\":[\"answer\"]}; exact IDs required.","key":"answersJson","kind":"string","option":"answers-json","repeated":false,"required":false},{"key":"bindingId","kind":"string","option":"binding-id","repeated":false,"required":false},{"choices":["accept","decline","cancel"],"key":"decision","kind":"enum","option":"decision","repeated":false,"required":false},{"key":"exchangeId","kind":"string","option":"exchange-id","repeated":false,"required":false},{"key":"generation","kind":"string","option":"generation","repeated":false,"required":true},{"key":"interactionId","kind":"string","option":"interaction-id","repeated":false,"required":true},{"key":"threadId","kind":"string","option":"thread-id","repeated":false,"required":true},{"key":"turnId","kind":"string","option":"turn-id","repeated":false,"required":true}],"path":["codex","bridge","respond"],"routeId":"cli:codex/bridge/respond"},{"aliases":[],"description":"Run a bounded foreground relay (up to 23 hours). Use the packaged gbot-relay.mjs script for unlimited service lifetime.","exitCode":"result","options":[{"description":"Foreground lifetime in milliseconds (100..82800000; default 23h).","key":"lifetimeMs","kind":"number","option":"lifetime-ms","repeated":false,"required":false}],"path":["codex","bridge","run"],"routeId":"cli:codex/bridge/run"},{"aliases":[],"description":"Managed Grok/Codex bridge start.","exitCode":"result","options":[{"choices":["steer","reject"],"key":"busyPolicy","kind":"enum","option":"busy-policy","repeated":false,"required":false},{"key":"codexThreadId","kind":"string","option":"codex-thread-id","repeated":false,"required":false},{"key":"expectedCwd","kind":"string","option":"expected-cwd","repeated":false,"required":false},{"key":"grokTarget","kind":"string","option":"grok-target","positional":0,"repeated":false,"required":true},{"key":"requestId","kind":"string","option":"request-id","repeated":false,"required":false}],"path":["codex","bridge","start"],"routeId":"cli:codex/bridge/start"},{"aliases":[],"description":"Managed Grok/Codex bridge status.","exitCode":"result","options":[{"key":"bindingId","kind":"string","option":"binding-id","repeated":false,"required":false},{"key":"limit","kind":"number","option":"limit","repeated":false,"required":false}],"path":["codex","bridge","status"],"routeId":"cli:codex/bridge/status"},{"aliases":[],"description":"Managed Grok/Codex bridge stop.","exitCode":"result","options":[{"key":"all","kind":"boolean","option":"all","repeated":false,"required":false},{"key":"bindingId","kind":"string","option":"binding-id","repeated":false,"required":false},{"key":"worker","kind":"boolean","option":"worker","repeated":false,"required":false}],"path":["codex","bridge","stop"],"routeId":"cli:codex/bridge/stop"},{"aliases":[],"description":"Install, remove, or check the ChatGPT Desktop shim: a CODEX_CLI_PATH wrapper that bridges Desktop stdio onto the managed Codex daemon (stock app-server proxy hangs). macOS persists via LaunchAgent; always fails open to real Codex.","exitCode":"result","options":[{"choices":["install","uninstall","status"],"description":"install | uninstall | status","key":"action","kind":"enum","option":"action","positional":0,"repeated":false,"required":true}],"path":["codex","desktop-shim"],"routeId":"cli:codex/desktop-shim"},{"aliases":[],"description":"List Codex daemon-managed threads.","exitCode":"result","options":[{"description":"Opaque pagination cursor (may start with -)","key":"cursor","kind":"string","option":"cursor","repeated":false,"required":false},{"description":"Max threads to list (1-200)","key":"limit","kind":"number","option":"limit","repeated":false,"required":false}],"path":["codex","list-threads"],"routeId":"cli:codex/list-threads"},{"aliases":[],"description":"List the experimental Codex thread queue (GROK_BOT_CODEX_EXPERIMENTAL=1).","exitCode":"result","options":[{"key":"threadId","kind":"string","option":"thread-id","positional":0,"repeated":false,"required":true}],"path":["codex","queue"],"routeId":"cli:codex/queue"},{"aliases":[],"description":"Send to Codex; acceptance is distinct from completion. Options precede threadId.","exitCode":"result","options":[{"key":"bindingId","kind":"string","option":"binding-id","repeated":false,"required":false},{"key":"correlationId","kind":"string","option":"correlation-id","repeated":false,"required":false},{"key":"envelope","kind":"boolean","option":"envelope","repeated":false,"required":false},{"key":"expectedCwd","kind":"string","option":"expected-cwd","repeated":false,"required":false},{"description":"Required active-turn guard for steer; stale guards reject.","key":"expectedTurnId","kind":"string","option":"expected-turn-id","repeated":false,"required":false},{"key":"hop","kind":"number","option":"hop","repeated":false,"required":false},{"description":"Reply budget: 1-4194304 bytes.","key":"maxOutputBytes","kind":"number","option":"max-output-bytes","repeated":false,"required":false},{"key":"message","kind":"string","option":"message","positional":1,"repeated":true,"required":true},{"key":"replyTo","kind":"string","option":"reply-to","repeated":false,"required":false},{"key":"replyToGrok","kind":"string","option":"reply-to-grok","repeated":false,"required":false},{"key":"requestId","kind":"string","option":"request-id","repeated":false,"required":false},{"key":"threadId","kind":"string","option":"thread-id","positional":0,"repeated":false,"required":true},{"description":"Observation timeout: 1-600000 milliseconds.","key":"timeoutMs","kind":"number","option":"timeout-ms","repeated":false,"required":false},{"key":"wait","kind":"boolean","option":"wait","repeated":false,"required":false},{"choices":["reject","queue","steer"],"key":"whenBusy","kind":"enum","option":"when-busy","repeated":false,"required":false}],"path":["codex","send"],"routeId":"cli:codex/send"},{"aliases":[],"description":"Probe the local Codex app-server daemon. Exit 0 only when it is usable.","exitCode":"result","options":[],"path":["codex","status"],"routeId":"cli:codex/status"},{"aliases":[],"description":"Bounded Codex wait observation; never interrupts execution.","exitCode":"result","options":[{"key":"expectedCwd","kind":"string","option":"expected-cwd","repeated":false,"required":false},{"description":"Reply budget: 1-4194304 bytes.","key":"maxOutputBytes","kind":"number","option":"max-output-bytes","repeated":false,"required":false},{"key":"messageId","kind":"string","option":"message-id","repeated":false,"required":false},{"key":"threadId","kind":"string","option":"thread-id","positional":0,"repeated":false,"required":true},{"description":"Observation timeout: 1-600000 milliseconds.","key":"timeoutMs","kind":"number","option":"timeout-ms","repeated":false,"required":false},{"key":"turnId","kind":"string","option":"turn-id","positional":1,"repeated":false,"required":true}],"path":["codex","wait"],"routeId":"cli:codex/wait"},{"aliases":[],"description":"Bounded Codex watch observation; never interrupts execution.","exitCode":"result","options":[{"key":"expectedCwd","kind":"string","option":"expected-cwd","repeated":false,"required":false},{"description":"Maximum observed events: 1-500.","key":"maxEvents","kind":"number","option":"max-events","repeated":false,"required":false},{"key":"threadId","kind":"string","option":"thread-id","positional":0,"repeated":false,"required":true},{"description":"Observation timeout: 1-600000 milliseconds.","key":"timeoutMs","kind":"number","option":"timeout-ms","repeated":false,"required":false}],"path":["codex","watch"],"routeId":"cli:codex/watch"},{"aliases":[],"description":"Show which agents root and auth sources gbot can see.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false}],"path":["doctor"],"routeId":"cli:doctor"},{"aliases":[],"description":"Add a bot to a group.","exitCode":"zero","options":[{"key":"bot","kind":"string","option":"bot","positional":1,"repeated":false,"required":true},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"group","kind":"string","option":"group","positional":0,"repeated":false,"required":true}],"path":["groups","add"],"routeId":"cli:groups/add"},{"aliases":[],"description":"Create a Grok Bot group.","exitCode":"zero","options":[{"key":"avatarColor","kind":"string","option":"avatar-color","repeated":false,"required":false},{"key":"avatarShape","kind":"string","option":"avatar-shape","repeated":false,"required":false},{"key":"description","kind":"string","option":"description","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Member bot id or name (repeatable)","key":"member","kind":"string","option":"member","repeated":true,"required":true},{"key":"name","kind":"string","option":"name","repeated":false,"required":true},{"key":"title","kind":"string","option":"title","repeated":false,"required":false}],"path":["groups","create"],"routeId":"cli:groups/create"},{"aliases":[],"description":"Delete a group by id or name.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true}],"path":["groups","delete"],"routeId":"cli:groups/delete"},{"aliases":[],"description":"Show one group by id or name.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true}],"path":["groups","get"],"routeId":"cli:groups/get"},{"aliases":[],"description":"List Grok Bot groups.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false}],"path":["groups","list"],"routeId":"cli:groups/list"},{"aliases":[],"description":"Show members of a group (same payload as groups get).","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true}],"path":["groups","members"],"routeId":"cli:groups/members"},{"aliases":[],"description":"Remove a bot from a group.","exitCode":"zero","options":[{"key":"bot","kind":"string","option":"bot","positional":1,"repeated":false,"required":true},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"group","kind":"string","option":"group","positional":0,"repeated":false,"required":true}],"path":["groups","remove"],"routeId":"cli:groups/remove"},{"aliases":[],"description":"Replace a group's member list.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"group","kind":"string","option":"group","positional":0,"repeated":false,"required":true},{"description":"Member bot id or name (repeatable)","key":"member","kind":"string","option":"member","repeated":true,"required":true}],"path":["groups","set"],"routeId":"cli:groups/set"},{"aliases":[],"description":"Update a group profile (members stay on set/add/remove).","exitCode":"zero","options":[{"key":"avatarColor","kind":"string","option":"avatar-color","repeated":false,"required":false},{"key":"avatarShape","kind":"string","option":"avatar-shape","repeated":false,"required":false},{"key":"description","kind":"string","option":"description","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"key":"hidden","kind":"string","option":"hidden","repeated":false,"required":false},{"key":"name","kind":"string","option":"name","repeated":false,"required":false},{"key":"notify","kind":"string","option":"notify","repeated":false,"required":false},{"description":"Group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":true},{"key":"title","kind":"string","option":"title","repeated":false,"required":false}],"path":["groups","update"],"routeId":"cli:groups/update"},{"aliases":[],"description":"Read the opt-in local JSONL history without contacting the gateway.","exitCode":"zero","options":[{"description":"Directory containing history.jsonl","key":"historyDir","kind":"string","option":"history-dir","repeated":false,"required":false},{"description":"Maximum matching rows (1 or more)","key":"limit","kind":"number","option":"limit","repeated":false,"required":false},{"description":"Print the history file path","key":"path","kind":"boolean","option":"path","repeated":false,"required":false},{"description":"Bot or group id or name","key":"ref","kind":"string","option":"ref","positional":0,"repeated":false,"required":false},{"description":"Case-insensitive message text filter","key":"search","kind":"string","option":"search","repeated":false,"required":false}],"path":["history"],"routeId":"cli:history"},{"aliases":[],"description":"Send a message to a Grok Bot bot or group by name or id.","exitCode":"result","options":[{"key":"bindingId","kind":"string","option":"binding-id","repeated":false,"required":false},{"key":"codexThreadId","kind":"string","option":"codex-thread-id","repeated":false,"required":false},{"description":"Stable correlation id for multi-hop replies","key":"correlationId","kind":"string","option":"correlation-id","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Prepend the [gbot …] header","key":"envelope","kind":"boolean","option":"envelope","repeated":false,"required":false},{"key":"expectedCwd","kind":"string","option":"expected-cwd","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Directory containing history.jsonl","key":"historyDir","kind":"string","option":"history-dir","repeated":false,"required":false},{"description":"Hop count; refused at GROK_BOT_MAX_HOPS","key":"hop","kind":"number","option":"hop","repeated":false,"required":false},{"key":"message","kind":"string","option":"message","positional":1,"repeated":true,"required":true},{"description":"Skip local history for this command","key":"noHistory","kind":"boolean","option":"no-history","repeated":false,"required":false},{"choices":["auto","manual"],"key":"replyMode","kind":"enum","option":"reply-mode","repeated":false,"required":false},{"description":"Prior message id this send replies to","key":"replyTo","kind":"string","option":"reply-to","repeated":false,"required":false},{"key":"requestId","kind":"string","option":"request-id","repeated":false,"required":false},{"key":"target","kind":"string","option":"target","positional":0,"repeated":false,"required":true}],"path":["send"],"routeId":"cli:send"},{"aliases":[],"description":"Add a SKILL.md to the shared skill library. Every bot sees it.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"SKILL.md file, or a directory holding one","key":"path","kind":"string","option":"path","positional":0,"repeated":false,"required":true}],"path":["skills","add"],"routeId":"cli:skills/add"},{"aliases":[],"description":"List the skill library every bot in this Grok Bot shares.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false}],"path":["skills","list"],"routeId":"cli:skills/list"},{"aliases":[],"description":"Remove a library skill by id or name. Every bot loses it.","exitCode":"zero","options":[{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Skill id or name","key":"skill","kind":"string","option":"skill","positional":0,"repeated":false,"required":true}],"path":["skills","remove"],"routeId":"cli:skills/remove"},{"aliases":[],"description":"Read the most recent messages in a Grok Bot bot or group thread.","exitCode":"zero","options":[{"description":"Return entries after this opaque entry id","key":"after","kind":"string","option":"after","repeated":false,"required":false},{"description":"Agents directory for --files mode","key":"dir","kind":"string","option":"dir","repeated":false,"required":false},{"description":"Force the on-disk agents store","key":"files","kind":"boolean","option":"files","repeated":false,"required":false},{"description":"Show full entry text in human output","key":"full","kind":"boolean","option":"full","repeated":false,"required":false},{"description":"Force the live gateway","key":"gateway","kind":"boolean","option":"gateway","repeated":false,"required":false},{"description":"Directory containing history.jsonl","key":"historyDir","kind":"string","option":"history-dir","repeated":false,"required":false},{"description":"How many trailing entries to return (1-200)","key":"limit","kind":"number","option":"limit","repeated":false,"required":false},{"description":"Skip local history for this command","key":"noHistory","kind":"boolean","option":"no-history","repeated":false,"required":false},{"description":"Read one rooted thread by message id","key":"root","kind":"string","option":"root","repeated":false,"required":false},{"key":"target","kind":"string","option":"target","positional":0,"repeated":false,"required":true}],"path":["thread"],"routeId":"cli:thread"}],"mode":"generated","routes":[{"contract":"contract:src/cli/approvals/list.tsx#inputJsonSchema","description":"List current Grok approval cards (latest 200 entries).","id":"cli:approvals/list","inputSchema":{"additionalProperties":false,"properties":{"target":{"type":"string"}},"required":["target"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/approvals/list.tsx"},{"contract":"contract:src/cli/approvals/respond.tsx#inputJsonSchema","description":"Explicit user decision: accept a Grok request once or decline; never grant persistent permissions.","id":"cli:approvals/respond","inputSchema":{"additionalProperties":false,"properties":{"decision":{"enum":["accept","decline"],"type":"string"},"entryId":{"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","entryId","requestId","decision"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/approvals/respond.tsx"},{"contract":"contract:src/cli/bots/create.tsx#inputJsonSchema","description":"Create a Grok Bot bot.","id":"cli:bots/create","inputSchema":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"name":{"type":"string"},"title":{"type":"string"}},"required":["name"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/bots/create.tsx"},{"contract":"contract:src/cli/bots/delete.tsx#inputJsonSchema","description":"Delete a bot or group by id or name.","id":"cli:bots/delete","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/bots/delete.tsx"},{"contract":"contract:src/cli/bots/get.tsx#inputJsonSchema","description":"Show one bot or group by id or name.","id":"cli:bots/get","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/bots/get.tsx"},{"contract":"contract:src/cli/bots/list.tsx#inputJsonSchema","description":"List Grok Bot bots (not groups).","id":"cli:bots/list","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/bots/list.tsx"},{"contract":"contract:src/cli/bots/update.tsx#inputJsonSchema","description":"Update a bot or group profile.","id":"cli:bots/update","inputSchema":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"hidden":{"type":"string"},"name":{"type":"string"},"notify":{"type":"string"},"ref":{"description":"Bot or group id or name","type":"string"},"title":{"type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/bots/update.tsx"},{"contract":"contract:src/cli/codex/bridge/respond.tsx#inputJsonSchema","description":"Managed Grok/Codex bridge respond.","id":"cli:codex/bridge/respond","inputSchema":{"additionalProperties":false,"properties":{"answersJson":{"description":"JSON object mapping each advertised question ID to {\"answers\":[\"answer\"]}; exact IDs required.","type":"string"},"bindingId":{"type":"string"},"decision":{"enum":["accept","decline","cancel"],"type":"string"},"exchangeId":{"type":"string"},"generation":{"type":"string"},"interactionId":{"type":"string"},"threadId":{"type":"string"},"turnId":{"type":"string"}},"required":["interactionId","generation","threadId","turnId"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/bridge/respond.tsx"},{"contract":"contract:src/cli/codex/bridge/run.tsx#inputJsonSchema","description":"Run a bounded foreground relay (up to 23 hours). Use the packaged gbot-relay.mjs script for unlimited service lifetime.","id":"cli:codex/bridge/run","inputSchema":{"additionalProperties":false,"properties":{"lifetimeMs":{"description":"Foreground lifetime in milliseconds (100..82800000; default 23h).","type":"number"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/bridge/run.tsx"},{"contract":"contract:src/cli/codex/bridge/start.tsx#inputJsonSchema","description":"Managed Grok/Codex bridge start.","id":"cli:codex/bridge/start","inputSchema":{"additionalProperties":false,"properties":{"busyPolicy":{"enum":["steer","reject"],"type":"string"},"codexThreadId":{"type":"string"},"expectedCwd":{"type":"string"},"grokTarget":{"type":"string"},"requestId":{"type":"string"}},"required":["grokTarget"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/bridge/start.tsx"},{"contract":"contract:src/cli/codex/bridge/status.tsx#inputJsonSchema","description":"Managed Grok/Codex bridge status.","id":"cli:codex/bridge/status","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"limit":{"type":"number"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/bridge/status.tsx"},{"contract":"contract:src/cli/codex/bridge/stop.tsx#inputJsonSchema","description":"Managed Grok/Codex bridge stop.","id":"cli:codex/bridge/stop","inputSchema":{"additionalProperties":false,"properties":{"all":{"type":"boolean"},"bindingId":{"type":"string"},"worker":{"type":"boolean"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/bridge/stop.tsx"},{"contract":"contract:src/cli/codex/desktop-shim.tsx#inputJsonSchema","description":"Install, remove, or check the ChatGPT Desktop shim: a CODEX_CLI_PATH wrapper that bridges Desktop stdio onto the managed Codex daemon (stock app-server proxy hangs). macOS persists via LaunchAgent; always fails open to real Codex.","id":"cli:codex/desktop-shim","inputSchema":{"additionalProperties":false,"properties":{"action":{"description":"install | uninstall | status","enum":["install","uninstall","status"],"type":"string"}},"required":["action"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/desktop-shim.tsx"},{"contract":"contract:src/cli/codex/list-threads.tsx#inputJsonSchema","description":"List Codex daemon-managed threads.","id":"cli:codex/list-threads","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"description":"Opaque pagination cursor (may start with -)","type":"string"},"limit":{"default":20,"description":"Max threads to list (1-200)","type":"number"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/list-threads.tsx"},{"contract":"contract:src/cli/codex/queue.tsx#inputJsonSchema","description":"List the experimental Codex thread queue (GROK_BOT_CODEX_EXPERIMENTAL=1).","id":"cli:codex/queue","inputSchema":{"additionalProperties":false,"properties":{"threadId":{"type":"string"}},"required":["threadId"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/queue.tsx"},{"contract":"contract:src/cli/codex/send.tsx#inputJsonSchema","description":"Send to Codex; acceptance is distinct from completion. Options precede threadId.","id":"cli:codex/send","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"correlationId":{"type":"string"},"envelope":{"type":"boolean"},"expectedCwd":{"type":"string"},"expectedTurnId":{"description":"Required active-turn guard for steer; stale guards reject.","type":"string"},"hop":{"type":"number"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"message":{"items":{"type":"string"},"type":"array"},"replyTo":{"type":"string"},"replyToGrok":{"type":"string"},"requestId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"wait":{"type":"boolean"},"whenBusy":{"enum":["reject","queue","steer"],"type":"string"}},"required":["threadId","message"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/send.tsx"},{"contract":"contract:src/cli/codex/status.tsx#inputJsonSchema","description":"Probe the local Codex app-server daemon. Exit 0 only when it is usable.","id":"cli:codex/status","inputSchema":{"additionalProperties":false,"properties":{},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/status.tsx"},{"contract":"contract:src/cli/codex/wait.tsx#inputJsonSchema","description":"Bounded Codex wait observation; never interrupts execution.","id":"cli:codex/wait","inputSchema":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"messageId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"turnId":{"type":"string"}},"required":["threadId","turnId"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/wait.tsx"},{"contract":"contract:src/cli/codex/watch.tsx#inputJsonSchema","description":"Bounded Codex watch observation; never interrupts execution.","id":"cli:codex/watch","inputSchema":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxEvents":{"description":"Maximum observed events: 1-500.","type":"number"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"}},"required":["threadId"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/codex/watch.tsx"},{"contract":"contract:src/cli/doctor.tsx#inputJsonSchema","description":"Show which agents root and auth sources gbot can see.","id":"cli:doctor","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/doctor.tsx"},{"contract":"contract:src/cli/groups/add.tsx#inputJsonSchema","description":"Add a bot to a group.","id":"cli:groups/add","inputSchema":{"additionalProperties":false,"properties":{"bot":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"}},"required":["group","bot"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/add.tsx"},{"contract":"contract:src/cli/groups/create.tsx#inputJsonSchema","description":"Create a Grok Bot group.","id":"cli:groups/create","inputSchema":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"member":{"description":"Member bot id or name (repeatable)","items":{"type":"string"},"type":"array"},"name":{"type":"string"},"title":{"type":"string"}},"required":["name","member"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/create.tsx"},{"contract":"contract:src/cli/groups/delete.tsx#inputJsonSchema","description":"Delete a group by id or name.","id":"cli:groups/delete","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/delete.tsx"},{"contract":"contract:src/cli/groups/get.tsx#inputJsonSchema","description":"Show one group by id or name.","id":"cli:groups/get","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/get.tsx"},{"contract":"contract:src/cli/groups/list.tsx#inputJsonSchema","description":"List Grok Bot groups.","id":"cli:groups/list","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/list.tsx"},{"contract":"contract:src/cli/groups/members.tsx#inputJsonSchema","description":"Show members of a group (same payload as groups get).","id":"cli:groups/members","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/members.tsx"},{"contract":"contract:src/cli/groups/remove.tsx#inputJsonSchema","description":"Remove a bot from a group.","id":"cli:groups/remove","inputSchema":{"additionalProperties":false,"properties":{"bot":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"}},"required":["group","bot"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/remove.tsx"},{"contract":"contract:src/cli/groups/set.tsx#inputJsonSchema","description":"Replace a group's member list.","id":"cli:groups/set","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"},"member":{"description":"Member bot id or name (repeatable)","items":{"type":"string"},"type":"array"}},"required":["group","member"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/set.tsx"},{"contract":"contract:src/cli/groups/update.tsx#inputJsonSchema","description":"Update a group profile (members stay on set/add/remove).","id":"cli:groups/update","inputSchema":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"hidden":{"type":"string"},"name":{"type":"string"},"notify":{"type":"string"},"ref":{"description":"Group id or name","type":"string"},"title":{"type":"string"}},"required":["ref"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/groups/update.tsx"},{"contract":"contract:src/cli/history.tsx#inputJsonSchema","description":"Read the opt-in local JSONL history without contacting the gateway.","id":"cli:history","inputSchema":{"additionalProperties":false,"properties":{"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"limit":{"default":40,"description":"Maximum matching rows (1 or more)","type":"number"},"path":{"description":"Print the history file path","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"},"search":{"description":"Case-insensitive message text filter","type":"string"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/history.tsx"},{"contract":"contract:src/cli/send.tsx#inputJsonSchema","description":"Send a message to a Grok Bot bot or group by name or id.","id":"cli:send","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"codexThreadId":{"type":"string"},"correlationId":{"description":"Stable correlation id for multi-hop replies","type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"envelope":{"description":"Prepend the [gbot …] header","type":"boolean"},"expectedCwd":{"type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"hop":{"description":"Hop count; refused at GROK_BOT_MAX_HOPS","type":"number"},"message":{"items":{"type":"string"},"type":"array"},"noHistory":{"description":"Skip local history for this command","type":"boolean"},"replyMode":{"enum":["auto","manual"],"type":"string"},"replyTo":{"description":"Prior message id this send replies to","type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","message"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/send.tsx"},{"contract":"contract:src/cli/skills/add.tsx#inputJsonSchema","description":"Add a SKILL.md to the shared skill library. Every bot sees it.","id":"cli:skills/add","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"path":{"description":"SKILL.md file, or a directory holding one","type":"string"}},"required":["path"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/skills/add.tsx"},{"contract":"contract:src/cli/skills/list.tsx#inputJsonSchema","description":"List the skill library every bot in this Grok Bot shares.","id":"cli:skills/list","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/skills/list.tsx"},{"contract":"contract:src/cli/skills/remove.tsx#inputJsonSchema","description":"Remove a library skill by id or name. Every bot loses it.","id":"cli:skills/remove","inputSchema":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"skill":{"description":"Skill id or name","type":"string"}},"required":["skill"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/skills/remove.tsx"},{"contract":"contract:src/cli/thread.tsx#inputJsonSchema","description":"Read the most recent messages in a Grok Bot bot or group thread.","id":"cli:thread","inputSchema":{"additionalProperties":false,"properties":{"after":{"description":"Return entries after this opaque entry id","type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"full":{"description":"Show full entry text in human output","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"limit":{"default":40,"description":"How many trailing entries to return (1-200)","type":"number"},"noHistory":{"description":"Skip local history for this command","type":"boolean"},"root":{"description":"Read one rooted thread by message id","type":"string"},"target":{"type":"string"}},"required":["target"],"type":"object"},"kind":"cli","provenance":{"kind":"conventional"},"source":"src/cli/thread.tsx"}]},"contracts":[{"id":"contract:src/cli/approvals/list.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"target":{"type":"string"}},"required":["target"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/approvals/list.tsx"},"routes":["cli:approvals/list"]},{"id":"contract:src/cli/approvals/respond.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"decision":{"enum":["accept","decline"],"type":"string"},"entryId":{"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","entryId","requestId","decision"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/approvals/respond.tsx"},"routes":["cli:approvals/respond"]},{"id":"contract:src/cli/bots/create.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"name":{"type":"string"},"title":{"type":"string"}},"required":["name"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/bots/create.tsx"},"routes":["cli:bots/create"]},{"id":"contract:src/cli/bots/delete.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/bots/delete.tsx"},"routes":["cli:bots/delete"]},{"id":"contract:src/cli/bots/get.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/bots/get.tsx"},"routes":["cli:bots/get"]},{"id":"contract:src/cli/bots/list.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/bots/list.tsx"},"routes":["cli:bots/list"]},{"id":"contract:src/cli/bots/update.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"hidden":{"type":"string"},"name":{"type":"string"},"notify":{"type":"string"},"ref":{"description":"Bot or group id or name","type":"string"},"title":{"type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/bots/update.tsx"},"routes":["cli:bots/update"]},{"id":"contract:src/cli/codex/bridge/respond.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"answersJson":{"description":"JSON object mapping each advertised question ID to {\"answers\":[\"answer\"]}; exact IDs required.","type":"string"},"bindingId":{"type":"string"},"decision":{"enum":["accept","decline","cancel"],"type":"string"},"exchangeId":{"type":"string"},"generation":{"type":"string"},"interactionId":{"type":"string"},"threadId":{"type":"string"},"turnId":{"type":"string"}},"required":["interactionId","generation","threadId","turnId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/bridge/respond.tsx"},"routes":["cli:codex/bridge/respond"]},{"id":"contract:src/cli/codex/bridge/run.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"lifetimeMs":{"description":"Foreground lifetime in milliseconds (100..82800000; default 23h).","type":"number"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/bridge/run.tsx"},"routes":["cli:codex/bridge/run"]},{"id":"contract:src/cli/codex/bridge/start.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"busyPolicy":{"enum":["steer","reject"],"type":"string"},"codexThreadId":{"type":"string"},"expectedCwd":{"type":"string"},"grokTarget":{"type":"string"},"requestId":{"type":"string"}},"required":["grokTarget"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/bridge/start.tsx"},"routes":["cli:codex/bridge/start"]},{"id":"contract:src/cli/codex/bridge/status.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"limit":{"type":"number"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/bridge/status.tsx"},"routes":["cli:codex/bridge/status"]},{"id":"contract:src/cli/codex/bridge/stop.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"all":{"type":"boolean"},"bindingId":{"type":"string"},"worker":{"type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/bridge/stop.tsx"},"routes":["cli:codex/bridge/stop"]},{"id":"contract:src/cli/codex/desktop-shim.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"action":{"description":"install | uninstall | status","enum":["install","uninstall","status"],"type":"string"}},"required":["action"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/desktop-shim.tsx"},"routes":["cli:codex/desktop-shim"]},{"id":"contract:src/cli/codex/list-threads.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"cursor":{"description":"Opaque pagination cursor (may start with -)","type":"string"},"limit":{"default":20,"description":"Max threads to list (1-200)","type":"number"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/list-threads.tsx"},"routes":["cli:codex/list-threads"]},{"id":"contract:src/cli/codex/queue.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"threadId":{"type":"string"}},"required":["threadId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/queue.tsx"},"routes":["cli:codex/queue"]},{"id":"contract:src/cli/codex/send.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"correlationId":{"type":"string"},"envelope":{"type":"boolean"},"expectedCwd":{"type":"string"},"expectedTurnId":{"description":"Required active-turn guard for steer; stale guards reject.","type":"string"},"hop":{"type":"number"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"message":{"items":{"type":"string"},"type":"array"},"replyTo":{"type":"string"},"replyToGrok":{"type":"string"},"requestId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"wait":{"type":"boolean"},"whenBusy":{"enum":["reject","queue","steer"],"type":"string"}},"required":["threadId","message"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/send.tsx"},"routes":["cli:codex/send"]},{"id":"contract:src/cli/codex/status.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/status.tsx"},"routes":["cli:codex/status"]},{"id":"contract:src/cli/codex/wait.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"messageId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"turnId":{"type":"string"}},"required":["threadId","turnId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/wait.tsx"},"routes":["cli:codex/wait"]},{"id":"contract:src/cli/codex/watch.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxEvents":{"description":"Maximum observed events: 1-500.","type":"number"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"}},"required":["threadId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/codex/watch.tsx"},"routes":["cli:codex/watch"]},{"id":"contract:src/cli/doctor.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/doctor.tsx"},"routes":["cli:doctor"]},{"id":"contract:src/cli/groups/add.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bot":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"}},"required":["group","bot"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/add.tsx"},"routes":["cli:groups/add"]},{"id":"contract:src/cli/groups/create.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"member":{"description":"Member bot id or name (repeatable)","items":{"type":"string"},"type":"array"},"name":{"type":"string"},"title":{"type":"string"}},"required":["name","member"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/create.tsx"},"routes":["cli:groups/create"]},{"id":"contract:src/cli/groups/delete.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/delete.tsx"},"routes":["cli:groups/delete"]},{"id":"contract:src/cli/groups/get.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/get.tsx"},"routes":["cli:groups/get"]},{"id":"contract:src/cli/groups/list.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/list.tsx"},"routes":["cli:groups/list"]},{"id":"contract:src/cli/groups/members.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"ref":{"description":"Group id or name","type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/members.tsx"},"routes":["cli:groups/members"]},{"id":"contract:src/cli/groups/remove.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bot":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"}},"required":["group","bot"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/remove.tsx"},"routes":["cli:groups/remove"]},{"id":"contract:src/cli/groups/set.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"group":{"type":"string"},"member":{"description":"Member bot id or name (repeatable)","items":{"type":"string"},"type":"array"}},"required":["group","member"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/set.tsx"},"routes":["cli:groups/set"]},{"id":"contract:src/cli/groups/update.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"avatarColor":{"type":"string"},"avatarShape":{"type":"string"},"description":{"type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"hidden":{"type":"string"},"name":{"type":"string"},"notify":{"type":"string"},"ref":{"description":"Group id or name","type":"string"},"title":{"type":"string"}},"required":["ref"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/groups/update.tsx"},"routes":["cli:groups/update"]},{"id":"contract:src/cli/history.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"limit":{"default":40,"description":"Maximum matching rows (1 or more)","type":"number"},"path":{"description":"Print the history file path","type":"boolean"},"ref":{"description":"Bot or group id or name","type":"string"},"search":{"description":"Case-insensitive message text filter","type":"string"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/history.tsx"},"routes":["cli:history"]},{"id":"contract:src/cli/send.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"codexThreadId":{"type":"string"},"correlationId":{"description":"Stable correlation id for multi-hop replies","type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"envelope":{"description":"Prepend the [gbot …] header","type":"boolean"},"expectedCwd":{"type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"hop":{"description":"Hop count; refused at GROK_BOT_MAX_HOPS","type":"number"},"message":{"items":{"type":"string"},"type":"array"},"noHistory":{"description":"Skip local history for this command","type":"boolean"},"replyMode":{"enum":["auto","manual"],"type":"string"},"replyTo":{"description":"Prior message id this send replies to","type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","message"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/send.tsx"},"routes":["cli:send"]},{"id":"contract:src/cli/skills/add.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"path":{"description":"SKILL.md file, or a directory holding one","type":"string"}},"required":["path"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/skills/add.tsx"},"routes":["cli:skills/add"]},{"id":"contract:src/cli/skills/list.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/skills/list.tsx"},"routes":["cli:skills/list"]},{"id":"contract:src/cli/skills/remove.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"skill":{"description":"Skill id or name","type":"string"}},"required":["skill"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/skills/remove.tsx"},"routes":["cli:skills/remove"]},{"id":"contract:src/cli/thread.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"after":{"description":"Return entries after this opaque entry id","type":"string"},"dir":{"description":"Agents directory for --files mode","type":"string"},"files":{"description":"Force the on-disk agents store","type":"boolean"},"full":{"description":"Show full entry text in human output","type":"boolean"},"gateway":{"description":"Force the live gateway","type":"boolean"},"historyDir":{"description":"Directory containing history.jsonl","type":"string"},"limit":{"default":40,"description":"How many trailing entries to return (1-200)","type":"number"},"noHistory":{"description":"Skip local history for this command","type":"boolean"},"root":{"description":"Read one rooted thread by message id","type":"string"},"target":{"type":"string"}},"required":["target"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/cli/thread.tsx"},"routes":["cli:thread"]},{"id":"contract:src/mcp/grok-bot/tools/codex_send.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"correlationId":{"type":"string"},"envelope":{"type":"boolean"},"expectedCwd":{"type":"string"},"expectedTurnId":{"type":"string"},"hop":{"type":"number"},"maxOutputBytes":{"type":"number"},"message":{"type":"string"},"replyTo":{"type":"string"},"replyToGrok":{"type":"string"},"requestId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"type":"number"},"wait":{"default":false,"type":"boolean"},"whenBusy":{"enum":["reject","queue","steer"],"type":"string"}},"required":["threadId","message"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/codex_send.tsx"},"routes":["tool:grok-bot/codex_send"]},{"id":"contract:src/mcp/grok-bot/tools/codex_threads.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"cursor":{"type":"string"},"limit":{"description":"Maximum threads in this page: 1-200.","type":"number"}},"required":[],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/codex_threads.tsx"},"routes":["tool:grok-bot/codex_threads"]},{"id":"contract:src/mcp/grok-bot/tools/codex_wait.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"messageId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"turnId":{"type":"string"}},"required":["threadId","turnId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/codex_wait.tsx"},"routes":["tool:grok-bot/codex_wait"]},{"id":"contract:src/mcp/grok-bot/tools/codex_watch.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxEvents":{"description":"Maximum observed events: 1-500.","type":"number"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"}},"required":["threadId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/codex_watch.tsx"},"routes":["tool:grok-bot/codex_watch"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_bridge_start.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"busyPolicy":{"enum":["steer","reject"],"type":"string"},"codexThreadId":{"type":"string"},"expectedCwd":{"type":"string"},"grokTarget":{"type":"string"},"requestId":{"type":"string"}},"required":["grokTarget"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_bridge_start.tsx"},"routes":["tool:grok-bot/gbot_bridge_start"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_bridge_status.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"limit":{"type":"number"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_bridge_status.tsx"},"routes":["tool:grok-bot/gbot_bridge_status"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_bridge_stop.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"all":{"type":"boolean"},"bindingId":{"type":"string"},"worker":{"type":"boolean"}},"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_bridge_stop.tsx"},"routes":["tool:grok-bot/gbot_bridge_stop"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_codex_respond.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"answersJson":{"description":"JSON object mapping each advertised question ID to {\"answers\":[\"answer\"]}; exact IDs required.","type":"string"},"bindingId":{"type":"string"},"decision":{"enum":["accept","decline","cancel"],"type":"string"},"exchangeId":{"type":"string"},"generation":{"type":"string"},"interactionId":{"type":"string"},"threadId":{"type":"string"},"turnId":{"type":"string"}},"required":["interactionId","generation","threadId","turnId"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_codex_respond.tsx"},"routes":["tool:grok-bot/gbot_codex_respond"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_grok_approvals.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"target":{"type":"string"}},"required":["target"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_grok_approvals.tsx"},"routes":["tool:grok-bot/gbot_grok_approvals"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_grok_respond.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"decision":{"enum":["accept","decline"],"type":"string"},"entryId":{"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","entryId","requestId","decision"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_grok_respond.tsx"},"routes":["tool:grok-bot/gbot_grok_respond"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_send.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"codexThreadId":{"type":"string"},"correlationId":{"type":"string"},"expectedCwd":{"type":"string"},"hop":{"description":"Explicit chain hop count, refused at the configured bound.","type":"number"},"message":{"type":"string"},"replyMode":{"enum":["auto","manual"],"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","message"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_send.tsx"},"routes":["tool:grok-bot/gbot_send"]},{"id":"contract:src/mcp/grok-bot/tools/gbot_thread.tsx#inputJsonSchema","input":{"additionalProperties":false,"properties":{"after":{"description":"Opaque cursor from the previous call. Returns entries strictly after it; an unknown cursor resets with a bounded snapshot.","type":"string"},"full":{"default":false,"description":"Return entries with text up to bounded budgets (20k chars per entry, 200k total). Every entry reports truncated/fullLength; read any remainder with `gbot thread --full` / `--json` on the machine.","type":"boolean"},"limit":{"default":40,"description":"How many trailing entries to inspect (1-200). Entries are returned only with full:true.","type":"number"},"target":{"description":"Bot or group name or id, for example \"General\".","type":"string"}},"required":["target"],"type":"object"},"origin":{"binding":"inputJsonSchema","module":"src/mcp/grok-bot/tools/gbot_thread.tsx"},"routes":["tool:grok-bot/gbot_thread"]}],"digest":"2ca82f243db8390590ba51a27b27dafd9050e415ce2cef09b135b41e65629e76","events":[],"layouts":[],"providers":[],"scripts":[{"id":"script:gbot-relay","kind":"script","provenance":{"kind":"conventional"},"source":"src/scripts/gbot-relay.ts"}],"servers":[{"id":"mcp:grok-bot","mode":"generated","name":"grok-bot","routes":[{"contract":"contract:src/mcp/grok-bot/tools/codex_send.tsx#inputJsonSchema","description":"Send to Codex. With replyToGrok or bindingId, managed delivery returns the terminal answer to Grok automatically. Otherwise optional wait observes completion and explicit steer requires expectedTurnId. Acceptance is not completion.","id":"tool:grok-bot/codex_send","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"correlationId":{"type":"string"},"envelope":{"type":"boolean"},"expectedCwd":{"type":"string"},"expectedTurnId":{"type":"string"},"hop":{"type":"number"},"maxOutputBytes":{"type":"number"},"message":{"type":"string"},"replyTo":{"type":"string"},"replyToGrok":{"type":"string"},"requestId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"type":"number"},"wait":{"default":false,"type":"boolean"},"whenBusy":{"enum":["reject","queue","steer"],"type":"string"}},"required":["threadId","message"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/codex_send.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/codex_threads.tsx#inputJsonSchema","description":"Discover a bounded page of Codex daemon threads.","id":"tool:grok-bot/codex_threads","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"type":"string"},"limit":{"description":"Maximum threads in this page: 1-200.","type":"number"}},"required":[],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/codex_threads.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/codex_wait.tsx#inputJsonSchema","description":"Explicit diagnostic observation of one Codex turn; returns execution and final reply without interrupting it.","id":"tool:grok-bot/codex_wait","inputSchema":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxOutputBytes":{"description":"Reply budget: 1-4194304 bytes.","type":"number"},"messageId":{"type":"string"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"},"turnId":{"type":"string"}},"required":["threadId","turnId"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/codex_wait.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/codex_watch.tsx#inputJsonSchema","description":"Watch bounded Codex thread events for diagnostics without answering approvals.","id":"tool:grok-bot/codex_watch","inputSchema":{"additionalProperties":false,"properties":{"expectedCwd":{"type":"string"},"maxEvents":{"description":"Maximum observed events: 1-500.","type":"number"},"threadId":{"type":"string"},"timeoutMs":{"description":"Observation timeout: 1-600000 milliseconds.","type":"number"}},"required":["threadId"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/codex_watch.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_bridge_start.tsx#inputJsonSchema","description":"Link a Grok conversation to Codex once. New visible Grok messages arrive automatically and Codex final answers return to Grok.","id":"tool:grok-bot/gbot_bridge_start","inputSchema":{"additionalProperties":false,"properties":{"busyPolicy":{"enum":["steer","reject"],"type":"string"},"codexThreadId":{"type":"string"},"expectedCwd":{"type":"string"},"grokTarget":{"type":"string"},"requestId":{"type":"string"}},"required":["grokTarget"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_bridge_start.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_bridge_status.tsx#inputJsonSchema","description":"Inspect worker health, route coverage, bounded receipts and scoped pending operator interactions.","id":"tool:grok-bot/gbot_bridge_status","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"limit":{"type":"number"}},"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_bridge_status.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_bridge_stop.tsx#inputJsonSchema","description":"Stop a binding without deleting receipts or interrupting Codex. all stops all bindings; worker explicitly shuts down the worker.","id":"tool:grok-bot/gbot_bridge_stop","inputSchema":{"additionalProperties":false,"properties":{"all":{"type":"boolean"},"bindingId":{"type":"string"},"worker":{"type":"boolean"}},"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_bridge_stop.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_codex_respond.tsx#inputJsonSchema","description":"Explicit operator response to a current scoped Codex interaction. Supports only one-time accept/decline/cancel or exact question-ID answers. Never auto-approve.","id":"tool:grok-bot/gbot_codex_respond","inputSchema":{"additionalProperties":false,"properties":{"answersJson":{"description":"JSON object mapping each advertised question ID to {\"answers\":[\"answer\"]}; exact IDs required.","type":"string"},"bindingId":{"type":"string"},"decision":{"enum":["accept","decline","cancel"],"type":"string"},"exchangeId":{"type":"string"},"generation":{"type":"string"},"interactionId":{"type":"string"},"threadId":{"type":"string"},"turnId":{"type":"string"}},"required":["interactionId","generation","threadId","turnId"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_codex_respond.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_grok_approvals.tsx#inputJsonSchema","description":"List pending auto-review and local-tool approval cards in the latest 200 entries for a Grok bot. Older or unsupported requests require the owning Grok UI.","id":"tool:grok-bot/gbot_grok_approvals","inputSchema":{"additionalProperties":false,"properties":{"target":{"type":"string"}},"required":["target"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_grok_approvals.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_grok_respond.tsx#inputJsonSchema","description":"Only after an explicit user decision: accept one current Grok approval once or decline it. Exact target, entryId and approval requestId required. Never auto-approve or grant persistent permissions. Success acknowledges response delivery, not execution.","id":"tool:grok-bot/gbot_grok_respond","inputSchema":{"additionalProperties":false,"properties":{"decision":{"enum":["accept","decline"],"type":"string"},"entryId":{"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","entryId","requestId","decision"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_grok_respond.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_send.tsx#inputJsonSchema","description":"Send to Grok Bot. Native Codex calls automatically receive replies in their originating thread; send once and continue work. Without a native source, supply codexThreadId or use manual gbot_thread reading.","id":"tool:grok-bot/gbot_send","inputSchema":{"additionalProperties":false,"properties":{"bindingId":{"type":"string"},"codexThreadId":{"type":"string"},"correlationId":{"type":"string"},"expectedCwd":{"type":"string"},"hop":{"description":"Explicit chain hop count, refused at the configured bound.","type":"number"},"message":{"type":"string"},"replyMode":{"enum":["auto","manual"],"type":"string"},"requestId":{"type":"string"},"target":{"type":"string"}},"required":["target","message"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_send.tsx"},{"contract":"contract:src/mcp/grok-bot/tools/gbot_thread.tsx#inputJsonSchema","description":"Read a bounded Grok Bot thread tail. Returns a small receipt by default; pass the last cursor as after for an exclusive client-side delta, or full:true to include bounded entry text.","id":"tool:grok-bot/gbot_thread","inputSchema":{"additionalProperties":false,"properties":{"after":{"description":"Opaque cursor from the previous call. Returns entries strictly after it; an unknown cursor resets with a bounded snapshot.","type":"string"},"full":{"default":false,"description":"Return entries with text up to bounded budgets (20k chars per entry, 200k total). Every entry reports truncated/fullLength; read any remainder with `gbot thread --full` / `--json` on the machine.","type":"boolean"},"limit":{"default":40,"description":"How many trailing entries to inspect (1-200). Entries are returned only with full:true.","type":"number"},"target":{"description":"Bot or group name or id, for example \"General\".","type":"string"}},"required":["target"],"type":"object"},"kind":"tool","provenance":{"kind":"conventional"},"serverId":"mcp:grok-bot","source":"src/mcp/grok-bot/tools/gbot_thread.tsx"}]}]},"runtime":{"node":"22.19.0"}} diff --git a/artifact/bin/gbot-flight.mjs b/artifact/bin/gbot-flight.mjs new file mode 100644 index 0000000..9bb6af2 --- /dev/null +++ b/artifact/bin/gbot-flight.mjs @@ -0,0 +1,32910 @@ +import * as __rspack_external_node_async_hooks_4d8b1b4a from "node:async_hooks"; +import * as __rspack_external_node_child_process_cd435d64 from "node:child_process"; +import * as __rspack_external_node_crypto_2e7c4b46 from "node:crypto"; +import * as __rspack_external_node_fs_1b05aee1 from "node:fs"; +import * as __rspack_external_node_fs_promises_3b710708 from "node:fs/promises"; +import * as __rspack_external_node_net_5ed819e1 from "node:net"; +import * as __rspack_external_node_os_4f3c9d58 from "node:os"; +import * as __rspack_external_node_path_806ed179 from "node:path"; +import * as __rspack_external_node_readline_d8f53bef from "node:readline"; +import * as __rspack_external_node_string_decoder_69b9bd04 from "node:string_decoder"; +import * as __rspack_external_node_url_3991086a from "node:url"; +import * as __rspack_external_node_worker_threads_28ca7740 from "node:worker_threads"; +import { createRequire as __rspack_createRequire } from "node:module"; +const __rspack_createRequire_require = __rspack_createRequire(import.meta.url); +var __webpack_modules__ = ({ +"./node_modules/react-dom/cjs/react-dom.react-server.development.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-dom.react-server.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function noop() {} + function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; + } + function getValueDescriptorExpectingObjectForWarning(thing) { + return null === thing + ? "`null`" + : void 0 === thing + ? "`undefined`" + : "" === thing + ? "an empty string" + : 'something with type "' + typeof thing + '"'; + } + function getValueDescriptorExpectingEnumForWarning(thing) { + return null === thing + ? "`null`" + : void 0 === thing + ? "`undefined`" + : "" === thing + ? "an empty string" + : "string" === typeof thing + ? JSON.stringify(thing) + : "number" === typeof thing + ? "`" + thing + "`" + : 'something with type "' + typeof thing + '"'; + } + var React = __webpack_require__("./node_modules/react/react.react-server.js"), + Internals = { + d: { + f: noop, + r: function () { + throw Error( + "Invalid form element. requestFormReset must be passed a form that was rendered by React." + ); + }, + D: noop, + C: noop, + L: noop, + m: noop, + X: noop, + S: noop, + M: noop + }, + p: 0, + findDOMNode: null + }; + if (!React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); + ("function" === typeof Map && + null != Map.prototype && + "function" === typeof Map.prototype.forEach && + "function" === typeof Set && + null != Set.prototype && + "function" === typeof Set.prototype.clear && + "function" === typeof Set.prototype.forEach) || + console.error( + "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills" + ); + exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + Internals; + exports.preconnect = function (href, options) { + "string" === typeof href && href + ? null != options && "object" !== typeof options + ? console.error( + "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : null != options && + "string" !== typeof options.crossOrigin && + console.error( + "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.", + getValueDescriptorExpectingObjectForWarning(options.crossOrigin) + ) + : console.error( + "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + "string" === typeof href && + (options + ? ((options = options.crossOrigin), + (options = + "string" === typeof options + ? "use-credentials" === options + ? options + : "" + : void 0)) + : (options = null), + Internals.d.C(href, options)); + }; + exports.prefetchDNS = function (href) { + if ("string" !== typeof href || !href) + console.error( + "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + else if (1 < arguments.length) { + var options = arguments[1]; + "object" === typeof options && options.hasOwnProperty("crossOrigin") + ? console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ); + } + "string" === typeof href && Internals.d.D(href); + }; + exports.preinit = function (href, options) { + "string" === typeof href && href + ? null == options || "object" !== typeof options + ? console.error( + "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : "style" !== options.as && + "script" !== options.as && + console.error( + 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".', + getValueDescriptorExpectingEnumForWarning(options.as) + ) + : console.error( + "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + if ( + "string" === typeof href && + options && + "string" === typeof options.as + ) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), + integrity = + "string" === typeof options.integrity ? options.integrity : void 0, + fetchPriority = + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0; + "style" === as + ? Internals.d.S( + href, + "string" === typeof options.precedence + ? options.precedence + : void 0, + { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority + } + ) + : "script" === as && + Internals.d.X(href, { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } + }; + exports.preinitModule = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + void 0 !== options && "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : options && + "as" in options && + "script" !== options.as && + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingEnumForWarning(options.as) + + "."); + if (encountered) + console.error( + "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s", + encountered + ); + else + switch ( + ((encountered = + options && "string" === typeof options.as ? options.as : "script"), + encountered) + ) { + case "script": + break; + default: + (encountered = + getValueDescriptorExpectingEnumForWarning(encountered)), + console.error( + 'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)', + encountered, + href + ); + } + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) + (encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + )), + Internals.d.M(href, { + crossOrigin: encountered, + integrity: + "string" === typeof options.integrity + ? options.integrity + : void 0, + nonce: + "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } else null == options && Internals.d.M(href); + }; + exports.preload = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + null == options || "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : ("string" === typeof options.as && options.as) || + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingObjectForWarning(options.as) + + "."); + encountered && + console.error( + 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + if ( + "string" === typeof href && + "object" === typeof options && + null !== options && + "string" === typeof options.as + ) { + encountered = options.as; + var crossOrigin = getCrossOriginStringAs( + encountered, + options.crossOrigin + ); + Internals.d.L(href, encountered, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0, + referrerPolicy: + "string" === typeof options.referrerPolicy + ? options.referrerPolicy + : void 0, + imageSrcSet: + "string" === typeof options.imageSrcSet + ? options.imageSrcSet + : void 0, + imageSizes: + "string" === typeof options.imageSizes + ? options.imageSizes + : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } + }; + exports.preloadModule = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + void 0 !== options && "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : options && + "as" in options && + "string" !== typeof options.as && + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingObjectForWarning(options.as) + + "."); + encountered && + console.error( + 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + "string" === typeof href && + (options + ? ((encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + )), + Internals.d.m(href, { + as: + "string" === typeof options.as && "script" !== options.as + ? options.as + : void 0, + crossOrigin: encountered, + integrity: + "string" === typeof options.integrity + ? options.integrity + : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + })) + : Internals.d.m(href)); + }; + exports.version = "19.3.0"; + })(); + + +}, +"./node_modules/react-dom/cjs/react-dom.react-server.production.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-dom.react-server.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var React = __webpack_require__("./node_modules/react/react.react-server.js"); +function noop() {} +var Internals = { + d: { + f: noop, + r: function () { + throw Error( + "Invalid form element. requestFormReset must be passed a form that was rendered by React." + ); + }, + D: noop, + C: noop, + L: noop, + m: noop, + X: noop, + S: noop, + M: noop + }, + p: 0, + findDOMNode: null +}; +if (!React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); +function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; +} +exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + Internals; +exports.preconnect = function (href, options) { + "string" === typeof href && + (options + ? ((options = options.crossOrigin), + (options = + "string" === typeof options + ? "use-credentials" === options + ? options + : "" + : void 0)) + : (options = null), + Internals.d.C(href, options)); +}; +exports.prefetchDNS = function (href) { + "string" === typeof href && Internals.d.D(href); +}; +exports.preinit = function (href, options) { + if ("string" === typeof href && options && "string" === typeof options.as) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), + integrity = + "string" === typeof options.integrity ? options.integrity : void 0, + fetchPriority = + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0; + "style" === as + ? Internals.d.S( + href, + "string" === typeof options.precedence ? options.precedence : void 0, + { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority + } + ) + : "script" === as && + Internals.d.X(href, { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } +}; +exports.preinitModule = function (href, options) { + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) { + var crossOrigin = getCrossOriginStringAs( + options.as, + options.crossOrigin + ); + Internals.d.M(href, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } + } else null == options && Internals.d.M(href); +}; +exports.preload = function (href, options) { + if ( + "string" === typeof href && + "object" === typeof options && + null !== options && + "string" === typeof options.as + ) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); + Internals.d.L(href, as, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0, + referrerPolicy: + "string" === typeof options.referrerPolicy + ? options.referrerPolicy + : void 0, + imageSrcSet: + "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, + imageSizes: + "string" === typeof options.imageSizes ? options.imageSizes : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } +}; +exports.preloadModule = function (href, options) { + if ("string" === typeof href) + if (options) { + var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); + Internals.d.m(href, { + as: + "string" === typeof options.as && "script" !== options.as + ? options.as + : void 0, + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } else Internals.d.m(href); +}; +exports.version = "19.3.0"; + + +}, +"./node_modules/react-dom/react-dom.react-server.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react-dom/cjs/react-dom.react-server.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react-dom/cjs/react-dom.react-server.development.js"); +} + + +}, +"./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-server-dom-rspack-server.node.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function voidHandler() {} + function isClientReference(reference) { + return reference.$$typeof === CLIENT_REFERENCE_TAG$1; + } + function bind() { + var newFn = FunctionBind.apply(this, arguments); + if (this.$$typeof === SERVER_REFERENCE_TAG) { + null != arguments[0] && + console.error( + 'Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().' + ); + var args = ArraySlice.call(arguments, 1), + $$typeof = { value: SERVER_REFERENCE_TAG }, + $$id = { value: this.$$id }; + args = { value: this.$$bound ? this.$$bound.concat(args) : args }; + return Object.defineProperties(newFn, { + $$typeof: $$typeof, + $$id: $$id, + $$bound: args, + $$location: { value: this.$$location, configurable: !0 }, + bind: { value: bind, configurable: !0 } + }); + } + return newFn; + } + function createClientManifest( + clientManifest, + moduleLoading, + cssLinkPrecedence + ) { + return { + clientManifest: clientManifest, + moduleLoading: moduleLoading, + cssLinkPrecedence: cssLinkPrecedence + }; + } + function resolveClientReferenceMetadata(config, clientReference) { + var modulePath = clientReference.$$id, + clientManifest = config.clientManifest, + exportSeparatorIndex = modulePath.lastIndexOf("#"), + clientReferenceId = + -1 === exportSeparatorIndex + ? modulePath + : modulePath.slice(0, exportSeparatorIndex), + name = "", + resolvedModuleData = clientManifest[modulePath]; + if (resolvedModuleData) name = resolvedModuleData.name; + else if ( + (-1 !== exportSeparatorIndex && + ((name = modulePath.slice(exportSeparatorIndex + 1)), + (resolvedModuleData = clientManifest[clientReferenceId])), + !resolvedModuleData) + ) + throw Error( + 'Could not find the module "' + + modulePath + + '" in the React Client Manifest. This is probably a bug in the React Server Components bundler.' + ); + clientManifest = resolvedModuleData.cssFiles || []; + config = config.cssLinkPrecedence; + config = + void 0 === config + ? "rspack-rsc/client-reference" + : !1 === config + ? void 0 + : config; + for ( + exportSeparatorIndex = 0; + exportSeparatorIndex < clientManifest.length; + exportSeparatorIndex++ + ) + ReactDOM.preinit(clientManifest[exportSeparatorIndex], { + as: "style", + precedence: config + }); + if (!0 === resolvedModuleData.async && !0 === clientReference.$$async) + throw Error( + 'The module "' + + modulePath + + '" is marked as an async ESM module but was loaded as a CJS proxy. This is probably a bug in the React Server Components bundler.' + ); + return !0 === resolvedModuleData.async || !0 === clientReference.$$async + ? [resolvedModuleData.id, resolvedModuleData.chunks, name, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } + function noop() {} + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) + return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + function flushBuffered(destination) { + "function" === typeof destination.flush && destination.flush(); + } + function writeChunk(destination, chunk) { + if ("string" === typeof chunk) { + if (0 !== chunk.length) + if (4096 < 3 * chunk.length) + 0 < writtenBytes && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + writeToDestination(destination, chunk); + else { + var target = currentView; + 0 < writtenBytes && (target = currentView.subarray(writtenBytes)); + target = textEncoder.encodeInto(chunk, target); + var read = target.read; + writtenBytes += target.written; + read < chunk.length && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = textEncoder.encodeInto( + chunk.slice(read), + currentView + ).written)); + 4096 === writtenBytes && + (writeToDestination(destination, currentView), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)); + } + } else + 0 !== chunk.byteLength && + (4096 < chunk.byteLength + ? (0 < writtenBytes && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + writeToDestination(destination, chunk)) + : ((target = currentView.length - writtenBytes), + target < chunk.byteLength && + (0 === target + ? writeToDestination(destination, currentView) + : (currentView.set(chunk.subarray(0, target), writtenBytes), + (writtenBytes += target), + writeToDestination(destination, currentView), + (chunk = chunk.subarray(target))), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + currentView.set(chunk, writtenBytes), + (writtenBytes += chunk.byteLength), + 4096 === writtenBytes && + (writeToDestination(destination, currentView), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)))); + } + function writeToDestination(destination, view) { + destination = destination.write(view); + destinationHasCapacity = destinationHasCapacity && destination; + } + function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; + } + function completeWriting(destination) { + currentView && + 0 < writtenBytes && + destination.write(currentView.subarray(0, writtenBytes)); + currentView = null; + writtenBytes = 0; + destinationHasCapacity = !0; + } + function byteLengthOfChunk(chunk) { + return "string" === typeof chunk + ? Buffer.byteLength(chunk, "utf8") + : chunk.byteLength; + } + function preload(href, as, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "L"; + if ("image" === as && options) { + var imageSrcSet = options.imageSrcSet, + imageSizes = options.imageSizes, + uniquePart = ""; + "string" === typeof imageSrcSet && "" !== imageSrcSet + ? ((uniquePart += "[" + imageSrcSet + "]"), + "string" === typeof imageSizes && + (uniquePart += "[" + imageSizes + "]")) + : (uniquePart += "[][]" + href); + key += "[image]" + uniquePart; + } else key += "[" + as + "]" + href; + hints.has(key) || + (hints.add(key), + (options = trimOptions(options)) + ? emitHint(request, "L", [href, as, options]) + : emitHint(request, "L", [href, as])); + } else previousDispatcher.L(href, as, options); + } + } + function preloadModule$1(href, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "m|" + href; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "m", [href, options]) + : emitHint(request, "m", href); + } + previousDispatcher.m(href, options); + } + } + function trimOptions(options) { + if (null == options) return null; + var hasProperties = !1, + trimmed = {}, + key; + for (key in options) + null != options[key] && + ((hasProperties = !0), (trimmed[key] = options[key])); + return hasProperties ? trimmed : null; + } + function getChildFormatContext(parentContext, type, props) { + switch (type) { + case "img": + type = props.src; + var srcSet = props.srcSet; + if ( + !( + "lazy" === props.loading || + (!type && !srcSet) || + ("string" !== typeof type && null != type) || + ("string" !== typeof srcSet && null != srcSet) || + "low" === props.fetchPriority || + parentContext & 3 + ) && + ("string" !== typeof type || + ":" !== type[4] || + ("d" !== type[0] && "D" !== type[0]) || + ("a" !== type[1] && "A" !== type[1]) || + ("t" !== type[2] && "T" !== type[2]) || + ("a" !== type[3] && "A" !== type[3])) && + ("string" !== typeof srcSet || + ":" !== srcSet[4] || + ("d" !== srcSet[0] && "D" !== srcSet[0]) || + ("a" !== srcSet[1] && "A" !== srcSet[1]) || + ("t" !== srcSet[2] && "T" !== srcSet[2]) || + ("a" !== srcSet[3] && "A" !== srcSet[3])) + ) { + var sizes = "string" === typeof props.sizes ? props.sizes : void 0; + var input = props.crossOrigin; + preload(type || "", "image", { + imageSrcSet: srcSet, + imageSizes: sizes, + crossOrigin: + "string" === typeof input + ? "use-credentials" === input + ? input + : "" + : void 0, + integrity: props.integrity, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy + }); + } + return parentContext; + case "link": + type = props.rel; + srcSet = props.href; + if ( + !( + parentContext & 1 || + null != props.itemProp || + "string" !== typeof type || + "string" !== typeof srcSet || + "" === srcSet + ) + ) + switch (type) { + case "preload": + preload(srcSet, props.as, { + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy, + imageSrcSet: props.imageSrcSet, + imageSizes: props.imageSizes, + media: props.media + }); + break; + case "modulepreload": + preloadModule$1(srcSet, { + as: props.as, + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce + }); + break; + case "stylesheet": + preload(srcSet, "style", { + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy, + media: props.media + }); + } + return parentContext; + case "picture": + return parentContext | 2; + case "noscript": + return parentContext | 1; + default: + return parentContext; + } + } + function resolveOwner() { + if (currentOwner) return currentOwner; + var owner = componentStorage.getStore(); + return owner ? owner : null; + } + function resolvePromiseOrAwaitNode(unresolvedNode, endTime) { + unresolvedNode.tag = 3 === unresolvedNode.tag ? 1 : 2; + unresolvedNode.end = endTime; + return unresolvedNode; + } + function getAsyncSequenceFromPromise(promise) { + try { + var asyncId = getAsyncId.call(promise); + } catch (x) {} + if (void 0 === asyncId) return null; + promise = pendingOperations.get(asyncId); + return void 0 === promise ? null : promise; + } + function collectStackTracePrivate(error, structuredStackTrace) { + error = []; + for (var i = framesToSkip; i < structuredStackTrace.length; i++) { + var callSite = structuredStackTrace[i], + name = callSite.getFunctionName() || ""; + if (name.includes("react_stack_bottom_frame")) break; + else if (callSite.isNative()) + (callSite = callSite.isAsync()), + error.push([name, "", 0, 0, 0, 0, callSite]); + else { + if (callSite.isConstructor()) name = "new " + name; + else if (!callSite.isToplevel()) { + var callSite$jscomp$0 = callSite; + name = callSite$jscomp$0.getTypeName(); + var methodName = callSite$jscomp$0.getMethodName(); + callSite$jscomp$0 = callSite$jscomp$0.getFunctionName(); + var result = ""; + callSite$jscomp$0 + ? (name && + identifierRegExp.test(callSite$jscomp$0) && + callSite$jscomp$0 !== name && + (result += name + "."), + (result += callSite$jscomp$0), + !methodName || + callSite$jscomp$0 === methodName || + callSite$jscomp$0.endsWith("." + methodName) || + callSite$jscomp$0.endsWith(" " + methodName) || + (result += " [as " + methodName + "]")) + : (name && (result += name + "."), + (result = methodName + ? result + methodName + : result + "")); + name = result; + } + "" === name && (name = ""); + methodName = callSite.getScriptNameOrSourceURL() || ""; + "" === methodName && + ((methodName = ""), + callSite.isEval() && + (callSite$jscomp$0 = callSite.getEvalOrigin()) && + (methodName = callSite$jscomp$0.toString() + ", ")); + callSite$jscomp$0 = callSite.getLineNumber() || 0; + result = callSite.getColumnNumber() || 0; + var enclosingLine = + "function" === typeof callSite.getEnclosingLineNumber + ? callSite.getEnclosingLineNumber() || 0 + : 0, + enclosingCol = + "function" === typeof callSite.getEnclosingColumnNumber + ? callSite.getEnclosingColumnNumber() || 0 + : 0; + callSite = callSite.isAsync(); + error.push([ + name, + methodName, + callSite$jscomp$0, + result, + enclosingLine, + enclosingCol, + callSite + ]); + } + } + collectedStackTrace = error; + return ""; + } + function collectStackTrace(error, structuredStackTrace) { + collectStackTracePrivate(error, structuredStackTrace); + error = (error.name || "Error") + ": " + (error.message || ""); + for (var i = 0; i < structuredStackTrace.length; i++) + error += "\n at " + structuredStackTrace[i].toString(); + return error; + } + function parseStackTracePrivate(error, skipFrames) { + collectedStackTrace = null; + framesToSkip = skipFrames; + skipFrames = Error.prepareStackTrace; + Error.prepareStackTrace = collectStackTracePrivate; + try { + if ("" !== error.stack) return null; + } finally { + Error.prepareStackTrace = skipFrames; + } + return collectedStackTrace; + } + function parseStackTrace(error, skipFrames) { + var existing = stackTraceCache.get(error); + if (void 0 !== existing) return existing; + collectedStackTrace = null; + framesToSkip = skipFrames; + existing = Error.prepareStackTrace; + Error.prepareStackTrace = collectStackTrace; + try { + var stack = String(error.stack); + } finally { + Error.prepareStackTrace = existing; + } + if (null !== collectedStackTrace) + return ( + (stack = collectedStackTrace), + (collectedStackTrace = null), + stackTraceCache.set(error, stack), + stack + ); + stack.startsWith("Error: react-stack-top-frame\n") && + (stack = stack.slice(29)); + existing = stack.indexOf("react_stack_bottom_frame"); + -1 !== existing && (existing = stack.lastIndexOf("\n", existing)); + -1 !== existing && (stack = stack.slice(0, existing)); + stack = stack.split("\n"); + for (existing = []; skipFrames < stack.length; skipFrames++) { + var parsed = frameRegExp.exec(stack[skipFrames]); + if (parsed) { + var name = parsed[1] || "", + isAsync = "async " === parsed[8]; + "" === name + ? (name = "") + : name.startsWith("async ") && + ((name = name.slice(5)), (isAsync = !0)); + var filename = parsed[2] || parsed[5] || ""; + "" === filename && (filename = ""); + existing.push([ + name, + filename, + +(parsed[3] || parsed[6]), + +(parsed[4] || parsed[7]), + 0, + 0, + isAsync + ]); + } + } + stackTraceCache.set(error, existing); + return existing; + } + function createTemporaryReference(temporaryReferences, id) { + var reference = Object.defineProperties( + function () { + throw Error( + "Attempted to call a temporary Client Reference from the server but it is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component." + ); + }, + { $$typeof: { value: TEMPORARY_REFERENCE_TAG } } + ); + reference = new Proxy(reference, proxyHandlers); + temporaryReferences.set(reference, id); + return reference; + } + function trackUsedThenable(thenableState, thenable, index) { + index = thenableState[index]; + void 0 === index + ? (thenableState.push(thenable), + (thenableState._stacks || (thenableState._stacks = [])).push(Error())) + : index !== thenable && (thenable.then(noop, noop), (thenable = index)); + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + thenableState = thenable.reason; + if (void 0 === thenableState && !("reason" in thenable)) + throw Error( + "A rejected Promise was passed to React without a `reason` property. React threw a generic error from where the Promise was used to assist in identifying the problematic Promise. Make sure that instrumented Promises correctly set the `reason` property when setting `status` to `'rejected'`." + ); + throw thenableState; + default: + "string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenableState = thenable), + (thenableState.status = "pending"), + thenableState.then( + function (fulfilledValue) { + if ("pending" === thenable.status) { + var fulfilledThenable = thenable; + fulfilledThenable.status = "fulfilled"; + fulfilledThenable.value = fulfilledValue; + } + }, + function (error) { + if ("pending" === thenable.status) { + var rejectedThenable = thenable; + rejectedThenable.status = "rejected"; + rejectedThenable.reason = error; + } + } + )); + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + suspendedThenable = thenable; + throw SuspenseException; + } + } + function getSuspendedThenable() { + if (null === suspendedThenable) + throw Error( + "Expected a suspended thenable. This is a bug in React. Please file an issue." + ); + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; + } + function getThenableStateAfterSuspending() { + var state = thenableState || []; + state._componentDebugInfo = currentComponentDebugInfo; + thenableState = currentComponentDebugInfo = null; + return state; + } + function unsupportedHook() { + throw Error("This Hook is not supported in Server Components."); + } + function unsupportedRefresh() { + throw Error( + "Refreshing the cache is not supported in Server Components." + ); + } + function unsupportedContext() { + throw Error("Cannot read a Client Context from a Server Component."); + } + function prepareStackTrace(error, structuredStackTrace) { + error = (error.name || "Error") + ": " + (error.message || ""); + for (var i = 0; i < structuredStackTrace.length; i++) + error += "\n at " + structuredStackTrace[i].toString(); + return error; + } + function resetOwnerStackLimit() { + var now = getCurrentTime(); + 1e3 < now - lastResetTime && + ((ReactSharedInternalsServer.recentlyCreatedOwnerStacks = 0), + (lastResetTime = now)); + } + function isObjectPrototype(object) { + if (!object) return !1; + var ObjectPrototype = Object.prototype; + if (object === ObjectPrototype) return !0; + if (getPrototypeOf(object)) return !1; + object = Object.getOwnPropertyNames(object); + for (var i = 0; i < object.length; i++) + if (!(object[i] in ObjectPrototype)) return !1; + return !0; + } + function isGetter(object, name) { + if (object === Object.prototype || null === object) return !1; + var descriptor = Object.getOwnPropertyDescriptor(object, name); + return void 0 === descriptor + ? isGetter(getPrototypeOf(object), name) + : "function" === typeof descriptor.get; + } + function isSimpleObject(object) { + if (!isObjectPrototype(getPrototypeOf(object))) return !1; + for ( + var names = Object.getOwnPropertyNames(object), i = 0; + i < names.length; + i++ + ) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + if ( + !descriptor || + (!descriptor.enumerable && + (("key" !== names[i] && "ref" !== names[i]) || + "function" !== typeof descriptor.get)) + ) + return !1; + } + return !0; + } + function objectName(object) { + object = Object.prototype.toString.call(object); + return object.slice(8, object.length - 1); + } + function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; + } + function describeValueForErrorMessage(value) { + switch (typeof value) { + case "string": + return JSON.stringify( + 10 >= value.length ? value : value.slice(0, 10) + "..." + ); + case "object": + if (isArrayImpl(value)) return "[...]"; + if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG) + return "client"; + value = objectName(value); + return "Object" === value ? "{...}" : value; + case "function": + return value.$$typeof === CLIENT_REFERENCE_TAG + ? "client" + : (value = value.displayName || value.name) + ? "function " + value + : "function"; + default: + return String(value); + } + } + function describeElementType(type) { + if ("string" === typeof type) return type; + switch (type) { + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + case REACT_MEMO_TYPE: + return describeElementType(type.type); + case REACT_LAZY_TYPE: + var payload = type._payload; + type = type._init; + try { + return describeElementType(type(payload)); + } catch (x) {} + } + return ""; + } + function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + if ("Object" !== objKind && "Array" !== objKind) return objKind; + var start = -1, + length = 0; + if (isArrayImpl(objectOrArray)) + if (jsxChildrenParents.has(objectOrArray)) { + var type = jsxChildrenParents.get(objectOrArray); + objKind = "<" + describeElementType(type) + ">"; + for (var i = 0; i < objectOrArray.length; i++) { + var value = objectOrArray[i]; + value = + "string" === typeof value + ? value + : "object" === typeof value && null !== value + ? "{" + describeObjectForErrorMessage(value) + "}" + : "{" + describeValueForErrorMessage(value) + "}"; + "" + i === expandedName + ? ((start = objKind.length), + (length = value.length), + (objKind += value)) + : (objKind = + 15 > value.length && 40 > objKind.length + value.length + ? objKind + value + : objKind + "{...}"); + } + objKind += ""; + } else { + objKind = "["; + for (type = 0; type < objectOrArray.length; type++) + 0 < type && (objKind += ", "), + (i = objectOrArray[type]), + (i = + "object" === typeof i && null !== i + ? describeObjectForErrorMessage(i) + : describeValueForErrorMessage(i)), + "" + type === expandedName + ? ((start = objKind.length), + (length = i.length), + (objKind += i)) + : (objKind = + 10 > i.length && 40 > objKind.length + i.length + ? objKind + i + : objKind + "..."); + objKind += "]"; + } + else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) + objKind = "<" + describeElementType(objectOrArray.type) + "/>"; + else { + if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client"; + if (jsxPropsParents.has(objectOrArray)) { + objKind = jsxPropsParents.get(objectOrArray); + objKind = "<" + (describeElementType(objKind) || "..."); + type = Object.keys(objectOrArray); + for (i = 0; i < type.length; i++) { + objKind += " "; + value = type[i]; + objKind += describeKeyForErrorMessage(value) + "="; + var _value2 = objectOrArray[value]; + var _substr2 = + value === expandedName && + "object" === typeof _value2 && + null !== _value2 + ? describeObjectForErrorMessage(_value2) + : describeValueForErrorMessage(_value2); + "string" !== typeof _value2 && (_substr2 = "{" + _substr2 + "}"); + value === expandedName + ? ((start = objKind.length), + (length = _substr2.length), + (objKind += _substr2)) + : (objKind = + 10 > _substr2.length && 40 > objKind.length + _substr2.length + ? objKind + _substr2 + : objKind + "..."); + } + objKind += ">"; + } else { + objKind = "{"; + type = Object.keys(objectOrArray); + for (i = 0; i < type.length; i++) + 0 < i && (objKind += ", "), + (value = type[i]), + (objKind += describeKeyForErrorMessage(value) + ": "), + (_value2 = objectOrArray[value]), + (_value2 = + "object" === typeof _value2 && null !== _value2 + ? describeObjectForErrorMessage(_value2) + : describeValueForErrorMessage(_value2)), + value === expandedName + ? ((start = objKind.length), + (length = _value2.length), + (objKind += _value2)) + : (objKind = + 10 > _value2.length && 40 > objKind.length + _value2.length + ? objKind + _value2 + : objKind + "..."); + objKind += "}"; + } + } + return void 0 === expandedName + ? objKind + : -1 < start && 0 < length + ? ((objectOrArray = " ".repeat(start) + "^".repeat(length)), + "\n " + objKind + "\n " + objectOrArray) + : "\n " + objKind; + } + function defaultFilterStackFrame(filename) { + return ( + "" !== filename && + !filename.startsWith("node:") && + !filename.includes("node_modules") + ); + } + function devirtualizeURL(url) { + if (url.startsWith("about://React/")) { + var envIdx = url.indexOf("/", 14), + suffixIdx = url.lastIndexOf("?"); + if (-1 < envIdx && -1 < suffixIdx) + return decodeURI(url.slice(envIdx + 1, suffixIdx)); + } + return url; + } + function isPromiseCreationInternal(url, functionName) { + if ("node:internal/async_hooks" === url) return !0; + if ("" !== url) return !1; + switch (functionName) { + case "new Promise": + case "Function.withResolvers": + case "Promise.withResolvers": + case "Function.reject": + case "Promise.reject": + case "Function.resolve": + case "Promise.resolve": + case "Function.all": + case "Promise.all": + case "Function.allSettled": + case "Promise.allSettled": + case "Function.race": + case "Promise.race": + case "Function.try": + case "Promise.try": + return !0; + default: + return !1; + } + } + function filterStackTrace(request, stack) { + request = request.filterStackFrame; + for (var filteredStack = [], i = 0; i < stack.length; i++) { + var callsite = stack[i], + functionName = callsite[0], + url = devirtualizeURL(callsite[1]); + request(url, functionName, callsite[2], callsite[3]) && + ((callsite = callsite.slice(0)), + (callsite[1] = url), + filteredStack.push(callsite)); + } + return filteredStack; + } + function hasUnfilteredFrame(request, stack) { + request = request.filterStackFrame; + for (var i = 0; i < stack.length; i++) { + var callsite = stack[i], + functionName = callsite[0], + url = devirtualizeURL(callsite[1]), + lineNumber = callsite[2], + columnNumber = callsite[3]; + if ( + !callsite[6] && + request(url, functionName, lineNumber, columnNumber) && + "" !== url + ) + return !0; + } + return !1; + } + function isPromiseAwaitInternal(url, functionName) { + if ("node:internal/async_hooks" === url) return !0; + if ("" !== url) return !1; + switch (functionName) { + case "Promise.then": + case "Promise.catch": + case "Promise.finally": + case "Function.reject": + case "Promise.reject": + case "Function.resolve": + case "Promise.resolve": + case "Function.all": + case "Promise.all": + case "Function.allSettled": + case "Promise.allSettled": + case "Function.any": + case "Promise.any": + case "Function.race": + case "Promise.race": + case "Function.try": + case "Promise.try": + case "Function.withResolvers": + case "Promise.withResolvers": + return !0; + default: + return !1; + } + } + function isAwaitInUserspace(request, stack) { + for ( + var firstFrame = 0; + stack.length > firstFrame && + isPromiseAwaitInternal(stack[firstFrame][1], stack[firstFrame][0]); + + ) + firstFrame++; + if (stack.length > firstFrame) { + request = request.filterStackFrame; + stack = stack[firstFrame]; + firstFrame = stack[0]; + var url = devirtualizeURL(stack[1]); + return request(url, firstFrame, stack[2], stack[3]) && "" !== url; + } + return !1; + } + function patchConsole(consoleInst, methodName) { + var descriptor = Object.getOwnPropertyDescriptor(consoleInst, methodName); + if ( + descriptor && + (descriptor.configurable || descriptor.writable) && + "function" === typeof descriptor.value + ) { + var originalMethod = descriptor.value; + descriptor = Object.getOwnPropertyDescriptor(originalMethod, "name"); + var wrapperMethod = function () { + var request = resolveRequest(); + if (("assert" !== methodName || !arguments[0]) && null !== request) { + var stack = filterStackTrace( + request, + parseStackTracePrivate(Error("react-stack-top-frame"), 1) || [] + ); + request.pendingDebugChunks++; + var owner = resolveOwner(), + args = Array.from(arguments); + a: { + var env = 0; + switch (methodName) { + case "dir": + case "dirxml": + case "groupEnd": + case "table": + env = null; + break a; + case "assert": + env = 1; + } + var format = args[env], + style = args[env + 1], + badge = args[env + 2]; + "string" === typeof format && + format.startsWith("\u001b[0m\u001b[7m%c%s\u001b[0m%c") && + "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px" === + style && + "string" === typeof badge + ? ((format = format.slice(18)), + " " === format[0] && (format = format.slice(1)), + args.splice(env, 4, format), + (env = badge.slice(1, badge.length - 1))) + : (env = null); + } + null === env && (env = (0, request.environmentName)()); + null != owner && outlineComponentInfo(request, owner); + badge = [methodName, stack, owner, env]; + badge.push.apply(badge, args); + args = serializeDebugModel( + request, + (null === request.deferredDebugObjects ? 500 : 10) + stack.length, + badge + ); + "[" !== args[0] && + (args = serializeDebugModel(request, 10 + stack.length, [ + methodName, + stack, + owner, + env, + "Unknown Value: React could not send it from the server." + ])); + request.completedDebugChunks.push(":W" + args + "\n"); + } + return originalMethod.apply(this, arguments); + }; + descriptor && Object.defineProperty(wrapperMethod, "name", descriptor); + Object.defineProperty(consoleInst, methodName, { + value: wrapperMethod + }); + } + } + function getCurrentStackInDEV() { + var owner = resolveOwner(); + if (null === owner) return ""; + try { + var info = ""; + if (owner.owner || "string" !== typeof owner.name) { + for (; owner; ) { + var ownerStack = owner.debugStack; + if (null != ownerStack) { + if ((owner = owner.owner)) { + var JSCompiler_temp_const = info; + var error = ownerStack, + prevPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = prepareStackTrace; + var stack = error.stack; + Error.prepareStackTrace = prevPrepareStackTrace; + stack.startsWith("Error: react-stack-top-frame\n") && + (stack = stack.slice(29)); + var idx = stack.indexOf("\n"); + -1 !== idx && (stack = stack.slice(idx + 1)); + idx = stack.indexOf("react_stack_bottom_frame"); + -1 !== idx && (idx = stack.lastIndexOf("\n", idx)); + var JSCompiler_inline_result = + -1 !== idx ? (stack = stack.slice(0, idx)) : ""; + info = + JSCompiler_temp_const + ("\n" + JSCompiler_inline_result); + } + } else break; + } + var JSCompiler_inline_result$jscomp$0 = info; + } else { + JSCompiler_temp_const = owner.name; + if (void 0 === prefix) + try { + throw Error(); + } catch (x) { + (prefix = + ((error = x.stack.trim().match(/\n( *(at )?)/)) && error[1]) || + ""), + (suffix = + -1 < x.stack.indexOf("\n at") + ? " ()" + : -1 < x.stack.indexOf("@") + ? "@unknown:0:0" + : ""); + } + JSCompiler_inline_result$jscomp$0 = + "\n" + prefix + JSCompiler_temp_const + suffix; + } + } catch (x) { + JSCompiler_inline_result$jscomp$0 = + "\nError generating stack: " + x.message + "\n" + x.stack; + } + return JSCompiler_inline_result$jscomp$0; + } + function defaultErrorHandler(error) { + console.error(error); + } + function RequestInstance( + type, + model, + bundlerConfig, + onError, + onAllReady, + onFatalError, + identifierPrefix, + temporaryReferences, + debugStartTime, + environmentName, + filterStackFrame, + keepDebugAlive + ) { + if ( + null !== ReactSharedInternalsServer.A && + ReactSharedInternalsServer.A !== DefaultAsyncDispatcher + ) + throw Error( + "Currently React only supports one RSC renderer at a time." + ); + ReactSharedInternalsServer.A = DefaultAsyncDispatcher; + ReactSharedInternalsServer.getCurrentStack = getCurrentStackInDEV; + var abortSet = new Set(), + pingedTasks = [], + hints = new Set(); + this.type = type; + this.status = OPENING; + this.flushScheduled = !1; + this.destination = this.fatalError = null; + this.bundlerConfig = bundlerConfig; + this.cache = new Map(); + this.cacheController = new AbortController(); + this.pendingChunks = this.nextChunkId = 0; + this.hints = hints; + this.abortableTasks = abortSet; + this.pingedTasks = pingedTasks; + this.completedImportChunks = []; + this.completedHintChunks = []; + this.completedRegularChunks = []; + this.completedErrorChunks = []; + this.writtenSymbols = new Map(); + this.writtenClientReferences = new Map(); + this.writtenServerReferences = new Map(); + this.writtenObjects = new WeakMap(); + this.temporaryReferences = temporaryReferences; + this.identifierPrefix = identifierPrefix || ""; + this.identifierCount = 1; + this.taintCleanupQueue = []; + this.onError = void 0 === onError ? defaultErrorHandler : onError; + this.onAllReady = onAllReady; + this.onFatalError = onFatalError; + this.pendingDebugChunks = 0; + this.completedDebugChunks = []; + this.debugDestination = null; + this.environmentName = + void 0 === environmentName + ? function () { + return "Server"; + } + : "function" !== typeof environmentName + ? function () { + return environmentName; + } + : environmentName; + this.filterStackFrame = + void 0 === filterStackFrame + ? defaultFilterStackFrame + : filterStackFrame; + this.didWarnForKey = null; + this.writtenDebugObjects = new WeakMap(); + this.deferredDebugObjects = keepDebugAlive + ? { retained: new Map(), existing: new Map() } + : null; + type = + "number" === typeof debugStartTime + ? (this.timeOrigin = debugStartTime - performance.timeOrigin) + : (this.timeOrigin = performance.now()); + emitTimeOriginChunk(this, type + performance.timeOrigin); + this.abortTime = -0; + model = createTask( + this, + model, + null, + !1, + 0, + abortSet, + type, + null, + null, + null + ); + pingedTasks.push(model); + } + function createRequest( + model, + bundlerConfig, + onError, + identifierPrefix, + temporaryReferences, + debugStartTime, + environmentName, + filterStackFrame, + keepDebugAlive + ) { + resetOwnerStackLimit(); + return new RequestInstance( + 20, + model, + bundlerConfig, + onError, + noop, + noop, + identifierPrefix, + temporaryReferences, + debugStartTime, + environmentName, + filterStackFrame, + keepDebugAlive + ); + } + function createPrerenderRequest( + model, + bundlerConfig, + onAllReady, + onFatalError, + onError, + identifierPrefix, + temporaryReferences, + debugStartTime, + environmentName, + filterStackFrame, + keepDebugAlive + ) { + resetOwnerStackLimit(); + return new RequestInstance( + PRERENDER, + model, + bundlerConfig, + onError, + onAllReady, + onFatalError, + identifierPrefix, + temporaryReferences, + debugStartTime, + environmentName, + filterStackFrame, + keepDebugAlive + ); + } + function resolveRequest() { + if (currentRequest) return currentRequest; + var store = requestStorage.getStore(); + return store ? store : null; + } + function serializeDebugThenable(request, counter, thenable) { + request.pendingDebugChunks++; + var id = request.nextChunkId++, + ref = "$@" + id.toString(16); + request.writtenDebugObjects.set(thenable, ref); + switch (thenable.status) { + case "fulfilled": + return ( + emitOutlinedDebugModelChunk(request, id, counter, thenable.value), + ref + ); + case "rejected": + return ( + emitErrorChunk(request, id, "", thenable.reason, !0, null), ref + ); + } + if (request.status === ABORTING) + return emitDebugHaltChunk(request, id), ref; + var deferredDebugObjects = request.deferredDebugObjects; + if (null !== deferredDebugObjects) + return ( + deferredDebugObjects.retained.set(id, thenable), + (ref = "$Y@" + id.toString(16)), + request.writtenDebugObjects.set(thenable, ref), + ref + ); + var cancelled = !1; + thenable.then( + function (value) { + cancelled || + ((cancelled = !0), + request.status === ABORTING + ? emitDebugHaltChunk(request, id) + : (isArrayImpl(value) && 200 < value.length) || + ((value instanceof ArrayBuffer || + value instanceof Int8Array || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray || + value instanceof Int16Array || + value instanceof Uint16Array || + value instanceof Int32Array || + value instanceof Uint32Array || + value instanceof Float32Array || + value instanceof Float64Array || + value instanceof BigInt64Array || + value instanceof BigUint64Array || + value instanceof DataView) && + 1e3 < value.byteLength) + ? emitDebugHaltChunk(request, id) + : emitOutlinedDebugModelChunk(request, id, counter, value), + enqueueFlush(request)); + }, + function (reason) { + cancelled || + ((cancelled = !0), + request.status === ABORTING + ? emitDebugHaltChunk(request, id) + : emitErrorChunk(request, id, "", reason, !0, null), + enqueueFlush(request)); + } + ); + Promise.resolve().then(function () { + cancelled || + ((cancelled = !0), + emitDebugHaltChunk(request, id), + enqueueFlush(request), + (counter = request = null)); + }); + return ref; + } + function emitRequestedDebugThenable(request, id, counter, thenable) { + thenable.then( + function (value) { + request.status === ABORTING + ? emitDebugHaltChunk(request, id) + : emitOutlinedDebugModelChunk(request, id, counter, value); + enqueueFlush(request); + }, + function (reason) { + request.status === ABORTING + ? emitDebugHaltChunk(request, id) + : emitErrorChunk(request, id, "", reason, !0, null); + enqueueFlush(request); + } + ); + } + function createThenableTask(request, task, thenable) { + return createTask( + request, + thenable, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + ); + } + function serializeThenable(request, task, thenable) { + switch (thenable.status) { + case "fulfilled": + return ( + (task = createThenableTask(request, task, thenable)), + forwardDebugInfoFromThenable(request, task, thenable, null, null), + (task.model = thenable.value), + pingTask(request, task), + task.id + ); + case "rejected": + return ( + (task = createThenableTask(request, task, thenable)), + forwardDebugInfoFromThenable(request, task, thenable, null, null), + erroredTask(request, task, thenable.reason), + task.id + ); + default: + var _newTask2 = createThenableTask(request, task, thenable); + if (request.status === ABORTING) + return ( + request.abortableTasks.delete(_newTask2), + request.type === PRERENDER + ? (haltTask(_newTask2), finishHaltedTask(_newTask2, request)) + : ((task = request.fatalError), + abortTask(_newTask2), + finishAbortedTask(_newTask2, request, task)), + _newTask2.id + ); + "string" !== typeof thenable.status && + ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + )); + thenable.then( + function (value) { + forwardDebugInfoFromCurrentContext(request, _newTask2, thenable); + _newTask2.model = value; + pingTask(request, _newTask2); + }, + function (reason) { + _newTask2.status === PENDING$1 && + ((_newTask2.timed = !0), + erroredTask(request, _newTask2, reason), + enqueueFlush(request)); + } + ); + return _newTask2.id; + } + } + function serializeReadableStream(request, task, stream) { + function progress(entry) { + if (streamTask.status === PENDING$1) + if (entry.done) + (streamTask.status = COMPLETED), + (entry = streamTask.id.toString(16) + ":C\n"), + request.completedRegularChunks.push(entry), + request.abortableTasks.delete(streamTask), + request.cacheController.signal.removeEventListener( + "abort", + abortStream + ), + enqueueFlush(request), + callOnAllReadyIfReady(request); + else + try { + request.pendingChunks++, + (streamTask.model = entry.value), + isByteStream + ? emitTypedArrayChunk( + request, + streamTask.id, + "b", + streamTask.model, + !1 + ) + : tryStreamTask(request, streamTask), + enqueueFlush(request), + reader.read().then(progress, error); + } catch (x$6) { + error(x$6); + } + } + function error(reason) { + streamTask.status === PENDING$1 && + (request.cacheController.signal.removeEventListener( + "abort", + abortStream + ), + erroredTask(request, streamTask, reason), + enqueueFlush(request), + reader.cancel(reason).then(error, error)); + } + function abortStream() { + if (streamTask.status === PENDING$1) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortStream); + signal = signal.reason; + request.type === PRERENDER + ? (request.abortableTasks.delete(streamTask), + haltTask(streamTask), + finishHaltedTask(streamTask, request)) + : (erroredTask(request, streamTask, signal), enqueueFlush(request)); + reader.cancel(signal).then(error, error); + } + } + var supportsBYOB = stream.supportsBYOB; + if (void 0 === supportsBYOB) + try { + stream.getReader({ mode: "byob" }).releaseLock(), (supportsBYOB = !0); + } catch (x) { + supportsBYOB = !1; + } + var isByteStream = supportsBYOB, + reader = stream.getReader(), + streamTask = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + ); + request.pendingChunks++; + task = + streamTask.id.toString(16) + ":" + (isByteStream ? "r" : "R") + "\n"; + request.completedRegularChunks.push(task); + request.cacheController.signal.addEventListener("abort", abortStream); + reader.read().then(progress, error); + return serializeByValueID(streamTask.id); + } + function serializeAsyncIterable(request, task, iterable, iterator) { + function progress(entry) { + if (streamTask.status === PENDING$1) + if (entry.done) { + streamTask.status = COMPLETED; + if (void 0 === entry.value) + var endStreamRow = streamTask.id.toString(16) + ":C\n"; + else + try { + var chunkId = outlineModel(request, entry.value); + endStreamRow = + streamTask.id.toString(16) + + ":C" + + stringify(serializeByValueID(chunkId)) + + "\n"; + } catch (x) { + error(x); + return; + } + request.completedRegularChunks.push(endStreamRow); + request.abortableTasks.delete(streamTask); + request.cacheController.signal.removeEventListener( + "abort", + abortIterable + ); + enqueueFlush(request); + callOnAllReadyIfReady(request); + } else + try { + (streamTask.model = entry.value), + request.pendingChunks++, + tryStreamTask(request, streamTask), + enqueueFlush(request), + callIteratorInDEV(iterator, progress, error); + } catch (x$7) { + error(x$7); + } + } + function error(reason) { + streamTask.status === PENDING$1 && + (request.cacheController.signal.removeEventListener( + "abort", + abortIterable + ), + erroredTask(request, streamTask, reason), + enqueueFlush(request), + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop)); + } + function abortIterable() { + if (streamTask.status === PENDING$1) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortIterable); + var reason = signal.reason; + request.type === PRERENDER + ? (request.abortableTasks.delete(streamTask), + haltTask(streamTask), + finishHaltedTask(streamTask, request)) + : (erroredTask(request, streamTask, signal.reason), + enqueueFlush(request)); + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop); + } + } + var isIterator = iterable === iterator, + streamTask = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + ); + (task = iterable._debugInfo) && + forwardDebugInfo(request, streamTask, task); + request.pendingChunks++; + isIterator = + streamTask.id.toString(16) + ":" + (isIterator ? "x" : "X") + "\n"; + request.completedRegularChunks.push(isIterator); + request.cacheController.signal.addEventListener("abort", abortIterable); + callIteratorInDEV(iterator, progress, error); + return serializeByValueID(streamTask.id); + } + function emitHint(request, code, model) { + model = stringify(model); + request.completedHintChunks.push(":H" + code + model + "\n"); + enqueueFlush(request); + } + function readThenable(thenable) { + if ("fulfilled" === thenable.status) return thenable.value; + if ("rejected" === thenable.status) throw thenable.reason; + throw thenable; + } + function createLazyWrapperAroundWakeable(request, task, wakeable) { + switch (wakeable.status) { + case "fulfilled": + return ( + forwardDebugInfoFromThenable(request, task, wakeable, null, null), + wakeable.value + ); + case "rejected": + forwardDebugInfoFromThenable(request, task, wakeable, null, null); + break; + default: + "string" !== typeof wakeable.status && + ((wakeable.status = "pending"), + wakeable.then( + function (fulfilledValue) { + forwardDebugInfoFromCurrentContext(request, task, wakeable); + "pending" === wakeable.status && + ((wakeable.status = "fulfilled"), + (wakeable.value = fulfilledValue)); + }, + function (error) { + forwardDebugInfoFromCurrentContext(request, task, wakeable); + "pending" === wakeable.status && + ((wakeable.status = "rejected"), (wakeable.reason = error)); + } + )); + } + return { + $$typeof: REACT_LAZY_TYPE, + _payload: wakeable, + _init: readThenable + }; + } + function callWithDebugContextInDEV(request, task, callback, arg) { + var componentDebugInfo = { + name: "", + env: task.environmentName, + key: null, + owner: task.debugOwner + }; + componentDebugInfo.stack = + null === task.debugStack + ? null + : filterStackTrace(request, parseStackTrace(task.debugStack, 1)); + componentDebugInfo.debugStack = task.debugStack; + request = componentDebugInfo.debugTask = task.debugTask; + currentOwner = componentDebugInfo; + try { + return request ? request.run(callback.bind(null, arg)) : callback(arg); + } finally { + currentOwner = null; + } + } + function processServerComponentReturnValue( + request, + task, + Component, + result + ) { + if ( + "object" !== typeof result || + null === result || + isClientReference(result) + ) + return result; + if ("function" === typeof result.then) + return ( + result.then(function (resolvedValue) { + "object" === typeof resolvedValue && + null !== resolvedValue && + resolvedValue.$$typeof === REACT_ELEMENT_TYPE && + (resolvedValue._store.validated = 1); + }, voidHandler), + createLazyWrapperAroundWakeable(request, task, result) + ); + result.$$typeof === REACT_ELEMENT_TYPE && (result._store.validated = 1); + var iteratorFn = getIteratorFn(result); + if (iteratorFn) { + var $jscomp$compprop0 = {}; + $jscomp$compprop0 = + (($jscomp$compprop0[Symbol.iterator] = function () { + var iterator = iteratorFn.call(result); + iterator !== result || + ("[object GeneratorFunction]" === + Object.prototype.toString.call(Component) && + "[object Generator]" === + Object.prototype.toString.call(result)) || + callWithDebugContextInDEV(request, task, function () { + console.error( + "Returning an Iterator from a Server Component is not supported since it cannot be looped over more than once. " + ); + }); + return iterator; + }), + $jscomp$compprop0); + $jscomp$compprop0._debugInfo = result._debugInfo; + return $jscomp$compprop0; + } + return "function" !== typeof result[ASYNC_ITERATOR] || + ("function" === typeof ReadableStream && + result instanceof ReadableStream) + ? result + : (($jscomp$compprop0 = {}), + ($jscomp$compprop0 = + (($jscomp$compprop0[ASYNC_ITERATOR] = function () { + var iterator = result[ASYNC_ITERATOR](); + iterator !== result || + ("[object AsyncGeneratorFunction]" === + Object.prototype.toString.call(Component) && + "[object AsyncGenerator]" === + Object.prototype.toString.call(result)) || + callWithDebugContextInDEV(request, task, function () { + console.error( + "Returning an AsyncIterator from a Server Component is not supported since it cannot be looped over more than once. " + ); + }); + return iterator; + }), + $jscomp$compprop0)), + ($jscomp$compprop0._debugInfo = result._debugInfo), + $jscomp$compprop0); + } + function renderFunctionComponent( + request, + task, + key, + Component, + props, + validated + ) { + var prevThenableState = task.thenableState; + task.thenableState = null; + if (canEmitDebugInfo) + if (null !== prevThenableState) + var componentDebugInfo = prevThenableState._componentDebugInfo; + else { + var componentDebugID = task.id; + componentDebugInfo = Component.displayName || Component.name || ""; + var componentEnv = (0, request.environmentName)(); + request.pendingChunks++; + componentDebugInfo = { + name: componentDebugInfo, + env: componentEnv, + key: key, + owner: task.debugOwner + }; + componentDebugInfo.stack = + null === task.debugStack + ? null + : filterStackTrace(request, parseStackTrace(task.debugStack, 1)); + componentDebugInfo.props = props; + componentDebugInfo.debugStack = task.debugStack; + componentDebugInfo.debugTask = task.debugTask; + outlineComponentInfo(request, componentDebugInfo); + advanceTaskTime(request, task, performance.now()); + emitDebugChunk(request, componentDebugID, componentDebugInfo); + task.environmentName = componentEnv; + 2 === validated && + warnForMissingKey(request, key, componentDebugInfo, task.debugTask); + } + else return outlineTask(request, task); + thenableIndexCounter = 0; + thenableState = prevThenableState; + currentComponentDebugInfo = componentDebugInfo; + props = task.debugTask + ? task.debugTask.run( + componentStorage.run.bind( + componentStorage, + componentDebugInfo, + callComponentInDEV, + Component, + props, + componentDebugInfo + ) + ) + : componentStorage.run( + componentDebugInfo, + callComponentInDEV, + Component, + props, + componentDebugInfo + ); + if (request.status === ABORTING) + throw ( + ("object" !== typeof props || + null === props || + "function" !== typeof props.then || + isClientReference(props) || + props.then(voidHandler, voidHandler), + null) + ); + validated = thenableState; + if (null !== validated) + for ( + prevThenableState = validated._stacks || (validated._stacks = []), + componentDebugID = 0; + componentDebugID < validated.length; + componentDebugID++ + ) + forwardDebugInfoFromThenable( + request, + task, + validated[componentDebugID], + componentDebugInfo, + prevThenableState[componentDebugID] + ); + props = processServerComponentReturnValue( + request, + task, + Component, + props + ); + task.debugOwner = componentDebugInfo; + task.debugStack = null; + task.debugTask = null; + Component = task.keyPath; + componentDebugInfo = task.implicitSlot; + null !== key + ? (task.keyPath = + key === REACT_OPTIMISTIC_KEY || Component === REACT_OPTIMISTIC_KEY + ? REACT_OPTIMISTIC_KEY + : null === Component + ? key + : Component + "," + key) + : null === Component && (task.implicitSlot = !0); + request = renderModelDestructive(request, task, emptyRoot, "", props); + task.keyPath = Component; + task.implicitSlot = componentDebugInfo; + return request; + } + function warnForMissingKey(request, key, componentDebugInfo, debugTask) { + function logKeyError() { + console.error( + 'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.', + "", + "" + ); + } + key = request.didWarnForKey; + null == key && (key = request.didWarnForKey = new WeakSet()); + request = componentDebugInfo.owner; + if (null != request) { + if (key.has(request)) return; + key.add(request); + } + debugTask + ? debugTask.run( + componentStorage.run.bind( + componentStorage, + componentDebugInfo, + callComponentInDEV, + logKeyError, + null, + componentDebugInfo + ) + ) + : componentStorage.run( + componentDebugInfo, + callComponentInDEV, + logKeyError, + null, + componentDebugInfo + ); + } + function renderFragment(request, task, children) { + for (var i = 0; i < children.length; i++) { + var child = children[i]; + null === child || + "object" !== typeof child || + child.$$typeof !== REACT_ELEMENT_TYPE || + null !== child.key || + child._store.validated || + (child._store.validated = 2); + } + if (null !== task.keyPath) + return ( + (request = [ + REACT_ELEMENT_TYPE, + REACT_FRAGMENT_TYPE, + task.keyPath, + { children: children }, + null, + null, + 0 + ]), + task.implicitSlot ? [request] : request + ); + if ((i = children._debugInfo)) { + if (canEmitDebugInfo) forwardDebugInfo(request, task, i); + else return outlineTask(request, task); + children = Array.from(children); + } + return children; + } + function renderAsyncFragment(request, task, children, getAsyncIterator) { + if (null !== task.keyPath) + return ( + (request = [ + REACT_ELEMENT_TYPE, + REACT_FRAGMENT_TYPE, + task.keyPath, + { children: children }, + null, + null, + 0 + ]), + task.implicitSlot ? [request] : request + ); + getAsyncIterator = getAsyncIterator.call(children); + return serializeAsyncIterable(request, task, children, getAsyncIterator); + } + function deferTask(request, task) { + task = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + ); + pingTask(request, task); + return serializeLazyID(task.id); + } + function outlineTask(request, task) { + task = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + ); + retryTask(request, task); + return task.status === COMPLETED + ? serializeByValueID(task.id) + : serializeLazyID(task.id); + } + function renderElement(request, task, type, key, ref, props, validated) { + if (null !== ref && void 0 !== ref) + throw Error( + "Refs cannot be used in Server Components, nor passed to Client Components." + ); + jsxPropsParents.set(props, type); + "object" === typeof props.children && + null !== props.children && + jsxChildrenParents.set(props.children, type); + if ( + "function" !== typeof type || + isClientReference(type) || + type.$$typeof === TEMPORARY_REFERENCE_TAG + ) { + if (type === REACT_FRAGMENT_TYPE && null === key) + return ( + 2 === validated && + ((validated = { + name: "Fragment", + env: (0, request.environmentName)(), + key: key, + owner: task.debugOwner, + stack: + null === task.debugStack + ? null + : filterStackTrace( + request, + parseStackTrace(task.debugStack, 1) + ), + props: props, + debugStack: task.debugStack, + debugTask: task.debugTask + }), + warnForMissingKey(request, key, validated, task.debugTask)), + (validated = task.implicitSlot), + null === task.keyPath && (task.implicitSlot = !0), + (request = renderModelDestructive( + request, + task, + emptyRoot, + "", + props.children + )), + (task.implicitSlot = validated), + request + ); + if ( + null != type && + "object" === typeof type && + !isClientReference(type) + ) + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + type = callLazyInitInDEV(type); + if (request.status === ABORTING) throw null; + return renderElement( + request, + task, + type, + key, + ref, + props, + validated + ); + case REACT_FORWARD_REF_TYPE: + return renderFunctionComponent( + request, + task, + key, + type.render, + props, + validated + ); + case REACT_MEMO_TYPE: + return renderElement( + request, + task, + type.type, + key, + ref, + props, + validated + ); + case REACT_ELEMENT_TYPE: + type._store.validated = 1; + } + else if ("string" === typeof type) { + ref = task.formatContext; + var newFormatContext = getChildFormatContext(ref, type, props); + ref !== newFormatContext && + null != props.children && + outlineModelWithFormatContext( + request, + props.children, + newFormatContext + ); + } + } else + return renderFunctionComponent( + request, + task, + key, + type, + props, + validated + ); + ref = task.keyPath; + null === key + ? (key = ref) + : null !== ref && + (key = + ref === REACT_OPTIMISTIC_KEY || key === REACT_OPTIMISTIC_KEY + ? REACT_OPTIMISTIC_KEY + : ref + "," + key); + newFormatContext = null; + ref = task.debugOwner; + null !== ref && outlineComponentInfo(request, ref); + if (null !== task.debugStack) { + newFormatContext = filterStackTrace( + request, + parseStackTrace(task.debugStack, 1) + ); + var id = outlineDebugModel( + request, + { objectLimit: 2 * newFormatContext.length + 1 }, + newFormatContext + ); + request.writtenObjects.set(newFormatContext, serializeByValueID(id)); + } + request = [ + REACT_ELEMENT_TYPE, + type, + key, + props, + ref, + newFormatContext, + validated + ]; + task = task.implicitSlot && null !== key ? [request] : request; + return task; + } + function visitAsyncNode( + request, + task$jscomp$0, + node$jscomp$0, + visited, + cutOff + ) { + for ( + var chain = []; + null !== node$jscomp$0 && !visited.has(node$jscomp$0); + + ) + chain.push(node$jscomp$0), (node$jscomp$0 = node$jscomp$0.previous); + var previousIONode = + null !== node$jscomp$0 ? visited.get(node$jscomp$0) : null; + for ( + node$jscomp$0 = chain.length - 1; + 0 <= node$jscomp$0; + node$jscomp$0-- + ) { + var n = chain[node$jscomp$0]; + visited.set(n, null); + var result = request; + var task = task$jscomp$0, + node = n, + visited$jscomp$0 = visited, + cutOff$jscomp$0 = cutOff; + if (0 <= node.end && node.end <= result.timeOrigin) result = null; + else + switch (node.tag) { + case 0: + result = node; + break; + case 3: + result = previousIONode; + break; + case 1: + var awaited = node.awaited, + promise = node.promise.deref(); + if (null !== awaited) + if ( + ((cutOff$jscomp$0 = visitAsyncNode( + result, + task, + awaited, + visited$jscomp$0, + cutOff$jscomp$0 + )), + void 0 === cutOff$jscomp$0) + ) { + result = void 0; + break; + } else + null !== cutOff$jscomp$0 + ? (previousIONode = + 1 === cutOff$jscomp$0.tag + ? cutOff$jscomp$0 + : (null !== node.stack && + hasUnfilteredFrame(result, node.stack)) || + (void 0 !== promise && + "string" === typeof promise.displayName && + (null === cutOff$jscomp$0.stack || + !hasUnfilteredFrame( + result, + cutOff$jscomp$0.stack + ))) + ? node + : cutOff$jscomp$0) + : result.status === ABORTING && + node.start < result.abortTime && + node.end > result.abortTime && + ((null !== node.stack && + hasUnfilteredFrame(result, node.stack)) || + (void 0 !== promise && + "string" === typeof promise.displayName)) && + (previousIONode = node); + void 0 !== promise && + ((node = promise._debugInfo), + null == node || + visited$jscomp$0.has(node) || + (visited$jscomp$0.set(node, null), + forwardDebugInfo(result, task, node))); + result = previousIONode; + break; + case 4: + result = previousIONode; + break; + case 2: + awaited = node.awaited; + if (null !== awaited) + if ( + ((promise = visitAsyncNode( + result, + task, + awaited, + visited$jscomp$0, + cutOff$jscomp$0 + )), + void 0 === promise) + ) { + result = void 0; + break; + } else if (null !== promise) { + var startTime = node.start, + endTime = node.end; + startTime < cutOff$jscomp$0 + ? ((previousIONode = promise), + null !== node.stack && + isAwaitInUserspace(result, node.stack) && + void 0 !== + (null === awaited.promise + ? void 0 + : awaited.promise.deref()) && + serializeIONode(result, promise, awaited.promise)) + : null !== node.stack && + isAwaitInUserspace(result, node.stack) + ? (result.status === ABORTING && + startTime > result.abortTime) || + (serializeIONode(result, promise, awaited.promise), + visited$jscomp$0.set(promise, null), + null != node.owner && + outlineComponentInfo(result, node.owner), + (cutOff$jscomp$0 = (0, result.environmentName)()), + advanceTaskTime(result, task, startTime), + result.pendingChunks++, + emitDebugChunk(result, task.id, { + awaited: promise, + env: cutOff$jscomp$0, + owner: node.owner, + stack: + null === node.stack + ? null + : filterStackTrace(result, node.stack) + }), + markOperationEndTime(result, task, endTime), + result.status === ABORTING && (previousIONode = void 0)) + : (previousIONode = promise); + } + node = node.promise.deref(); + void 0 !== node && + ((node = node._debugInfo), + null == node || + visited$jscomp$0.has(node) || + (visited$jscomp$0.set(node, null), + forwardDebugInfo(result, task, node))); + result = previousIONode; + break; + default: + throw Error("Unknown AsyncSequence tag. This is a bug in React."); + } + null !== result && visited.set(n, result); + if (void 0 === result) return; + previousIONode = result; + } + return previousIONode; + } + function emitAsyncSequence( + request, + task, + node, + alreadyForwardedDebugInfo, + owner, + stack + ) { + var visited = new Map(); + alreadyForwardedDebugInfo && visited.set(alreadyForwardedDebugInfo, null); + node = visitAsyncNode(request, task, node, visited, task.time); + void 0 !== node && + null !== node && + (serializeIONode(request, node, node.promise), + request.pendingChunks++, + (alreadyForwardedDebugInfo = (0, request.environmentName)()), + (alreadyForwardedDebugInfo = { + awaited: node, + env: alreadyForwardedDebugInfo + }), + null === owner && null === stack + ? (null !== task.debugOwner && + (alreadyForwardedDebugInfo.owner = task.debugOwner), + null !== task.debugStack && + (alreadyForwardedDebugInfo.stack = filterStackTrace( + request, + parseStackTrace(task.debugStack, 1) + ))) + : (null != owner && (alreadyForwardedDebugInfo.owner = owner), + null != stack && + (alreadyForwardedDebugInfo.stack = filterStackTrace( + request, + parseStackTrace(stack, 1) + ))), + advanceTaskTime(request, task, task.time), + emitDebugChunk(request, task.id, alreadyForwardedDebugInfo), + markOperationEndTime(request, task, node.end)); + } + function pingTask(request, task) { + task.timed = !0; + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + 1 === pingedTasks.length && + ((request.flushScheduled = null !== request.destination), + request.type === PRERENDER || request.status === OPENING + ? scheduleMicrotask(function () { + return performWork(request); + }) + : setImmediate(function () { + return performWork(request); + })); + } + function createTask( + request, + model, + keyPath, + implicitSlot, + formatContext, + abortSet, + lastTimestamp, + debugOwner, + debugStack, + debugTask + ) { + return createTaskWithID( + request, + request.nextChunkId++, + model, + keyPath, + implicitSlot, + formatContext, + abortSet, + lastTimestamp, + debugOwner, + debugStack, + debugTask + ); + } + function createTaskWithID( + request, + id, + model, + keyPath, + implicitSlot, + formatContext, + abortSet, + lastTimestamp, + debugOwner, + debugStack, + debugTask + ) { + request.pendingChunks++; + "object" !== typeof model || + null === model || + null !== keyPath || + implicitSlot || + request.writtenObjects.set(model, serializeByValueID(id)); + var task = { + id: id, + status: PENDING$1, + model: model, + keyPath: keyPath, + implicitSlot: implicitSlot, + formatContext: formatContext, + ping: function () { + return pingTask(request, task); + }, + thenableState: null, + timed: !1 + }; + task.time = lastTimestamp; + task.environmentName = request.environmentName(); + task.debugOwner = debugOwner; + task.debugStack = debugStack; + task.debugTask = debugTask; + abortSet.add(task); + return task; + } + function resolveModel(request, task, parent, parentPropertyName, value) { + var jsonValue = value; + null !== value && + "object" === typeof value && + "function" === typeof value.toJSON && + (jsonValue = value.toJSON(parentPropertyName)); + var originalValue = parent[parentPropertyName]; + "object" !== typeof originalValue || + originalValue === jsonValue || + originalValue instanceof Date || + callWithDebugContextInDEV(request, task, function () { + ArrayBuffer.isView(originalValue) + ? console.error( + "Binary data with a toJSON method, such as a Node.js Buffer, is serialized through toJSON instead of as binary. Pass a Uint8Array or ArrayBuffer to send binary data.%s", + describeObjectForErrorMessage(parent, parentPropertyName) + ) + : "Object" !== objectName(originalValue) + ? "string" === typeof jsxChildrenParents.get(parent) + ? console.error( + "%s objects cannot be rendered as text children. Try formatting it using toString().%s", + objectName(originalValue), + describeObjectForErrorMessage(parent, parentPropertyName) + ) + : console.error( + "Only plain objects can be passed to Client Components from Server Components. %s objects are not supported.%s", + objectName(originalValue), + describeObjectForErrorMessage(parent, parentPropertyName) + ) + : console.error( + "Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.%s", + describeObjectForErrorMessage(parent, parentPropertyName) + ); + }); + value = renderModel(request, task, parent, parentPropertyName, jsonValue); + if (null === value || "object" !== typeof value) return value; + if (isArrayImpl(value)) { + var _resolved = []; + for (jsonValue = 0; jsonValue < value.length; jsonValue++) + _resolved[jsonValue] = resolveModel( + request, + task, + value, + "" + jsonValue, + value[jsonValue] + ); + return _resolved; + } + jsonValue = {}; + for (_resolved in value) + if (hasOwnProperty.call(value, _resolved)) { + var resolvedValue = resolveModel( + request, + task, + value, + _resolved, + value[_resolved] + ); + _resolved === __PROTO__$1 + ? Object.defineProperty(jsonValue, _resolved, { + value: resolvedValue, + enumerable: !0, + writable: !0, + configurable: !0 + }) + : (jsonValue[_resolved] = resolvedValue); + } + return jsonValue; + } + function serializeByValueID(id) { + return "$" + id.toString(16); + } + function serializeLazyID(id) { + return "$L" + id.toString(16); + } + function serializeDeferredObject(request, value) { + var deferredDebugObjects = request.deferredDebugObjects; + return null !== deferredDebugObjects + ? (request.pendingDebugChunks++, + (request = request.nextChunkId++), + deferredDebugObjects.existing.set(value, request), + deferredDebugObjects.retained.set(request, value), + "$Y" + request.toString(16)) + : "$Y"; + } + function serializeNumber(number) { + return Number.isFinite(number) + ? 0 === number && -Infinity === 1 / number + ? "$-0" + : number + : Infinity === number + ? "$Infinity" + : -Infinity === number + ? "$-Infinity" + : "$NaN"; + } + function encodeReferenceChunk(request, id, reference) { + request = stringify(reference); + return id.toString(16) + ":" + request + "\n"; + } + function serializeClientReference( + request, + parent, + parentPropertyName, + clientReference + ) { + var clientReferenceKey = clientReference.$$async + ? clientReference.$$id + "#async" + : clientReference.$$id, + writtenClientReferences = request.writtenClientReferences, + existingId = writtenClientReferences.get(clientReferenceKey); + if (void 0 !== existingId) + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(existingId) + : serializeByValueID(existingId); + try { + var clientReferenceMetadata = resolveClientReferenceMetadata( + request.bundlerConfig, + clientReference + ); + request.pendingChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata, !1); + writtenClientReferences.set(clientReferenceKey, importId); + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(importId) + : serializeByValueID(importId); + } catch (x) { + return ( + request.pendingChunks++, + (parent = request.nextChunkId++), + (parentPropertyName = logRecoverableError(request, x, null)), + emitErrorChunk(request, parent, parentPropertyName, x, !1, null), + serializeByValueID(parent) + ); + } + } + function serializeDebugClientReference( + request, + parent, + parentPropertyName, + clientReference + ) { + var existingId = request.writtenClientReferences.get( + clientReference.$$async + ? clientReference.$$id + "#async" + : clientReference.$$id + ); + if (void 0 !== existingId) + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(existingId) + : serializeByValueID(existingId); + try { + var clientReferenceMetadata = resolveClientReferenceMetadata( + request.bundlerConfig, + clientReference + ); + request.pendingDebugChunks++; + var importId = request.nextChunkId++; + emitImportChunk(request, importId, clientReferenceMetadata, !0); + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(importId) + : serializeByValueID(importId); + } catch (x) { + return ( + request.pendingDebugChunks++, + (parent = request.nextChunkId++), + (parentPropertyName = logRecoverableError(request, x, null)), + emitErrorChunk(request, parent, parentPropertyName, x, !0, null), + serializeByValueID(parent) + ); + } + } + function outlineModel(request, value) { + return outlineModelWithFormatContext(request, value, 0); + } + function outlineModelWithFormatContext(request, value, formatContext) { + value = createTask( + request, + value, + null, + !1, + formatContext, + request.abortableTasks, + performance.now(), + null, + null, + null + ); + retryTask(request, value); + return value.id; + } + function serializeServerReference(request, serverReference) { + var writtenServerReferences = request.writtenServerReferences, + existingId = writtenServerReferences.get(serverReference); + if (void 0 !== existingId) return "$h" + existingId.toString(16); + existingId = serverReference.$$bound; + existingId = null === existingId ? null : Promise.resolve(existingId); + var id = serverReference.$$id, + location = null, + error = serverReference.$$location; + error && + ((error = parseStackTrace(error, 1)), + 0 < error.length && + ((location = error[0]), + (location = [location[0], location[1], location[2], location[3]]))); + existingId = + null !== location + ? { + id: id, + bound: existingId, + name: + "function" === typeof serverReference + ? serverReference.name + : "", + env: (0, request.environmentName)(), + location: location + } + : { id: id, bound: existingId }; + request = outlineModel(request, existingId); + writtenServerReferences.set(serverReference, request); + return "$h" + request.toString(16); + } + function serializeLargeTextString(request, text) { + request.pendingChunks++; + var textId = request.nextChunkId++; + emitTextChunk(request, textId, text, !1); + return serializeByValueID(textId); + } + function serializeMap(request, map) { + map = Array.from(map); + return "$Q" + outlineModel(request, map).toString(16); + } + function serializeFormData(request, formData) { + formData = Array.from(formData.entries()); + return "$K" + outlineModel(request, formData).toString(16); + } + function serializeSet(request, set) { + set = Array.from(set); + return "$W" + outlineModel(request, set).toString(16); + } + function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks++; + var bufferId = request.nextChunkId++; + emitTypedArrayChunk(request, bufferId, tag, typedArray, !1); + return serializeByValueID(bufferId); + } + function serializeDebugTypedArray(request, tag, typedArray) { + if (1e3 < typedArray.byteLength && !doNotLimit.has(typedArray)) + return serializeDeferredObject(request, typedArray); + request.pendingDebugChunks++; + var bufferId = request.nextChunkId++; + emitTypedArrayChunk(request, bufferId, tag, typedArray, !0); + return serializeByValueID(bufferId); + } + function serializeDebugBlob(request, blob) { + function progress(entry) { + if (entry.done) + emitOutlinedDebugModelChunk( + request, + id, + { objectLimit: model.length + 2 }, + model + ), + enqueueFlush(request); + else + return ( + model.push(entry.value), reader.read().then(progress).catch(error) + ); + } + function error(reason) { + emitErrorChunk(request, id, "", reason, !0, null); + enqueueFlush(request); + reader.cancel(reason).then(noop, noop); + } + var model = [blob.type], + reader = blob.stream().getReader(); + request.pendingDebugChunks++; + var id = request.nextChunkId++; + reader.read().then(progress).catch(error); + return "$B" + id.toString(16); + } + function serializeBlob(request, blob) { + function progress(entry) { + if (newTask.status === PENDING$1) + if (entry.done) + request.cacheController.signal.removeEventListener( + "abort", + abortBlob + ), + pingTask(request, newTask); + else + return ( + model.push(entry.value), reader.read().then(progress).catch(error) + ); + } + function error(reason) { + newTask.status === PENDING$1 && + (request.cacheController.signal.removeEventListener( + "abort", + abortBlob + ), + erroredTask(request, newTask, reason), + enqueueFlush(request), + reader.cancel(reason).then(error, error)); + } + function abortBlob() { + if (newTask.status === PENDING$1) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortBlob); + signal = signal.reason; + request.type === PRERENDER + ? (request.abortableTasks.delete(newTask), + haltTask(newTask), + finishHaltedTask(newTask, request)) + : (erroredTask(request, newTask, signal), enqueueFlush(request)); + reader.cancel(signal).then(error, error); + } + } + var model = [blob.type], + newTask = createTask( + request, + model, + null, + !1, + 0, + request.abortableTasks, + performance.now(), + null, + null, + null + ), + reader = blob.stream().getReader(); + request.cacheController.signal.addEventListener("abort", abortBlob); + reader.read().then(progress).catch(error); + return "$B" + newTask.id.toString(16); + } + function renderModel(request, task, parent, key, value) { + serializedSize += key.length; + var prevKeyPath = task.keyPath, + prevImplicitSlot = task.implicitSlot; + try { + return renderModelDestructive(request, task, parent, key, value); + } catch (thrownValue) { + parent = task.model; + parent = + "object" === typeof parent && + null !== parent && + (parent.$$typeof === REACT_ELEMENT_TYPE || + parent.$$typeof === REACT_LAZY_TYPE); + if (request.status === ABORTING) { + task.status = ABORTED; + if (request.type === PRERENDER) + return ( + (task = request.nextChunkId++), + (task = parent + ? serializeLazyID(task) + : serializeByValueID(task)), + task + ); + task = request.fatalError; + return parent ? serializeLazyID(task) : serializeByValueID(task); + } + key = + thrownValue === SuspenseException + ? getSuspendedThenable() + : thrownValue; + if ( + "object" === typeof key && + null !== key && + "function" === typeof key.then + ) + return ( + (request = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks, + task.time, + task.debugOwner, + task.debugStack, + task.debugTask + )), + (value = request.ping), + key.then(value, value), + (request.thenableState = getThenableStateAfterSuspending()), + (task.keyPath = prevKeyPath), + (task.implicitSlot = prevImplicitSlot), + parent + ? serializeLazyID(request.id) + : serializeByValueID(request.id) + ); + task.keyPath = prevKeyPath; + task.implicitSlot = prevImplicitSlot; + request.pendingChunks++; + prevKeyPath = request.nextChunkId++; + prevImplicitSlot = logRecoverableError(request, key, task); + emitErrorChunk( + request, + prevKeyPath, + prevImplicitSlot, + key, + !1, + task.debugOwner + ); + return parent + ? serializeLazyID(prevKeyPath) + : serializeByValueID(prevKeyPath); + } + } + function renderModelDestructive( + request, + task, + parent, + parentPropertyName, + value + ) { + task.model = value; + parentPropertyName === __PROTO__$1 && + callWithDebugContextInDEV(request, task, function () { + console.error( + "Expected not to serialize an object with own property `__proto__`. When parsed this property will be omitted.%s", + describeObjectForErrorMessage(parent, parentPropertyName) + ); + }); + if (value === REACT_ELEMENT_TYPE) return "$"; + if (null === value) return null; + if ("object" === typeof value) { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + var elementReference = null, + _writtenObjects = request.writtenObjects; + if (null === task.keyPath && !task.implicitSlot) { + var _existingReference = _writtenObjects.get(value); + if (void 0 !== _existingReference) + if (modelRoot === value) modelRoot = null; + else return _existingReference; + else + -1 === parentPropertyName.indexOf(":") && + ((_existingReference = _writtenObjects.get(parent)), + void 0 !== _existingReference && + ((elementReference = + _existingReference + ":" + parentPropertyName), + _writtenObjects.set(value, elementReference))); + } + if (serializedSize > MAX_ROW_SIZE) return deferTask(request, task); + if ((_existingReference = value._debugInfo)) + if (canEmitDebugInfo) + forwardDebugInfo(request, task, _existingReference); + else return outlineTask(request, task); + _existingReference = value.props; + var refProp = _existingReference.ref; + refProp = void 0 !== refProp ? refProp : null; + task.debugOwner = value._owner; + task.debugStack = value._debugStack; + task.debugTask = value._debugTask; + if ( + void 0 === value._owner || + void 0 === value._debugStack || + void 0 === value._debugTask + ) { + var key = ""; + null !== value.key && + value.key !== REACT_OPTIMISTIC_KEY && + (key = ' key="' + value.key + '"'); + console.error( + "Attempted to render <%s%s> without development properties. This is not supported. It can happen if:\n- The element is created with a production version of React but rendered in development.\n- The element was cloned with a custom function instead of `React.cloneElement`.\nThe props of this element may help locate this element: %o", + value.type, + key, + value.props + ); + } + request = renderElement( + request, + task, + value.type, + value.key, + refProp, + _existingReference, + value._store.validated + ); + "object" === typeof request && + null !== request && + null !== elementReference && + (_writtenObjects.has(request) || + _writtenObjects.set(request, elementReference)); + return request; + case REACT_LAZY_TYPE: + if (serializedSize > MAX_ROW_SIZE) return deferTask(request, task); + task.thenableState = null; + elementReference = callLazyInitInDEV(value); + if (request.status === ABORTING) throw null; + if ((_writtenObjects = value._debugInfo)) + if (canEmitDebugInfo) + forwardDebugInfo(request, task, _writtenObjects); + else return outlineTask(request, task); + return renderModelDestructive( + request, + task, + parent, + parentPropertyName, + elementReference + ); + case REACT_LEGACY_ELEMENT_TYPE: + throw Error( + 'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.' + ); + } + if (isClientReference(value)) + return serializeClientReference( + request, + parent, + parentPropertyName, + value + ); + if ( + void 0 !== request.temporaryReferences && + ((elementReference = request.temporaryReferences.get(value)), + void 0 !== elementReference) + ) + return "$T" + elementReference; + elementReference = request.writtenObjects; + _writtenObjects = elementReference.get(value); + if ("function" === typeof value.then) { + if (void 0 !== _writtenObjects) { + if (null !== task.keyPath || task.implicitSlot) + return ( + "$@" + serializeThenable(request, task, value).toString(16) + ); + if (modelRoot === value) modelRoot = null; + else return _writtenObjects; + } + request = "$@" + serializeThenable(request, task, value).toString(16); + elementReference.set(value, request); + return request; + } + if (void 0 !== _writtenObjects) + if (modelRoot === value) { + if (_writtenObjects !== serializeByValueID(task.id)) + return _writtenObjects; + modelRoot = null; + } else return _writtenObjects; + else if ( + -1 === parentPropertyName.indexOf(":") && + ((_writtenObjects = elementReference.get(parent)), + void 0 !== _writtenObjects) + ) { + _existingReference = parentPropertyName; + if (isArrayImpl(parent) && parent[0] === REACT_ELEMENT_TYPE) + switch (parentPropertyName) { + case "1": + _existingReference = "type"; + break; + case "2": + _existingReference = "key"; + break; + case "3": + _existingReference = "props"; + break; + case "4": + _existingReference = "_owner"; + } + elementReference.set( + value, + _writtenObjects + ":" + _existingReference + ); + } + if (isArrayImpl(value)) return renderFragment(request, task, value); + if (value instanceof Map) return serializeMap(request, value); + if (value instanceof Set) return serializeSet(request, value); + if ("function" === typeof FormData && value instanceof FormData) + return serializeFormData(request, value); + if (value instanceof Error) return serializeErrorValue(request, value); + if (value instanceof ArrayBuffer) + return serializeTypedArray(request, "A", new Uint8Array(value)); + if (value instanceof Int8Array) + return serializeTypedArray(request, "O", value); + if (value instanceof Uint8Array) + return serializeTypedArray(request, "o", value); + if (value instanceof Uint8ClampedArray) + return serializeTypedArray(request, "U", value); + if (value instanceof Int16Array) + return serializeTypedArray(request, "S", value); + if (value instanceof Uint16Array) + return serializeTypedArray(request, "s", value); + if (value instanceof Int32Array) + return serializeTypedArray(request, "L", value); + if (value instanceof Uint32Array) + return serializeTypedArray(request, "l", value); + if (value instanceof Float32Array) + return serializeTypedArray(request, "G", value); + if (value instanceof Float64Array) + return serializeTypedArray(request, "g", value); + if (value instanceof BigInt64Array) + return serializeTypedArray(request, "M", value); + if (value instanceof BigUint64Array) + return serializeTypedArray(request, "m", value); + if (value instanceof DataView) + return serializeTypedArray(request, "V", value); + if ("function" === typeof Blob && value instanceof Blob) + return serializeBlob(request, value); + if ((elementReference = getIteratorFn(value))) + return ( + (elementReference = elementReference.call(value)), + elementReference === value + ? "$i" + + outlineModel(request, Array.from(elementReference)).toString(16) + : renderFragment(request, task, Array.from(elementReference)) + ); + if ( + "function" === typeof ReadableStream && + value instanceof ReadableStream + ) + return serializeReadableStream(request, task, value); + elementReference = value[ASYNC_ITERATOR]; + if ("function" === typeof elementReference) + return renderAsyncFragment(request, task, value, elementReference); + if (value instanceof Date) return "$D" + value.toJSON(); + elementReference = getPrototypeOf(value); + if ( + elementReference !== ObjectPrototype$1 && + (null === elementReference || + null !== getPrototypeOf(elementReference)) + ) + throw Error( + "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + if ("Object" !== objectName(value)) + callWithDebugContextInDEV(request, task, function () { + console.error( + "Only plain objects can be passed to Client Components from Server Components. %s objects are not supported.%s", + objectName(value), + describeObjectForErrorMessage(parent, parentPropertyName) + ); + }); + else if (!isSimpleObject(value)) + callWithDebugContextInDEV(request, task, function () { + console.error( + "Only plain objects can be passed to Client Components from Server Components. Classes or other objects with methods are not supported.%s", + describeObjectForErrorMessage(parent, parentPropertyName) + ); + }); + else if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(value); + 0 < symbols.length && + callWithDebugContextInDEV(request, task, function () { + console.error( + "Only plain objects can be passed to Client Components from Server Components. Objects with symbol properties like %s are not supported.%s", + symbols[0].description, + describeObjectForErrorMessage(parent, parentPropertyName) + ); + }); + } + return value; + } + if ("string" === typeof value) + return ( + (serializedSize += value.length), + "Z" === value[value.length - 1] && + parent[parentPropertyName] instanceof Date + ? "$D" + value + : 1024 <= value.length && null !== byteLengthOfChunk + ? serializeLargeTextString(request, value) + : "$" === value[0] + ? "$" + value + : value + ); + if ("boolean" === typeof value) return value; + if ("number" === typeof value) return serializeNumber(value); + if ("undefined" === typeof value) return "$undefined"; + if ("function" === typeof value) { + if (isClientReference(value)) + return serializeClientReference( + request, + parent, + parentPropertyName, + value + ); + if (value.$$typeof === SERVER_REFERENCE_TAG) + return serializeServerReference(request, value); + if ( + void 0 !== request.temporaryReferences && + ((request = request.temporaryReferences.get(value)), + void 0 !== request) + ) + return "$T" + request; + if (value.$$typeof === TEMPORARY_REFERENCE_TAG) + throw Error( + "Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server." + ); + if (/^on[A-Z]/.test(parentPropertyName)) + throw Error( + "Event handlers cannot be passed to Client Component props." + + describeObjectForErrorMessage(parent, parentPropertyName) + + "\nIf you need interactivity, consider converting part of this to a Client Component." + ); + if ( + jsxChildrenParents.has(parent) || + (jsxPropsParents.has(parent) && "children" === parentPropertyName) + ) + throw ( + ((request = value.displayName || value.name || "Component"), + Error( + "Functions are not valid as a child of Client Components. This may happen if you return " + + request + + " instead of <" + + request + + " /> from render. Or maybe you meant to call this function rather than return it." + + describeObjectForErrorMessage(parent, parentPropertyName) + )) + ); + throw Error( + 'Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.' + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + } + if ("symbol" === typeof value) { + task = request.writtenSymbols; + elementReference = task.get(value); + if (void 0 !== elementReference) + return serializeByValueID(elementReference); + elementReference = value.description; + if (Symbol.for(elementReference) !== value) + throw Error( + "Only global symbols received from Symbol.for(...) can be passed to Client Components. The symbol Symbol.for(" + + (value.description + ") cannot be found among global symbols.") + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + request.pendingChunks++; + _writtenObjects = request.nextChunkId++; + emitSymbolChunk(request, _writtenObjects, elementReference); + task.set(value, _writtenObjects); + return serializeByValueID(_writtenObjects); + } + if ("bigint" === typeof value) return "$n" + value.toString(10); + throw Error( + "Type " + + typeof value + + " is not supported in Client Component props." + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + } + function logRecoverableError(request, error, task) { + var prevRequest = currentRequest; + currentRequest = null; + try { + var onError = request.onError; + var errorDigest = + null !== task + ? requestStorage.run( + void 0, + callWithDebugContextInDEV, + request, + task, + onError, + error + ) + : requestStorage.run(void 0, onError, error); + } finally { + currentRequest = prevRequest; + } + if (null != errorDigest && "string" !== typeof errorDigest) + throw Error( + 'onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + + typeof errorDigest + + '" instead' + ); + return errorDigest || ""; + } + function fatalError(request, error) { + var onFatalError = request.onFatalError; + onFatalError(error); + null !== request.destination + ? ((request.status = CLOSED), request.destination.destroy(error)) + : ((request.status = CLOSING), (request.fatalError = error)); + request.cacheController.abort( + Error("The render was aborted due to a fatal error.", { cause: error }) + ); + } + function serializeErrorValue(request, error) { + var name = "Error", + env = (0, request.environmentName)(); + try { + name = error.name; + var message = String(error.message); + var stack = filterStackTrace(request, parseStackTrace(error, 0)); + var errorEnv = error.environmentName; + "string" === typeof errorEnv && (env = errorEnv); + } catch (x) { + (message = + "An error occurred but serializing the error message failed."), + (stack = []); + } + name = { name: name, message: message, stack: stack, env: env }; + "cause" in error && + ((message = outlineModel(request, error.cause)), + (name.cause = serializeByValueID(message))); + "undefined" !== typeof AggregateError && + error instanceof AggregateError && + ((error = outlineModel(request, error.errors)), + (name.errors = serializeByValueID(error))); + return "$Z" + outlineModel(request, name).toString(16); + } + function emitErrorChunk(request, id, digest, error, debug, owner) { + var name = "Error", + env = (0, request.environmentName)(), + causeReference = null, + errorsReference = null; + try { + if (error instanceof Error) { + name = error.name; + var message = String(error.message); + var stack = filterStackTrace(request, parseStackTrace(error, 0)); + var errorEnv = error.environmentName; + "string" === typeof errorEnv && (env = errorEnv); + if ("cause" in error) { + var cause = error.cause, + causeId = debug + ? outlineDebugModel(request, { objectLimit: 5 }, cause) + : outlineModel(request, cause); + causeReference = serializeByValueID(causeId); + } + if ( + "undefined" !== typeof AggregateError && + error instanceof AggregateError + ) { + var errors = error.errors, + errorsId = debug + ? outlineDebugModel(request, { objectLimit: 5 }, errors) + : outlineModel(request, errors); + errorsReference = serializeByValueID(errorsId); + } + } else + (message = + "object" === typeof error && null !== error + ? describeObjectForErrorMessage(error) + : String(error)), + (stack = []); + } catch (x) { + (message = + "An error occurred but serializing the error message failed."), + (stack = []); + } + error = null == owner ? null : outlineComponentInfo(request, owner); + digest = { + digest: digest, + name: name, + message: message, + stack: stack, + env: env, + owner: error + }; + null !== causeReference && (digest.cause = causeReference); + null !== errorsReference && (digest.errors = errorsReference); + id = id.toString(16) + ":E" + stringify(digest) + "\n"; + debug + ? request.completedDebugChunks.push(id) + : request.completedErrorChunks.push(id); + } + function emitImportChunk(request, id, clientReferenceMetadata, debug) { + clientReferenceMetadata = stringify(clientReferenceMetadata); + id = id.toString(16) + ":I" + clientReferenceMetadata + "\n"; + debug + ? request.completedDebugChunks.push(id) + : request.completedImportChunks.push(id); + } + function emitSymbolChunk(request, id, name) { + id = encodeReferenceChunk(request, id, "$S" + name); + request.completedImportChunks.push(id); + } + function emitDebugHaltChunk(request, id) { + id = id.toString(16) + ":\n"; + request.completedDebugChunks.push(id); + } + function emitDebugChunk(request, id, debugInfo) { + var json = serializeDebugModel(request, 500, debugInfo); + null !== request.debugDestination + ? '"' === json[0] && "$" === json[1] + ? ((id = id.toString(16) + ":D" + json + "\n"), + request.completedRegularChunks.push(id)) + : ((debugInfo = request.nextChunkId++), + (json = debugInfo.toString(16) + ":" + json + "\n"), + request.pendingDebugChunks++, + request.completedDebugChunks.push(json), + (id = id.toString(16) + ':D"$' + debugInfo.toString(16) + '"\n'), + request.completedRegularChunks.push(id)) + : ((id = id.toString(16) + ":D" + json + "\n"), + request.completedRegularChunks.push(id)); + } + function outlineComponentInfo(request, componentInfo) { + var existingRef = request.writtenDebugObjects.get(componentInfo); + if (void 0 !== existingRef) return existingRef; + null != componentInfo.owner && + outlineComponentInfo(request, componentInfo.owner); + existingRef = 10; + null != componentInfo.stack && + (existingRef += componentInfo.stack.length); + existingRef = { objectLimit: existingRef }; + var componentDebugInfo = { + name: componentInfo.name, + key: componentInfo.key + }; + null != componentInfo.env && (componentDebugInfo.env = componentInfo.env); + null != componentInfo.owner && + (componentDebugInfo.owner = componentInfo.owner); + null == componentInfo.stack && null != componentInfo.debugStack + ? (componentDebugInfo.stack = filterStackTrace( + request, + parseStackTrace(componentInfo.debugStack, 1) + )) + : null != componentInfo.stack && + (componentDebugInfo.stack = componentInfo.stack); + componentDebugInfo.props = componentInfo.props; + existingRef = outlineDebugModel(request, existingRef, componentDebugInfo); + existingRef = serializeByValueID(existingRef); + request.writtenDebugObjects.set(componentInfo, existingRef); + request.writtenObjects.set(componentInfo, existingRef); + return existingRef; + } + function emitIOInfoChunk( + request, + id, + name, + start, + end, + value, + env, + owner, + stack + ) { + var objectLimit = 10; + stack && (objectLimit += stack.length); + name = { + name: name, + start: start - request.timeOrigin, + end: end - request.timeOrigin + }; + null != env && (name.env = env); + null != stack && (name.stack = stack); + null != owner && (name.owner = owner); + void 0 !== value && (name.value = value); + value = serializeDebugModel(request, objectLimit, name); + id = id.toString(16) + ":J" + value + "\n"; + request.completedDebugChunks.push(id); + } + function serializeIONode(request, ioNode, promiseRef) { + var existingRef = request.writtenDebugObjects.get(ioNode); + if (void 0 !== existingRef) return existingRef; + existingRef = null; + var name = ""; + if (null !== ioNode.promise) { + var promise = ioNode.promise.deref(); + void 0 !== promise && + "string" === typeof promise.displayName && + (name = promise.displayName); + } + if (null !== ioNode.stack) { + a: { + existingRef = ioNode.stack; + for (promise = 0; promise < existingRef.length; promise++) { + var callsite = existingRef[promise]; + if (!isPromiseCreationInternal(callsite[1], callsite[0])) { + promise = 0 < promise ? existingRef.slice(promise) : existingRef; + break a; + } + } + promise = []; + } + existingRef = filterStackTrace(request, promise); + if ("" === name) { + a: { + name = promise; + promise = ""; + callsite = request.filterStackFrame; + for (var i = 0; i < name.length; i++) { + var callsite$jscomp$0 = name[i], + functionName = callsite$jscomp$0[0], + url = devirtualizeURL(callsite$jscomp$0[1]); + if ( + callsite( + url, + functionName, + callsite$jscomp$0[2], + callsite$jscomp$0[3] + ) && + "" !== url + ) { + if ("" === promise) { + name = functionName; + break a; + } + name = promise; + break a; + } else promise = functionName; + } + name = ""; + } + name.startsWith("Window.") + ? (name = name.slice(7)) + : name.startsWith(".") && (name = name.slice(7)); + } + } + promise = ioNode.owner; + null != promise && outlineComponentInfo(request, promise); + callsite = void 0; + null !== promiseRef && (callsite = promiseRef.deref()); + promiseRef = (0, request.environmentName)(); + i = 3 === ioNode.tag ? request.abortTime : ioNode.end; + request.pendingDebugChunks++; + callsite$jscomp$0 = request.nextChunkId++; + emitIOInfoChunk( + request, + callsite$jscomp$0, + name, + ioNode.start, + i, + callsite, + promiseRef, + promise, + existingRef + ); + promiseRef = serializeByValueID(callsite$jscomp$0); + request.writtenDebugObjects.set(ioNode, promiseRef); + return promiseRef; + } + function emitTypedArrayChunk(request, id, tag, typedArray, debug) { + debug ? request.pendingDebugChunks++ : request.pendingChunks++; + typedArray = new Uint8Array( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength + ); + var binaryLength = typedArray.byteLength; + id = id.toString(16) + ":" + tag + binaryLength.toString(16) + ","; + debug + ? request.completedDebugChunks.push( + NEXT_TWO_CHUNKS_ARE_ATOMIC, + id, + typedArray + ) + : request.completedRegularChunks.push( + NEXT_TWO_CHUNKS_ARE_ATOMIC, + id, + typedArray + ); + } + function emitTextChunk(request, id, text, debug) { + if (null === byteLengthOfChunk) + throw Error( + "Existence of byteLengthOfChunk should have already been checked. This is a bug in React." + ); + debug ? request.pendingDebugChunks++ : request.pendingChunks++; + var binaryLength = byteLengthOfChunk(text); + id = id.toString(16) + ":T" + binaryLength.toString(16) + ","; + debug + ? request.completedDebugChunks.push( + NEXT_TWO_CHUNKS_ARE_ATOMIC, + id, + text + ) + : request.completedRegularChunks.push( + NEXT_TWO_CHUNKS_ARE_ATOMIC, + id, + text + ); + } + function renderDebugModel( + request, + counter, + parent, + parentPropertyName, + value + ) { + if (null === value) return null; + if (value === REACT_ELEMENT_TYPE) return "$"; + if ("object" === typeof value) { + if (isClientReference(value)) + return serializeDebugClientReference( + request, + parent, + parentPropertyName, + value + ); + if (value.$$typeof === CONSTRUCTOR_MARKER) { + value = value.constructor; + var ref = request.writtenDebugObjects.get(value); + void 0 === ref && + ((request = outlineDebugModel(request, counter, value)), + (ref = serializeByValueID(request))); + return "$P" + ref.slice(1); + } + if (void 0 !== request.temporaryReferences) { + var tempRef = request.temporaryReferences.get(value); + if (void 0 !== tempRef) return "$T" + tempRef; + } + tempRef = request.writtenDebugObjects; + var existingDebugReference = tempRef.get(value); + if (void 0 !== existingDebugReference) + if (debugModelRoot === value) debugModelRoot = null; + else return existingDebugReference; + else if (-1 === parentPropertyName.indexOf(":")) + if ( + ((existingDebugReference = tempRef.get(parent)), + void 0 !== existingDebugReference) + ) { + if (0 >= counter.objectLimit && !doNotLimit.has(value)) + return serializeDeferredObject(request, value); + var propertyName = parentPropertyName; + if (isArrayImpl(parent) && parent[0] === REACT_ELEMENT_TYPE) + switch (parentPropertyName) { + case "1": + propertyName = "type"; + break; + case "2": + propertyName = "key"; + break; + case "3": + propertyName = "props"; + break; + case "4": + propertyName = "_owner"; + } + tempRef.set(value, existingDebugReference + ":" + propertyName); + } else if (debugNoOutline !== value) { + if ("function" === typeof value.then) + return serializeDebugThenable(request, counter, value); + request = outlineDebugModel(request, counter, value); + return serializeByValueID(request); + } + parent = request.writtenObjects.get(value); + if (void 0 !== parent) return parent; + if (0 >= counter.objectLimit && !doNotLimit.has(value)) + return serializeDeferredObject(request, value); + counter.objectLimit--; + parent = request.deferredDebugObjects; + if ( + null !== parent && + ((parentPropertyName = parent.existing.get(value)), + void 0 !== parentPropertyName) + ) + return ( + parent.existing.delete(value), + parent.retained.delete(parentPropertyName), + emitOutlinedDebugModelChunk( + request, + parentPropertyName, + counter, + value + ), + serializeByValueID(parentPropertyName) + ); + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + null != value._owner && outlineComponentInfo(request, value._owner); + "object" === typeof value.type && + null !== value.type && + doNotLimit.add(value.type); + "object" === typeof value.key && + null !== value.key && + doNotLimit.add(value.key); + doNotLimit.add(value.props); + null !== value._owner && doNotLimit.add(value._owner); + counter = null; + if (null != value._debugStack) + for ( + counter = filterStackTrace( + request, + parseStackTrace(value._debugStack, 1) + ), + doNotLimit.add(counter), + request = 0; + request < counter.length; + request++ + ) + doNotLimit.add(counter[request]); + return [ + REACT_ELEMENT_TYPE, + value.type, + value.key, + value.props, + value._owner, + counter, + value._store.validated + ]; + case REACT_LAZY_TYPE: + value = value._payload; + if (null !== value && "object" === typeof value) { + switch (value._status) { + case 1: + return ( + (request = outlineDebugModel( + request, + counter, + value._result + )), + serializeLazyID(request) + ); + case 2: + return ( + (counter = request.nextChunkId++), + emitErrorChunk( + request, + counter, + "", + value._result, + !0, + null + ), + serializeLazyID(counter) + ); + } + switch (value.status) { + case "fulfilled": + return ( + (request = outlineDebugModel( + request, + counter, + value.value + )), + serializeLazyID(request) + ); + case "rejected": + return ( + (counter = request.nextChunkId++), + emitErrorChunk( + request, + counter, + "", + value.reason, + !0, + null + ), + serializeLazyID(counter) + ); + } + } + request.pendingDebugChunks++; + value = request.nextChunkId++; + emitDebugHaltChunk(request, value); + return serializeLazyID(value); + } + if ("function" === typeof value.then) + return serializeDebugThenable(request, counter, value); + if (isArrayImpl(value)) + return 200 < value.length && !doNotLimit.has(value) + ? serializeDeferredObject(request, value) + : value; + if (value instanceof Date) return "$D" + value.toJSON(); + if (value instanceof Map) { + value = Array.from(value); + counter.objectLimit++; + for (ref = 0; ref < value.length; ref++) { + var entry = value[ref]; + doNotLimit.add(entry); + var key = entry[0]; + entry = entry[1]; + "object" === typeof key && null !== key && doNotLimit.add(key); + "object" === typeof entry && + null !== entry && + doNotLimit.add(entry); + } + return "$Q" + outlineDebugModel(request, counter, value).toString(16); + } + if (value instanceof Set) { + value = Array.from(value); + counter.objectLimit++; + for (ref = 0; ref < value.length; ref++) + (key = value[ref]), + "object" === typeof key && null !== key && doNotLimit.add(key); + return "$W" + outlineDebugModel(request, counter, value).toString(16); + } + if ("function" === typeof FormData && value instanceof FormData) + return ( + (value = Array.from(value.entries())), + "$K" + + outlineDebugModel( + request, + { objectLimit: 2 * value.length + 1 }, + value + ).toString(16) + ); + if (value instanceof Error) { + var name = "Error"; + parent = (0, request.environmentName)(); + try { + (name = value.name), + (key = String(value.message)), + (ref = filterStackTrace(request, parseStackTrace(value, 0))), + (entry = value.environmentName), + "string" === typeof entry && (parent = entry); + } catch (x) { + (key = + "An error occurred but serializing the error message failed."), + (ref = []); + } + key = { name: name, message: key, stack: ref, env: parent }; + "cause" in value && + (counter.objectLimit--, + (entry = outlineDebugModel(request, counter, value.cause)), + (key.cause = serializeByValueID(entry))); + "undefined" !== typeof AggregateError && + value instanceof AggregateError && + (counter.objectLimit--, + (value = outlineDebugModel(request, counter, value.errors)), + (key.errors = serializeByValueID(value))); + request = + "$Z" + + outlineDebugModel( + request, + { objectLimit: 2 * ref.length + 1 }, + key + ).toString(16); + return request; + } + if (value instanceof ArrayBuffer) + return serializeDebugTypedArray(request, "A", new Uint8Array(value)); + if (value instanceof Int8Array) + return serializeDebugTypedArray(request, "O", value); + if (value instanceof Uint8Array) + return serializeDebugTypedArray(request, "o", value); + if (value instanceof Uint8ClampedArray) + return serializeDebugTypedArray(request, "U", value); + if (value instanceof Int16Array) + return serializeDebugTypedArray(request, "S", value); + if (value instanceof Uint16Array) + return serializeDebugTypedArray(request, "s", value); + if (value instanceof Int32Array) + return serializeDebugTypedArray(request, "L", value); + if (value instanceof Uint32Array) + return serializeDebugTypedArray(request, "l", value); + if (value instanceof Float32Array) + return serializeDebugTypedArray(request, "G", value); + if (value instanceof Float64Array) + return serializeDebugTypedArray(request, "g", value); + if (value instanceof BigInt64Array) + return serializeDebugTypedArray(request, "M", value); + if (value instanceof BigUint64Array) + return serializeDebugTypedArray(request, "m", value); + if (value instanceof DataView) + return serializeDebugTypedArray(request, "V", value); + if ("function" === typeof Blob && value instanceof Blob) + return serializeDebugBlob(request, value); + if (getIteratorFn(value)) return Array.from(value); + request = getPrototypeOf(value); + if (request !== ObjectPrototype$1 && null !== request) { + counter = Object.create(null); + for (name in value) + if (hasOwnProperty.call(value, name) || isGetter(request, name)) + counter[name] = value[name]; + ref = request.constructor; + "function" !== typeof ref || + ref.prototype !== request || + hasOwnProperty.call(value, "") || + isGetter(request, "") || + (counter[""] = { $$typeof: CONSTRUCTOR_MARKER, constructor: ref }); + return counter; + } + return value; + } + if ("string" === typeof value) { + if (1e6 < value.length) + return ( + "This string of length " + + value.length + + " has been omitted by React to avoid sending too much data from the server." + ); + if (1024 <= value.length) { + if (0 >= counter.objectLimit) + return serializeDeferredObject(request, value); + counter.objectLimit--; + request.pendingDebugChunks++; + counter = request.nextChunkId++; + emitTextChunk(request, counter, value, !0); + return serializeByValueID(counter); + } + return "$" === value[0] ? "$" + value : value; + } + if ("boolean" === typeof value) return value; + if ("number" === typeof value) return serializeNumber(value); + if ("undefined" === typeof value) return "$undefined"; + if ("function" === typeof value) { + if (isClientReference(value)) + return serializeDebugClientReference( + request, + parent, + parentPropertyName, + value + ); + if ( + void 0 !== request.temporaryReferences && + ((counter = request.temporaryReferences.get(value)), + void 0 !== counter) + ) + return "$T" + counter; + counter = request.writtenDebugObjects; + ref = counter.get(value); + if (void 0 !== ref) return ref; + ref = Function.prototype.toString.call(value); + key = value.name; + key = + "$E" + + ("string" === typeof key + ? "Object.defineProperty(" + + ref + + ',"name",{value:' + + JSON.stringify(key) + + "})" + : "(" + ref + ")"); + request.pendingDebugChunks++; + ref = request.nextChunkId++; + key = encodeReferenceChunk(request, ref, key); + request.completedDebugChunks.push(key); + request = serializeByValueID(ref); + counter.set(value, request); + return request; + } + if ("symbol" === typeof value) { + counter = request.writtenSymbols.get(value); + if (void 0 !== counter) return serializeByValueID(counter); + value = value.description; + request.pendingChunks++; + counter = request.nextChunkId++; + emitSymbolChunk(request, counter, value); + return serializeByValueID(counter); + } + return "bigint" === typeof value + ? "$n" + value.toString(10) + : "unknown type " + typeof value; + } + function serializeDebugModel(request, objectLimit, model) { + function replacer(parentPropertyName) { + try { + return renderDebugModel( + request, + counter, + this, + parentPropertyName, + this[parentPropertyName] + ); + } catch (x) { + return ( + "Unknown Value: React could not send it from the server.\n" + + x.message + ); + } + } + var counter = { objectLimit: objectLimit }; + objectLimit = debugNoOutline; + debugNoOutline = model; + try { + return stringify(model, replacer); + } catch (x) { + return stringify( + "Unknown Value: React could not send it from the server.\n" + + x.message + ); + } finally { + debugNoOutline = objectLimit; + } + } + function emitOutlinedDebugModelChunk(request, id, counter, model) { + function replacer(parentPropertyName) { + try { + return renderDebugModel( + request, + counter, + this, + parentPropertyName, + this[parentPropertyName] + ); + } catch (x) { + return ( + "Unknown Value: React could not send it from the server.\n" + + x.message + ); + } + } + "object" === typeof model && null !== model && doNotLimit.add(model); + var prevModelRoot = debugModelRoot; + debugModelRoot = model; + "object" === typeof model && + null !== model && + request.writtenDebugObjects.set(model, serializeByValueID(id)); + try { + var json = stringify(model, replacer); + } catch (x) { + json = stringify( + "Unknown Value: React could not send it from the server.\n" + + x.message + ); + } finally { + debugModelRoot = prevModelRoot; + } + id = id.toString(16) + ":" + json + "\n"; + request.completedDebugChunks.push(id); + } + function outlineDebugModel(request, counter, model) { + var id = request.nextChunkId++; + request.pendingDebugChunks++; + emitOutlinedDebugModelChunk(request, id, counter, model); + return id; + } + function emitTimeOriginChunk(request, timeOrigin) { + request.pendingDebugChunks++; + request.completedDebugChunks.push(":N" + timeOrigin + "\n"); + } + function forwardDebugInfo(request$jscomp$0, task, debugInfo) { + for (var id = task.id, i = 0; i < debugInfo.length; i++) { + var info = debugInfo[i]; + if ("number" === typeof info.time) + markOperationEndTime(request$jscomp$0, task, info.time); + else if ("string" === typeof info.name) + outlineComponentInfo(request$jscomp$0, info), + request$jscomp$0.pendingChunks++, + emitDebugChunk(request$jscomp$0, id, info); + else if (info.awaited) { + var ioInfo = info.awaited; + if (!(ioInfo.end <= request$jscomp$0.timeOrigin)) { + var request = request$jscomp$0, + ioInfo$jscomp$0 = ioInfo; + if (!request.writtenObjects.has(ioInfo$jscomp$0)) { + request.pendingDebugChunks++; + var id$jscomp$0 = request.nextChunkId++, + owner = ioInfo$jscomp$0.owner; + null != owner && outlineComponentInfo(request, owner); + var debugStack = + null == ioInfo$jscomp$0.stack && + null != ioInfo$jscomp$0.debugStack + ? filterStackTrace( + request, + parseStackTrace(ioInfo$jscomp$0.debugStack, 1) + ) + : ioInfo$jscomp$0.stack; + var env = ioInfo$jscomp$0.env; + null == env && (env = (0, request.environmentName)()); + emitIOInfoChunk( + request, + id$jscomp$0, + ioInfo$jscomp$0.name, + ioInfo$jscomp$0.start, + ioInfo$jscomp$0.end, + ioInfo$jscomp$0.value, + env, + owner, + debugStack + ); + request.writtenDebugObjects.set( + ioInfo$jscomp$0, + serializeByValueID(id$jscomp$0) + ); + } + null != info.owner && + outlineComponentInfo(request$jscomp$0, info.owner); + debugStack = + null == info.stack && null != info.debugStack + ? filterStackTrace( + request$jscomp$0, + parseStackTrace(info.debugStack, 1) + ) + : info.stack; + ioInfo = { awaited: ioInfo }; + ioInfo.env = + null != info.env + ? info.env + : (0, request$jscomp$0.environmentName)(); + null != info.owner && (ioInfo.owner = info.owner); + null != debugStack && (ioInfo.stack = debugStack); + request$jscomp$0.pendingChunks++; + emitDebugChunk(request$jscomp$0, id, ioInfo); + } + } else + request$jscomp$0.pendingChunks++, + emitDebugChunk(request$jscomp$0, id, info); + } + } + function forwardDebugInfoFromThenable( + request, + task, + thenable, + owner, + stack + ) { + var debugInfo; + (debugInfo = thenable._debugInfo) && + forwardDebugInfo(request, task, debugInfo); + thenable = getAsyncSequenceFromPromise(thenable); + null !== thenable && + emitAsyncSequence(request, task, thenable, debugInfo, owner, stack); + } + function forwardDebugInfoFromCurrentContext(request, task, thenable) { + (thenable = thenable._debugInfo) && + forwardDebugInfo(request, task, thenable); + var sequence = pendingOperations.get(async_hooks.executionAsyncId()); + sequence = void 0 === sequence ? null : sequence; + null !== sequence && + emitAsyncSequence(request, task, sequence, thenable, null, null); + } + function forwardDebugInfoFromAbortedTask(request, task) { + var model = task.model; + if ("object" === typeof model && null !== model) { + var debugInfo; + (debugInfo = model._debugInfo) && + forwardDebugInfo(request, task, debugInfo); + var thenable = null; + "function" === typeof model.then + ? (thenable = model) + : model.$$typeof === REACT_LAZY_TYPE && + ((model = model._payload), + "function" === typeof model.then && (thenable = model)); + if ( + null !== thenable && + ((model = getAsyncSequenceFromPromise(thenable)), null !== model) + ) { + for ( + thenable = model; + 4 === thenable.tag && null !== thenable.awaited; + + ) + thenable = thenable.awaited; + 3 === thenable.tag + ? (serializeIONode(request, thenable, null), + request.pendingChunks++, + (debugInfo = (0, request.environmentName)()), + (debugInfo = { awaited: thenable, env: debugInfo }), + advanceTaskTime(request, task, task.time), + emitDebugChunk(request, task.id, debugInfo)) + : emitAsyncSequence(request, task, model, debugInfo, null, null); + } + } + } + function emitTimingChunk(request, id, timestamp) { + request.pendingChunks++; + var json = '{"time":' + (timestamp - request.timeOrigin) + "}"; + null !== request.debugDestination + ? ((timestamp = request.nextChunkId++), + (json = timestamp.toString(16) + ":" + json + "\n"), + request.pendingDebugChunks++, + request.completedDebugChunks.push(json), + (id = id.toString(16) + ':D"$' + timestamp.toString(16) + '"\n'), + request.completedRegularChunks.push(id)) + : ((id = id.toString(16) + ":D" + json + "\n"), + request.completedRegularChunks.push(id)); + } + function advanceTaskTime(request, task, timestamp) { + timestamp > task.time + ? (emitTimingChunk(request, task.id, timestamp), + (task.time = timestamp)) + : task.timed || emitTimingChunk(request, task.id, task.time); + task.timed = !0; + } + function markOperationEndTime(request, task, timestamp) { + (request.status === ABORTING && timestamp > request.abortTime) || + (timestamp > task.time + ? (emitTimingChunk(request, task.id, timestamp), + (task.time = timestamp)) + : emitTimingChunk(request, task.id, task.time)); + } + function emitChunk(request, task, value) { + var id = task.id; + "string" === typeof value && null !== byteLengthOfChunk + ? emitTextChunk(request, id, value, !1) + : value instanceof ArrayBuffer + ? emitTypedArrayChunk(request, id, "A", new Uint8Array(value), !1) + : value instanceof Int8Array + ? emitTypedArrayChunk(request, id, "O", value, !1) + : value instanceof Uint8Array + ? emitTypedArrayChunk(request, id, "o", value, !1) + : value instanceof Uint8ClampedArray + ? emitTypedArrayChunk(request, id, "U", value, !1) + : value instanceof Int16Array + ? emitTypedArrayChunk(request, id, "S", value, !1) + : value instanceof Uint16Array + ? emitTypedArrayChunk(request, id, "s", value, !1) + : value instanceof Int32Array + ? emitTypedArrayChunk(request, id, "L", value, !1) + : value instanceof Uint32Array + ? emitTypedArrayChunk(request, id, "l", value, !1) + : value instanceof Float32Array + ? emitTypedArrayChunk(request, id, "G", value, !1) + : value instanceof Float64Array + ? emitTypedArrayChunk(request, id, "g", value, !1) + : value instanceof BigInt64Array + ? emitTypedArrayChunk(request, id, "M", value, !1) + : value instanceof BigUint64Array + ? emitTypedArrayChunk( + request, + id, + "m", + value, + !1 + ) + : value instanceof DataView + ? emitTypedArrayChunk( + request, + id, + "V", + value, + !1 + ) + : ((value = resolveModel( + request, + task, + { "": value }, + "", + value + )), + (value = stringify(value)), + (task = + task.id.toString(16) + + ":" + + value + + "\n"), + request.completedRegularChunks.push(task)); + } + function erroredTask(request, task, error) { + task.timed && markOperationEndTime(request, task, performance.now()); + task.status = ERRORED$1; + var digest = logRecoverableError(request, error, task); + emitErrorChunk(request, task.id, digest, error, !1, task.debugOwner); + request.abortableTasks.delete(task); + callOnAllReadyIfReady(request); + } + function retryTask(request, task) { + if (task.status === PENDING$1) { + var prevCanEmitDebugInfo = canEmitDebugInfo; + task.status = RENDERING; + var parentSerializedSize = serializedSize; + try { + modelRoot = task.model; + canEmitDebugInfo = !0; + var resolvedModel = renderModelDestructive( + request, + task, + emptyRoot, + "", + task.model + ); + canEmitDebugInfo = !1; + modelRoot = resolvedModel; + task.keyPath = null; + task.implicitSlot = !1; + var currentEnv = (0, request.environmentName)(); + currentEnv !== task.environmentName && + (request.pendingChunks++, + emitDebugChunk(request, task.id, { env: currentEnv })); + task.timed && markOperationEndTime(request, task, performance.now()); + if ("object" === typeof resolvedModel && null !== resolvedModel) + request.writtenObjects.set( + resolvedModel, + serializeByValueID(task.id) + ), + emitChunk(request, task, resolvedModel); + else { + var json = stringify(resolvedModel), + processedChunk = task.id.toString(16) + ":" + json + "\n"; + request.completedRegularChunks.push(processedChunk); + } + task.status = COMPLETED; + request.abortableTasks.delete(task); + callOnAllReadyIfReady(request); + } catch (thrownValue) { + if (request.status === ABORTING) + if ( + (request.abortableTasks.delete(task), + (task.status = PENDING$1), + request.type === PRERENDER) + ) + haltTask(task), finishHaltedTask(task, request); + else { + var errorId = request.fatalError; + abortTask(task); + finishAbortedTask(task, request, errorId); + } + else { + var x = + thrownValue === SuspenseException + ? getSuspendedThenable() + : thrownValue; + if ( + "object" === typeof x && + null !== x && + "function" === typeof x.then + ) { + task.status = PENDING$1; + task.thenableState = getThenableStateAfterSuspending(); + var ping = task.ping; + x.then(ping, ping); + } else erroredTask(request, task, x); + } + } finally { + (canEmitDebugInfo = prevCanEmitDebugInfo), + (serializedSize = parentSerializedSize); + } + } + } + function tryStreamTask(request, task) { + var prevCanEmitDebugInfo = canEmitDebugInfo; + canEmitDebugInfo = !1; + var parentSerializedSize = serializedSize; + try { + emitChunk(request, task, task.model); + } finally { + (serializedSize = parentSerializedSize), + (canEmitDebugInfo = prevCanEmitDebugInfo); + } + } + function performWork(request) { + pendingOperations.delete(async_hooks.executionAsyncId()); + var prevDispatcher = ReactSharedInternalsServer.H; + ReactSharedInternalsServer.H = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest$1 = currentRequest = request; + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + for (var i = 0; i < pingedTasks.length; i++) + retryTask(request, pingedTasks[i]); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } finally { + (ReactSharedInternalsServer.H = prevDispatcher), + (currentRequest$1 = null), + (currentRequest = prevRequest); + } + } + function abortTask(task) { + task.status === PENDING$1 && (task.status = ABORTED); + } + function finishAbortedTask(task, request, errorId) { + task.status === ABORTED && + (forwardDebugInfoFromAbortedTask(request, task), + task.timed && markOperationEndTime(request, task, request.abortTime), + (errorId = serializeByValueID(errorId)), + (task = encodeReferenceChunk(request, task.id, errorId)), + request.completedErrorChunks.push(task)); + } + function haltTask(task) { + task.status === PENDING$1 && (task.status = ABORTED); + } + function finishHaltedTask(task, request) { + task.status === ABORTED && + (forwardDebugInfoFromAbortedTask(request, task), + request.pendingChunks--); + } + function flushCompletedChunks(request) { + if (null !== request.debugDestination) { + var debugDestination = request.debugDestination; + currentView = new Uint8Array(4096); + writtenBytes = 0; + destinationHasCapacity = !0; + try { + for ( + var debugChunks = request.completedDebugChunks, i = 0; + i < debugChunks.length; + i++ + ) { + var item = debugChunks[i]; + if (item === NEXT_TWO_CHUNKS_ARE_ATOMIC) { + if (i + 2 >= debugChunks.length) + throw Error( + "A chunk pair is incomplete. This is a bug in React." + ); + request.pendingDebugChunks -= 2; + writeChunk(debugDestination, debugChunks[i + 1]); + writeChunk(debugDestination, debugChunks[i + 2]); + i += 2; + } else + request.pendingDebugChunks--, writeChunk(debugDestination, item); + } + debugChunks.splice(0, i); + } finally { + completeWriting(debugDestination); + } + flushBuffered(debugDestination); + } + debugDestination = request.destination; + if (null !== debugDestination) { + currentView = new Uint8Array(4096); + writtenBytes = 0; + destinationHasCapacity = !0; + try { + var importsChunks = request.completedImportChunks; + for ( + debugChunks = 0; + debugChunks < importsChunks.length; + debugChunks++ + ) + if ( + (request.pendingChunks--, + !writeChunkAndReturn( + debugDestination, + importsChunks[debugChunks] + )) + ) { + request.destination = null; + debugChunks++; + break; + } + importsChunks.splice(0, debugChunks); + var hintChunks = request.completedHintChunks; + for (debugChunks = 0; debugChunks < hintChunks.length; debugChunks++) + if ( + !writeChunkAndReturn(debugDestination, hintChunks[debugChunks]) + ) { + request.destination = null; + debugChunks++; + break; + } + hintChunks.splice(0, debugChunks); + if (null === request.debugDestination) { + var _debugChunks = request.completedDebugChunks; + for ( + debugChunks = 0; + debugChunks < _debugChunks.length; + debugChunks++ + ) { + var _item = _debugChunks[debugChunks]; + importsChunks = void 0; + if (_item === NEXT_TWO_CHUNKS_ARE_ATOMIC) { + if (debugChunks + 2 >= _debugChunks.length) + throw Error( + "A chunk pair is incomplete. This is a bug in React." + ); + request.pendingDebugChunks -= 2; + writeChunk(debugDestination, _debugChunks[debugChunks + 1]); + importsChunks = writeChunkAndReturn( + debugDestination, + _debugChunks[debugChunks + 2] + ); + debugChunks += 2; + } else + request.pendingDebugChunks--, + (importsChunks = writeChunkAndReturn( + debugDestination, + _item + )); + if (!importsChunks) { + request.destination = null; + debugChunks++; + break; + } + } + _debugChunks.splice(0, debugChunks); + } + var regularChunks = request.completedRegularChunks; + for ( + debugChunks = 0; + debugChunks < regularChunks.length; + debugChunks++ + ) { + var _item2 = regularChunks[debugChunks]; + _debugChunks = void 0; + if (_item2 === NEXT_TWO_CHUNKS_ARE_ATOMIC) { + if (debugChunks + 2 >= regularChunks.length) + throw Error( + "A chunk pair is incomplete. This is a bug in React." + ); + request.pendingChunks -= 2; + writeChunk(debugDestination, regularChunks[debugChunks + 1]); + _debugChunks = writeChunkAndReturn( + debugDestination, + regularChunks[debugChunks + 2] + ); + debugChunks += 2; + } else + request.pendingChunks--, + (_debugChunks = writeChunkAndReturn(debugDestination, _item2)); + if (!_debugChunks) { + request.destination = null; + debugChunks++; + break; + } + } + regularChunks.splice(0, debugChunks); + var errorChunks = request.completedErrorChunks; + for (debugChunks = 0; debugChunks < errorChunks.length; debugChunks++) + if ( + (request.pendingChunks--, + !writeChunkAndReturn(debugDestination, errorChunks[debugChunks])) + ) { + request.destination = null; + debugChunks++; + break; + } + errorChunks.splice(0, debugChunks); + } finally { + (request.flushScheduled = !1), completeWriting(debugDestination); + } + flushBuffered(debugDestination); + } + 0 === request.pendingChunks && + ((regularChunks = request.debugDestination), + 0 === request.pendingDebugChunks + ? (null !== regularChunks && + (regularChunks.end(), (request.debugDestination = null)), + request.status < ABORTING && + request.cacheController.abort( + Error( + "This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources." + ) + ), + null !== request.destination && + ((request.status = CLOSED), + request.destination.end(), + (request.destination = null)), + null !== request.debugDestination && + (request.debugDestination.end(), + (request.debugDestination = null))) + : null !== regularChunks && + null !== request.destination && + ((request.status = CLOSED), + request.destination.end(), + (request.destination = null))); + } + function startWork(request) { + request.flushScheduled = null !== request.destination; + scheduleMicrotask(function () { + requestStorage.run(request, performWork, request); + }); + setImmediate(function () { + request.status === OPENING && (request.status = 11); + }); + } + function enqueueFlush(request) { + !1 !== request.flushScheduled || + 0 !== request.pingedTasks.length || + (null === request.destination && null === request.debugDestination) || + ((request.flushScheduled = !0), + setImmediate(function () { + request.flushScheduled = !1; + flushCompletedChunks(request); + })); + } + function callOnAllReadyIfReady(request) { + 0 === request.abortableTasks.size && + ((request = request.onAllReady), request()); + } + function startFlowing(request, destination) { + if (request.status === CLOSING) + (request.status = CLOSED), destination.destroy(request.fatalError); + else if (request.status !== CLOSED && null === request.destination) { + request.destination = destination; + try { + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } + } + } + function startFlowingDebug(request, debugDestination) { + if (request.status === CLOSING) + (request.status = CLOSED), debugDestination.destroy(request.fatalError); + else if (request.status !== CLOSED && null === request.debugDestination) { + request.debugDestination = debugDestination; + try { + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } + } + } + function finishHalt(request, abortedTasks) { + try { + abortedTasks.forEach(function (task) { + return finishHaltedTask(task, request); + }); + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } + } + function finishAbort(request, abortedTasks, errorId) { + try { + abortedTasks.forEach(function (task) { + return finishAbortedTask(task, request, errorId); + }); + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } + } + function abort(request, reason) { + if (!(11 < request.status)) + try { + request.status = ABORTING; + request.abortTime = performance.now(); + request.cacheController.abort(reason); + var abortableTasks = request.abortableTasks; + if (0 < abortableTasks.size) + if (request.type === PRERENDER) + abortableTasks.forEach(function (task) { + return haltTask(task, request); + }), + setImmediate(function () { + return finishHalt(request, abortableTasks); + }); + else { + var error = + void 0 === reason + ? Error( + "The render was aborted by the server without a reason." + ) + : "object" === typeof reason && + null !== reason && + "function" === typeof reason.then + ? Error( + "The render was aborted by the server with a promise." + ) + : reason, + digest = logRecoverableError(request, error, null), + errorId = request.nextChunkId++; + request.fatalError = errorId; + request.pendingChunks++; + emitErrorChunk(request, errorId, digest, error, !1, null); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + setImmediate(function () { + return finishAbort(request, abortableTasks, errorId); + }); + } + else { + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } + } catch (error$8) { + logRecoverableError(request, error$8, null), + fatalError(request, error$8); + } + } + function fromHex(str) { + return parseInt(str, 16); + } + function resolveDebugMessage(request, message) { + var deferredDebugObjects = request.deferredDebugObjects; + if (null === deferredDebugObjects) + throw Error( + "resolveDebugMessage/closeDebugChannel should not be called for a Request that wasn't kept alive. This is a bug in React." + ); + if ("" === message) closeDebugChannel(request); + else { + var command = message.charCodeAt(0); + message = message.slice(2).split(",").map(fromHex); + switch (command) { + case 82: + for (command = 0; command < message.length; command++) { + var id = message[command], + retainedValue = deferredDebugObjects.retained.get(id); + void 0 !== retainedValue && + (request.pendingDebugChunks--, + deferredDebugObjects.retained.delete(id), + deferredDebugObjects.existing.delete(retainedValue), + enqueueFlush(request)); + } + break; + case 81: + for (command = 0; command < message.length; command++) + (id = message[command]), + (retainedValue = deferredDebugObjects.retained.get(id)), + void 0 !== retainedValue && + (deferredDebugObjects.retained.delete(id), + deferredDebugObjects.existing.delete(retainedValue), + emitOutlinedDebugModelChunk( + request, + id, + { objectLimit: 10 }, + retainedValue + ), + enqueueFlush(request)); + break; + case 80: + for (command = 0; command < message.length; command++) + (id = message[command]), + (retainedValue = deferredDebugObjects.retained.get(id)), + void 0 !== retainedValue && + (deferredDebugObjects.retained.delete(id), + emitRequestedDebugThenable( + request, + id, + { objectLimit: 10 }, + retainedValue + )); + break; + default: + throw Error( + "Unknown command. The debugChannel was not wired up properly." + ); + } + } + } + function closeDebugChannel(request) { + var deferredDebugObjects = request.deferredDebugObjects; + if (null === deferredDebugObjects) + throw Error( + "resolveDebugMessage/closeDebugChannel should not be called for a Request that wasn't kept alive. This is a bug in React." + ); + deferredDebugObjects.retained.forEach(function (value, id) { + request.pendingDebugChunks--; + deferredDebugObjects.retained.delete(id); + deferredDebugObjects.existing.delete(value); + }); + enqueueFlush(request); + } + function resolveServerReference(bundlerConfig, id) { + var name = "", + resolvedModuleData = bundlerConfig[id]; + if (resolvedModuleData) name = resolvedModuleData.name; + else { + var idx = id.lastIndexOf("#"); + -1 !== idx && + ((name = id.slice(idx + 1)), + (resolvedModuleData = bundlerConfig[id.slice(0, idx)])); + if (!resolvedModuleData) + throw Error( + 'Could not find the module "' + + id + + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.' + ); + } + return resolvedModuleData.async + ? [resolvedModuleData.id, resolvedModuleData.chunks, name, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } + function requireAsyncModule(id) { + var promise = __webpack_require__(id); + if ("function" !== typeof promise.then || "fulfilled" === promise.status) + return null; + promise.then( + function (value) { + promise.status = "fulfilled"; + promise.value = value; + }, + function (reason) { + promise.status = "rejected"; + promise.reason = reason; + } + ); + return promise; + } + function ignoreReject() {} + function preloadModule(metadata) { + for ( + var chunks = metadata[1], promises = [], i = 0; + i < chunks.length; + + ) { + var chunkId = chunks[i++]; + chunks[i++]; + var entry = chunkCache.get(chunkId); + if (void 0 === entry) { + entry = __webpack_require__.e(chunkId); + promises.push(entry); + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + entry.then(resolve, ignoreReject); + chunkCache.set(chunkId, entry); + } else null !== entry && promises.push(entry); + } + return 4 === metadata.length + ? 0 === promises.length + ? requireAsyncModule(metadata[0]) + : Promise.all(promises).then(function () { + return requireAsyncModule(metadata[0]); + }) + : 0 < promises.length + ? Promise.all(promises) + : null; + } + function requireModule(metadata) { + var moduleExports = __webpack_require__(metadata[0]); + if (4 === metadata.length && "function" === typeof moduleExports.then) + if ("fulfilled" === moduleExports.status) + moduleExports = moduleExports.value; + else throw moduleExports.reason; + if ("*" === metadata[2]) return moduleExports; + if ("" === metadata[2]) + return moduleExports.__esModule ? moduleExports.default : moduleExports; + if (hasOwnProperty.call(moduleExports, metadata[2])) + return moduleExports[metadata[2]]; + } + function appendBackingEntry(backingStore, key, value) { + backingStore.data.append(key, value); + value = backingStore.keys; + null === value + ? ((backingStore.keys = Array.from(backingStore.data.keys())), + (backingStore.keyPointer = 0)) + : value.push(key); + } + function ReactPromise(status, value, reason) { + this.status = status; + this.value = value; + this.reason = reason; + } + function wakeChunk(response, listeners, value, chunk) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk.reason); + } + } + function rejectChunk(response, listeners, error) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(error) + : rejectReference(response, listener.handler, error); + } + } + function triggerErrorOnChunk(response, chunk, error) { + if ("pending" !== chunk.status && "blocked" !== chunk.status) + chunk.reason.error(error); + else { + var listeners = chunk.reason; + chunk.status = "rejected"; + chunk.reason = error; + null !== listeners && rejectChunk(response, listeners, error); + } + } + function createResolvedModelChunk(response, value, id) { + var $jscomp$compprop2 = {}; + return new ReactPromise( + "resolved_model", + value, + (($jscomp$compprop2.id = id), + ($jscomp$compprop2[RESPONSE_SYMBOL] = response), + $jscomp$compprop2) + ); + } + function resolveModelChunk(response, chunk, value, id) { + if ("pending" !== chunk.status) + (chunk = chunk.reason), + "C" === value[0] + ? chunk.close("C" === value ? '"$undefined"' : value.slice(1)) + : chunk.enqueueModel(value); + else { + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_model"; + chunk.value = value; + value = {}; + chunk.reason = + ((value.id = id), (value[RESPONSE_SYMBOL] = response), value); + if (null !== resolveListeners) + switch ((initializeModelChunk(chunk), chunk.status)) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + break; + case "blocked": + case "pending": + if (chunk.value) + for ( + response = 0; + response < resolveListeners.length; + response++ + ) + chunk.value.push(resolveListeners[response]); + else chunk.value = resolveListeners; + if (chunk.reason) { + if (rejectListeners) + for ( + resolveListeners = 0; + resolveListeners < rejectListeners.length; + resolveListeners++ + ) + chunk.reason.push(rejectListeners[resolveListeners]); + } else chunk.reason = rejectListeners; + break; + case "rejected": + rejectListeners && + rejectChunk(response, rejectListeners, chunk.reason); + } + } + } + function createResolvedIteratorResultChunk(response, value, done) { + var $jscomp$compprop4 = {}; + return new ReactPromise( + "resolved_model", + (done ? '{"done":true,"value":' : '{"done":false,"value":') + + value + + "}", + (($jscomp$compprop4.id = -1), + ($jscomp$compprop4[RESPONSE_SYMBOL] = response), + $jscomp$compprop4) + ); + } + function resolveIteratorResultChunk(response, chunk, value, done) { + resolveModelChunk( + response, + chunk, + (done ? '{"done":true,"value":' : '{"done":false,"value":') + + value + + "}", + -1 + ); + } + function loadServerReference$1(response, metaData, parentObject, key) { + function reject(error) { + var rejectListeners = blockedPromise.reason, + erroredPromise = blockedPromise; + erroredPromise.status = "rejected"; + erroredPromise.value = null; + erroredPromise.reason = error; + null !== rejectListeners && + rejectChunk(response, rejectListeners, error); + rejectReference(response, handler, error); + } + var id = metaData.id; + if ("string" !== typeof id || "then" === key) return null; + var cachedPromise = metaData.$$promise; + if (void 0 !== cachedPromise) { + if ("fulfilled" === cachedPromise.status) + return ( + (cachedPromise = cachedPromise.value), + "__proto__" === key ? null : (parentObject[key] = cachedPromise) + ); + initializingHandler + ? ((id = initializingHandler), id.deps++) + : (id = initializingHandler = + { chunk: null, value: null, reason: null, deps: 1, errored: !1 }); + cachedPromise.then( + resolveReference.bind(null, response, id, parentObject, key), + rejectReference.bind(null, response, id) + ); + return null; + } + var blockedPromise = new ReactPromise("blocked", null, null); + metaData.$$promise = blockedPromise; + var serverReference = resolveServerReference(response._bundlerConfig, id); + cachedPromise = metaData.bound; + if ((id = preloadModule(serverReference))) + cachedPromise instanceof ReactPromise && + (id = Promise.all([id, cachedPromise])); + else if (cachedPromise instanceof ReactPromise) + id = Promise.resolve(cachedPromise); + else + return ( + (cachedPromise = requireModule(serverReference)), + (id = blockedPromise), + (id.status = "fulfilled"), + (id.value = cachedPromise), + (id.reason = null), + cachedPromise + ); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + id.then(function () { + var resolvedValue = requireModule(serverReference); + if (metaData.bound) { + var promiseValue = metaData.bound.value; + promiseValue = isArrayImpl(promiseValue) ? promiseValue.slice(0) : []; + if (promiseValue.length > MAX_BOUND_ARGS) { + reject( + Error( + "Server Function has too many bound arguments. Received " + + promiseValue.length + + " but the limit is " + + MAX_BOUND_ARGS + + "." + ) + ); + return; + } + promiseValue.unshift(null); + resolvedValue = resolvedValue.bind.apply(resolvedValue, promiseValue); + } + promiseValue = blockedPromise.value; + var initializedPromise = blockedPromise; + initializedPromise.status = "fulfilled"; + initializedPromise.value = resolvedValue; + initializedPromise.reason = null; + null !== promiseValue && + wakeChunk(response, promiseValue, resolvedValue, initializedPromise); + resolveReference(response, handler, parentObject, key, resolvedValue); + }, reject); + return null; + } + function reviveModel( + response, + parentObj, + parentKey, + value, + reference, + arrayRoot + ) { + if ("string" === typeof value) + return parseModelString( + response, + parentObj, + parentKey, + value, + reference, + arrayRoot + ); + if ("object" === typeof value && null !== value) + if ( + (void 0 !== reference && + void 0 !== response._temporaryReferences && + response._temporaryReferences.set(value, reference), + isArrayImpl(value)) + ) { + if (null === arrayRoot) { + var childContext = { count: 0, fork: !1 }; + response._rootArrayContexts.set(value, childContext); + } else childContext = arrayRoot; + 1 < value.length && (childContext.fork = !0); + bumpArrayCount(childContext, value.length + 1, response); + for (parentObj = 0; parentObj < value.length; parentObj++) + value[parentObj] = reviveModel( + response, + value, + "" + parentObj, + value[parentObj], + void 0 !== reference ? reference + ":" + parentObj : void 0, + childContext + ); + } else + for (childContext in value) + hasOwnProperty.call(value, childContext) && + ("__proto__" === childContext + ? delete value[childContext] + : ((parentObj = + void 0 !== reference && -1 === childContext.indexOf(":") + ? reference + ":" + childContext + : void 0), + (parentObj = reviveModel( + response, + value, + childContext, + value[childContext], + parentObj, + null + )), + void 0 !== parentObj + ? (value[childContext] = parentObj) + : delete value[childContext])); + return value; + } + function bumpArrayCount(arrayContext, slots, response) { + if ( + (arrayContext.count += slots) > response._arraySizeLimit && + arrayContext.fork + ) + throw Error( + "Maximum array nesting exceeded. Large nested arrays can be dangerous. Try adding intermediate objects." + ); + } + function initializeModelChunk(chunk) { + var prevHandler = initializingHandler; + initializingHandler = null; + var _chunk$reason = chunk.reason, + response = _chunk$reason[RESPONSE_SYMBOL]; + _chunk$reason = _chunk$reason.id; + _chunk$reason = + -1 === _chunk$reason ? void 0 : _chunk$reason.toString(16); + var resolvedModel = chunk.value; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + try { + var rawModel = JSON.parse(resolvedModel); + resolvedModel = { count: 0, fork: !1 }; + var value = reviveModel( + response, + { "": rawModel }, + "", + rawModel, + _chunk$reason, + resolvedModel + ), + resolveListeners = chunk.value; + if (null !== resolveListeners) + for ( + chunk.value = null, chunk.reason = null, rawModel = 0; + rawModel < resolveListeners.length; + rawModel++ + ) { + var listener = resolveListeners[rawModel]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, resolvedModel); + } + if (null !== initializingHandler) { + if (initializingHandler.errored) throw initializingHandler.reason; + if (0 < initializingHandler.deps) { + initializingHandler.value = value; + initializingHandler.reason = resolvedModel; + initializingHandler.chunk = chunk; + return; + } + } + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = resolvedModel; + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } finally { + initializingHandler = prevHandler; + } + } + function reportGlobalError(response, error) { + response._closed = !0; + response._closedReason = error; + response._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? triggerErrorOnChunk(response, chunk, error) + : "fulfilled" === chunk.status && + null !== chunk.reason && + ((chunk = chunk.reason), + "function" === typeof chunk.error && chunk.error(error)); + }); + } + function getChunk(response, id) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk || + ((chunk = response._formData.data.get(response._prefix + id)), + (chunk = + "string" === typeof chunk + ? createResolvedModelChunk(response, chunk, id) + : response._closed + ? new ReactPromise("rejected", null, response._closedReason) + : new ReactPromise("pending", null, null)), + chunks.set(id, chunk)); + return chunk; + } + function fulfillReference(response, reference, value, arrayRoot) { + var handler = reference.handler, + parentObject = reference.parentObject, + key = reference.key, + map = reference.map, + path = reference.path; + try { + for ( + var localLength = 0, + rootArrayContexts = response._rootArrayContexts, + i = 1; + i < path.length; + i++ + ) { + var name = path[i]; + if ( + "object" !== typeof value || + null === value || + (getPrototypeOf(value) !== ObjectPrototype && + getPrototypeOf(value) !== ArrayPrototype) || + !hasOwnProperty.call(value, name) + ) + throw Error("Invalid reference."); + value = value[name]; + if (isArrayImpl(value)) + (localLength = 0), + (arrayRoot = rootArrayContexts.get(value) || arrayRoot); + else if (((arrayRoot = null), "string" === typeof value)) + localLength = value.length; + else if ("bigint" === typeof value) { + var n = Math.abs(Number(value)); + localLength = 0 === n ? 1 : Math.floor(Math.log10(n)) + 1; + } else localLength = ArrayBuffer.isView(value) ? value.byteLength : 0; + } + var resolvedValue = map(response, value, parentObject, key); + var referenceArrayRoot = reference.arrayRoot; + null !== referenceArrayRoot && + (null !== arrayRoot + ? (arrayRoot.fork && (referenceArrayRoot.fork = !0), + bumpArrayCount(referenceArrayRoot, arrayRoot.count, response)) + : 0 < localLength && + bumpArrayCount(referenceArrayRoot, localLength, response)); + } catch (error) { + rejectReference(response, handler, error); + return; + } + resolveReference(response, handler, parentObject, key, resolvedValue); + } + function resolveReference( + response, + handler, + parentObject, + key, + resolvedValue + ) { + "__proto__" !== key && (parentObject[key] = resolvedValue); + "" === key && null === handler.value && (handler.value = resolvedValue); + handler.deps--; + 0 === handler.deps && + ((parentObject = handler.chunk), + null !== parentObject && + "blocked" === parentObject.status && + ((key = parentObject.value), + (parentObject.status = "fulfilled"), + (parentObject.value = handler.value), + (parentObject.reason = handler.reason), + null !== key && + wakeChunk(response, key, handler.value, parentObject))); + } + function rejectReference(response, handler, error) { + handler.errored || + ((handler.errored = !0), + (handler.value = null), + (handler.reason = error), + (handler = handler.chunk), + null !== handler && + "blocked" === handler.status && + triggerErrorOnChunk(response, handler, error)); + } + function getOutlinedModel( + response, + reference, + parentObject, + key, + referenceArrayRoot, + map + ) { + reference = reference.split(":"); + var id = parseInt(reference[0], 16), + chunk = getChunk(response, id); + switch (chunk.status) { + case "resolved_model": + initializeModelChunk(chunk); + } + switch (chunk.status) { + case "fulfilled": + id = chunk.value; + chunk = chunk.reason; + if (null !== chunk && "error" in chunk) + throw Error( + "Expected an initialized chunk but got an initialized stream chunk instead. This payload may have been submitted by an older version of React." + ); + for ( + var localLength = 0, + rootArrayContexts = response._rootArrayContexts, + i = 1; + i < reference.length; + i++ + ) { + localLength = reference[i]; + if ( + "object" !== typeof id || + null === id || + (getPrototypeOf(id) !== ObjectPrototype && + getPrototypeOf(id) !== ArrayPrototype) || + !hasOwnProperty.call(id, localLength) + ) + throw Error("Invalid reference."); + id = id[localLength]; + isArrayImpl(id) + ? ((localLength = 0), + (chunk = rootArrayContexts.get(id) || chunk)) + : ((chunk = null), + "string" === typeof id + ? (localLength = id.length) + : "bigint" === typeof id + ? ((localLength = Math.abs(Number(id))), + (localLength = + 0 === localLength + ? 1 + : Math.floor(Math.log10(localLength)) + 1)) + : (localLength = ArrayBuffer.isView(id) + ? id.byteLength + : 0)); + } + parentObject = map(response, id, parentObject, key); + null !== referenceArrayRoot && + (null !== chunk + ? (chunk.fork && (referenceArrayRoot.fork = !0), + bumpArrayCount(referenceArrayRoot, chunk.count, response)) + : 0 < localLength && + bumpArrayCount(referenceArrayRoot, localLength, response)); + return parentObject; + case "blocked": + return ( + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (response = initializingHandler = + { + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }), + (referenceArrayRoot = { + handler: response, + parentObject: parentObject, + key: key, + map: map, + path: reference, + arrayRoot: referenceArrayRoot + }), + null === chunk.value + ? (chunk.value = [referenceArrayRoot]) + : chunk.value.push(referenceArrayRoot), + null === chunk.reason + ? (chunk.reason = [referenceArrayRoot]) + : chunk.reason.push(referenceArrayRoot), + null + ); + case "pending": + throw Error("Invalid forward reference."); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = chunk.reason)) + : (initializingHandler = { + chunk: null, + value: null, + reason: chunk.reason, + deps: 0, + errored: !0 + }), + null + ); + } + } + function createMap(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Map initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Map."); + model.$$consumed = !0; + return new Map(model); + } + function createSet(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Set initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Set."); + model.$$consumed = !0; + return new Set(model); + } + function extractIterator(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Iterator initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Iterator."); + model.$$consumed = !0; + return model[Symbol.iterator](); + } + function createModel(response, model, parentObject, key) { + return "then" === key && "function" === typeof model ? null : model; + } + function parseTypedArray( + response, + reference, + constructor, + bytesPerElement, + parentObject, + parentKey, + referenceArrayRoot + ) { + function reject(error) { + if (!handler.errored) { + handler.errored = !0; + handler.value = null; + handler.reason = error; + var chunk = handler.chunk; + null !== chunk && + "blocked" === chunk.status && + triggerErrorOnChunk(response, chunk, error); + } + } + reference = parseInt(reference.slice(2), 16); + var key = response._prefix + reference; + bytesPerElement = response._chunks; + if (bytesPerElement.has(reference)) + throw Error("Already initialized typed array."); + bytesPerElement.set( + reference, + new ReactPromise( + "rejected", + null, + Error("Already initialized typed array.") + ) + ); + reference = response._formData.data.get(key).arrayBuffer(); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + reference.then(function (buffer) { + try { + null !== referenceArrayRoot && + bumpArrayCount(referenceArrayRoot, buffer.byteLength, response); + var resolvedValue = + constructor === ArrayBuffer ? buffer : new constructor(buffer); + "__proto__" !== key && (parentObject[parentKey] = resolvedValue); + "" === parentKey && + null === handler.value && + (handler.value = resolvedValue); + } catch (x) { + reject(x); + return; + } + handler.deps--; + 0 === handler.deps && + ((buffer = handler.chunk), + null !== buffer && + "blocked" === buffer.status && + ((resolvedValue = buffer.value), + (buffer.status = "fulfilled"), + (buffer.value = handler.value), + (buffer.reason = null), + null !== resolvedValue && + wakeChunk(response, resolvedValue, handler.value, buffer))); + }, reject); + return null; + } + function resolveStream(response, id, stream, controller) { + var chunks = response._chunks; + stream = new ReactPromise("fulfilled", stream, controller); + chunks.set(id, stream); + response = response._formData.data.getAll(response._prefix + id); + for (id = 0; id < response.length; id++) + (chunks = response[id]), + "string" === typeof chunks && + ("C" === chunks[0] + ? controller.close( + "C" === chunks ? '"$undefined"' : chunks.slice(1) + ) + : controller.enqueueModel(chunks)); + } + function parseReadableStream(response, reference, type) { + function enqueue(value) { + "bytes" !== type || ArrayBuffer.isView(value) + ? controller.enqueue(value) + : flightController.error(Error("Invalid data for bytes stream.")); + } + reference = parseInt(reference.slice(2), 16); + if (response._chunks.has(reference)) + throw Error("Already initialized stream."); + var controller = null, + closed = !1, + stream = new ReadableStream({ + type: type, + start: function (c) { + controller = c; + } + }), + previousBlockedChunk = null, + flightController = { + enqueueModel: function (json) { + if (null === previousBlockedChunk) { + var chunk = createResolvedModelChunk(response, json, -1); + initializeModelChunk(chunk); + "fulfilled" === chunk.status + ? enqueue(chunk.value) + : (chunk.then(enqueue, flightController.error), + (previousBlockedChunk = chunk)); + } else { + chunk = previousBlockedChunk; + var _chunk = new ReactPromise("pending", null, null); + _chunk.then(enqueue, flightController.error); + previousBlockedChunk = _chunk; + chunk.then(function () { + previousBlockedChunk === _chunk && + (previousBlockedChunk = null); + resolveModelChunk(response, _chunk, json, -1); + }); + } + }, + close: function () { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.close(); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.close(); + }); + } + }, + error: function (error) { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.error(error); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.error(error); + }); + } + } + }; + resolveStream(response, reference, stream, flightController); + return stream; + } + function FlightIterator(next) { + this.next = next; + } + function parseAsyncIterable(response, reference, iterator) { + reference = parseInt(reference.slice(2), 16); + if (response._chunks.has(reference)) + throw Error("Already initialized stream."); + var buffer = [], + closed = !1, + nextWriteIndex = 0, + $jscomp$compprop5 = {}; + $jscomp$compprop5 = + (($jscomp$compprop5[ASYNC_ITERATOR] = function () { + var nextReadIndex = 0; + return new FlightIterator(function (arg) { + if (void 0 !== arg) + throw Error( + "Values cannot be passed to next() of AsyncIterables passed to Client Components." + ); + if (nextReadIndex === buffer.length) { + if (closed) + return new ReactPromise( + "fulfilled", + { done: !0, value: void 0 }, + null + ); + buffer[nextReadIndex] = new ReactPromise("pending", null, null); + } + return buffer[nextReadIndex++]; + }); + }), + $jscomp$compprop5); + iterator = iterator + ? $jscomp$compprop5[ASYNC_ITERATOR]() + : $jscomp$compprop5; + resolveStream(response, reference, iterator, { + enqueueModel: function (value) { + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !1 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !1 + ); + nextWriteIndex++; + }, + close: function (value) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !0 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !0 + ), + nextWriteIndex++; + nextWriteIndex < buffer.length; + + ) + resolveIteratorResultChunk( + response, + buffer[nextWriteIndex++], + '"$undefined"', + !0 + ); + }, + error: function (error) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length && + (buffer[nextWriteIndex] = new ReactPromise( + "pending", + null, + null + )); + nextWriteIndex < buffer.length; + + ) + triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); + } + }); + return iterator; + } + function parseModelString(response, obj, key, value, reference, arrayRoot) { + if ("$" === value[0]) { + switch (value[1]) { + case "$": + return ( + null !== arrayRoot && + bumpArrayCount(arrayRoot, value.length - 1, response), + value.slice(1) + ); + case "@": + return ( + (obj = parseInt(value.slice(2), 16)), getChunk(response, obj) + ); + case "h": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel( + response, + arrayRoot, + obj, + key, + null, + loadServerReference$1 + ) + ); + case "T": + if ( + void 0 === reference || + void 0 === response._temporaryReferences + ) + throw Error( + "Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server." + ); + return createTemporaryReference( + response._temporaryReferences, + reference + ); + case "Q": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel(response, arrayRoot, obj, key, null, createMap) + ); + case "W": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel(response, arrayRoot, obj, key, null, createSet) + ); + case "K": + key = value.slice(2); + obj = response._prefix + "_"; + key = obj + key + "_"; + arrayRoot = new FormData(); + for (response = response._formData; ; ) { + value = response; + reference = value.keys; + null === reference && + ((reference = value.keys = Array.from(value.data.keys())), + (value.keyPointer = 0)); + value = reference[value.keyPointer]; + if (void 0 === value) break; + if (value.startsWith(key)) { + reference = response.data.getAll(value); + for ( + var referencedFormDataKey = value.slice(key.length), i = 0; + i < reference.length; + i++ + ) + arrayRoot.append(referencedFormDataKey, reference[i]); + reference = response; + reference.data.delete(value); + reference.keyPointer++; + } else if (value.startsWith(obj)) break; + else response.keyPointer++; + } + return arrayRoot; + case "i": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel( + response, + arrayRoot, + obj, + key, + null, + extractIterator + ) + ); + case "I": + return Infinity; + case "-": + return "$-0" === value ? -0 : -Infinity; + case "N": + return NaN; + case "u": + return; + case "D": + return new Date(Date.parse(value.slice(2))); + case "n": + obj = value.slice(2); + if (obj.length > MAX_BIGINT_DIGITS) + throw Error( + "BigInt is too large. Received " + + obj.length + + " digits but the limit is " + + MAX_BIGINT_DIGITS + + "." + ); + null !== arrayRoot && + bumpArrayCount(arrayRoot, obj.length, response); + return BigInt(obj); + case "A": + return parseTypedArray( + response, + value, + ArrayBuffer, + 1, + obj, + key, + arrayRoot + ); + case "O": + return parseTypedArray( + response, + value, + Int8Array, + 1, + obj, + key, + arrayRoot + ); + case "o": + return parseTypedArray( + response, + value, + Uint8Array, + 1, + obj, + key, + arrayRoot + ); + case "U": + return parseTypedArray( + response, + value, + Uint8ClampedArray, + 1, + obj, + key, + arrayRoot + ); + case "S": + return parseTypedArray( + response, + value, + Int16Array, + 2, + obj, + key, + arrayRoot + ); + case "s": + return parseTypedArray( + response, + value, + Uint16Array, + 2, + obj, + key, + arrayRoot + ); + case "L": + return parseTypedArray( + response, + value, + Int32Array, + 4, + obj, + key, + arrayRoot + ); + case "l": + return parseTypedArray( + response, + value, + Uint32Array, + 4, + obj, + key, + arrayRoot + ); + case "G": + return parseTypedArray( + response, + value, + Float32Array, + 4, + obj, + key, + arrayRoot + ); + case "g": + return parseTypedArray( + response, + value, + Float64Array, + 8, + obj, + key, + arrayRoot + ); + case "M": + return parseTypedArray( + response, + value, + BigInt64Array, + 8, + obj, + key, + arrayRoot + ); + case "m": + return parseTypedArray( + response, + value, + BigUint64Array, + 8, + obj, + key, + arrayRoot + ); + case "V": + return parseTypedArray( + response, + value, + DataView, + 1, + obj, + key, + arrayRoot + ); + case "B": + obj = parseInt(value.slice(2), 16); + response = response._formData.data.get(response._prefix + obj); + if (!(response instanceof Blob)) + throw Error("Referenced Blob is not a Blob."); + return response; + case "R": + return parseReadableStream(response, value, void 0); + case "r": + return parseReadableStream(response, value, "bytes"); + case "X": + return parseAsyncIterable(response, value, !1); + case "x": + return parseAsyncIterable(response, value, !0); + } + value = value.slice(1); + return getOutlinedModel( + response, + value, + obj, + key, + arrayRoot, + createModel + ); + } + null !== arrayRoot && bumpArrayCount(arrayRoot, value.length, response); + return value; + } + function createResponse( + bundlerConfig, + formFieldPrefix, + temporaryReferences + ) { + var backingFormData = + 3 < arguments.length && void 0 !== arguments[3] + ? arguments[3] + : new FormData(), + arraySizeLimit = + 4 < arguments.length && void 0 !== arguments[4] ? arguments[4] : 1e6, + chunks = new Map(); + return { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: { data: backingFormData, keyPointer: -1, keys: null }, + _chunks: chunks, + _closed: !1, + _closedReason: null, + _temporaryReferences: temporaryReferences, + _rootArrayContexts: new WeakMap(), + _arraySizeLimit: arraySizeLimit + }; + } + function resolveField(response, key, value) { + appendBackingEntry(response._formData, key, value); + var prefix = response._prefix; + if (key.startsWith(prefix)) { + var chunks = response._chunks; + key = +key.slice(prefix.length); + (chunks = chunks.get(key)) && + resolveModelChunk(response, chunks, value, key); + } + } + function close(response) { + reportGlobalError(response, Error("Connection closed.")); + } + function loadServerReference(bundlerConfig, metaData) { + var id = metaData.id; + if ("string" !== typeof id) return null; + var serverReference = resolveServerReference(bundlerConfig, id); + bundlerConfig = preloadModule(serverReference); + metaData = metaData.bound; + return metaData instanceof Promise + ? Promise.all([metaData, bundlerConfig]).then(function (_ref) { + _ref = _ref[0]; + var fn = requireModule(serverReference); + if (_ref.length > MAX_BOUND_ARGS) + throw Error( + "Server Function has too many bound arguments. Received " + + _ref.length + + " but the limit is " + + MAX_BOUND_ARGS + + "." + ); + return fn.bind.apply(fn, [null].concat(_ref)); + }) + : bundlerConfig + ? Promise.resolve(bundlerConfig).then(function () { + return requireModule(serverReference); + }) + : Promise.resolve(requireModule(serverReference)); + } + function decodeBoundActionMetaData( + body, + serverManifest, + formFieldPrefix, + arraySizeLimit + ) { + body = createResponse( + serverManifest, + formFieldPrefix, + void 0, + body, + arraySizeLimit + ); + close(body); + body = getChunk(body, 0); + body.then(function () {}); + if ("fulfilled" !== body.status) throw body.reason; + return body.value; + } + function decodeAction$1(body, serverManifest) { + var formData = new FormData(), + maybeActionKey = null; + body.forEach(function (value, key) { + key.startsWith("$ACTION_") + ? key.startsWith("$ACTION_REF_") + ? (maybeActionKey = key) + : key.startsWith("$ACTION_ID_") && (maybeActionKey = key) + : formData.append(key, value); + }); + if (null === maybeActionKey) return null; + var actionKey = maybeActionKey, + action = null; + if (actionKey.startsWith("$ACTION_REF_")) + (actionKey = "$ACTION_" + actionKey.slice(12) + ":"), + (body = decodeBoundActionMetaData(body, serverManifest, actionKey)), + (action = loadServerReference(serverManifest, body)); + else if (actionKey.startsWith("$ACTION_ID_")) + (body = actionKey.slice(11)), + (action = loadServerReference(serverManifest, { + id: body, + bound: null + })); + else throw Error("Cannot handle action key. This is a bug in React."); + return action.then(function (fn) { + return fn.bind(null, formData); + }); + } + function decodeFormState$1(actionResult, body, serverManifest) { + var keyPath = body.get("$ACTION_KEY"); + if ("string" !== typeof keyPath) return Promise.resolve(null); + var actionKey = null; + body.forEach(function (value, key) { + key.startsWith("$ACTION_REF_") && (actionKey = key); + }); + if (null === actionKey) return Promise.resolve(null); + var formFieldPrefix = "$ACTION_" + actionKey.slice(12) + ":"; + body = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + var referenceId = body.id; + return Promise.resolve(body.bound).then(function (bound) { + return null === bound + ? null + : [actionResult, keyPath, referenceId, bound.length - 1]; + }); + } + function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; + } + function createCancelHandler(request, reason) { + return function () { + request.destination = null; + abort(request, Error(reason)); + }; + } + function startReadingFromDebugChannelReadable(request, stream) { + function onData(chunk) { + if ("string" === typeof chunk) { + if (lastWasPartial) { + var JSCompiler_temp_const = stringBuffer; + var JSCompiler_inline_result = new Uint8Array(0); + JSCompiler_inline_result = stringDecoder.decode( + JSCompiler_inline_result + ); + stringBuffer = JSCompiler_temp_const + JSCompiler_inline_result; + lastWasPartial = !1; + } + stringBuffer += chunk; + } else + (stringBuffer += stringDecoder.decode(chunk, decoderOptions)), + (lastWasPartial = !0); + chunk = stringBuffer.split("\n"); + for ( + JSCompiler_temp_const = 0; + JSCompiler_temp_const < chunk.length - 1; + JSCompiler_temp_const++ + ) + resolveDebugMessage(request, chunk[JSCompiler_temp_const]); + stringBuffer = chunk[chunk.length - 1]; + } + function onError(error) { + abort( + request, + Error("Lost connection to the Debug Channel.", { cause: error }) + ); + } + function onClose() { + closeDebugChannel(request); + } + var stringDecoder = new util.TextDecoder(), + lastWasPartial = !1, + stringBuffer = ""; + "function" === typeof stream.addEventListener && + "string" === typeof stream.binaryType + ? ((stream.binaryType = "arraybuffer"), + stream.addEventListener("message", function (event) { + onData(event.data); + }), + stream.addEventListener("error", function (event) { + onError(event.error); + }), + stream.addEventListener("close", onClose)) + : (stream.on("data", onData), + stream.on("error", onError), + stream.on("end", onClose)); + } + function createFakeWritableFromWebSocket(webSocket) { + return { + write: function (chunk) { + webSocket.send(chunk); + return !0; + }, + end: function () { + webSocket.close(); + }, + destroy: function (reason) { + "object" === typeof reason && + null !== reason && + (reason = reason.message); + "string" === typeof reason + ? webSocket.close(1011, reason) + : webSocket.close(1011); + } + }; + } + function createFakeWritableFromReadableStreamController(controller) { + return { + write: function (chunk) { + "string" === typeof chunk && (chunk = textEncoder.encode(chunk)); + controller.enqueue(chunk); + return !0; + }, + end: function () { + controller.close(); + }, + destroy: function (error) { + "function" === typeof controller.error + ? controller.error(error) + : controller.close(); + } + }; + } + function startReadingFromDebugChannelReadableStream(request, stream) { + function progress(_ref) { + var done = _ref.done, + buffer = _ref.value; + _ref = stringBuffer; + done + ? ((buffer = new Uint8Array(0)), + (buffer = stringDecoder.decode(buffer))) + : (buffer = stringDecoder.decode(buffer, decoderOptions)); + stringBuffer = _ref + buffer; + _ref = stringBuffer.split("\n"); + for (buffer = 0; buffer < _ref.length - 1; buffer++) + resolveDebugMessage(request, _ref[buffer]); + stringBuffer = _ref[_ref.length - 1]; + if (done) closeDebugChannel(request); + else return reader.read().then(progress).catch(error); + } + function error(e) { + abort( + request, + Error("Lost connection to the Debug Channel.", { cause: e }) + ); + } + var reader = stream.getReader(), + stringDecoder = new util.TextDecoder(), + stringBuffer = ""; + reader.read().then(progress).catch(error); + } + function createFakeWritableFromNodeReadable(readable) { + return { + write: function (chunk) { + return readable.push(chunk); + }, + end: function () { + readable.push(null); + }, + destroy: function (error) { + readable.destroy(error); + } + }; + } + var ReactDOM = __webpack_require__("./node_modules/react-dom/react-dom.react-server.js"), + stream = __webpack_require__("stream"), + util = __webpack_require__("util"); + __webpack_require__("crypto"); + var async_hooks = __webpack_require__("async_hooks"), + React = __webpack_require__("./node_modules/react/react.react-server.js"), + assign = Object.assign, + CLIENT_REFERENCE_TAG$1 = Symbol.for("react.client.reference"), + SERVER_REFERENCE_TAG = Symbol.for("react.server.reference"), + FunctionBind = Function.prototype.bind, + ArraySlice = Array.prototype.slice, + serverReferenceToString = { + value: function () { + return "function () { [omitted code] }"; + }, + configurable: !0, + writable: !0 + }, + currentStrategy = { + encrypt: function (_actionId) { + for ( + var _len = arguments.length, + args = Array(1 < _len ? _len - 1 : 0), + _key = 1; + _key < _len; + _key++ + ) + args[_key - 1] = arguments[_key]; + return Promise.resolve(args); + }, + decrypt: function (_actionId, payloadPromise) { + return payloadPromise; + } + }, + REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator, + ASYNC_ITERATOR = Symbol.asyncIterator, + REACT_OPTIMISTIC_KEY = Symbol.for("react.optimistic_key"), + scheduleMicrotask = queueMicrotask, + currentView = null, + writtenBytes = 0, + destinationHasCapacity = !0, + textEncoder = new util.TextEncoder(), + ReactDOMSharedInternals = + ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + previousDispatcher = ReactDOMSharedInternals.d; + ReactDOMSharedInternals.d = { + f: previousDispatcher.f, + r: previousDispatcher.r, + D: function (href) { + if ("string" === typeof href && href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "D|" + href; + hints.has(key) || (hints.add(key), emitHint(request, "D", href)); + } else previousDispatcher.D(href); + } + }, + C: function (href, crossOrigin) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = + "C|" + + (null == crossOrigin ? "null" : crossOrigin) + + "|" + + href; + hints.has(key) || + (hints.add(key), + "string" === typeof crossOrigin + ? emitHint(request, "C", [href, crossOrigin]) + : emitHint(request, "C", href)); + } else previousDispatcher.C(href, crossOrigin); + } + }, + L: preload, + m: preloadModule$1, + X: function (src, options) { + if ("string" === typeof src) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "X|" + src; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "X", [src, options]) + : emitHint(request, "X", src); + } + previousDispatcher.X(src, options); + } + }, + S: function (href, precedence, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "S|" + href; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "S", [ + href, + "string" === typeof precedence ? precedence : 0, + options + ]) + : "string" === typeof precedence + ? emitHint(request, "S", [href, precedence]) + : emitHint(request, "S", href); + } + previousDispatcher.S(href, precedence, options); + } + }, + M: function (src, options) { + if ("string" === typeof src) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "M|" + src; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "M", [src, options]) + : emitHint(request, "M", src); + } + previousDispatcher.M(src, options); + } + } + }; + var currentOwner = null, + getAsyncId = async_hooks.AsyncResource.prototype.asyncId, + pendingOperations = new Map(), + lastRanAwait = null, + emptyStack = [], + framesToSkip = 0, + collectedStackTrace = null, + identifierRegExp = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/, + frameRegExp = + /^ {3} at (?:(.+) \((?:(.+):(\d+):(\d+)|)\)|(?:async )?(.+):(\d+):(\d+)|)$/, + stackTraceCache = new WeakMap(), + requestStorage = new async_hooks.AsyncLocalStorage(), + componentStorage = new async_hooks.AsyncLocalStorage(), + TEMPORARY_REFERENCE_TAG = Symbol.for("react.temporary.reference"), + proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + case "$$typeof": + return target.$$typeof; + case "name": + return; + case "displayName": + return; + case "defaultProps": + return; + case "_debugInfo": + return; + case "toJSON": + return; + case Symbol.toPrimitive: + return Object.prototype[Symbol.toPrimitive]; + case Symbol.toStringTag: + return Object.prototype[Symbol.toStringTag]; + case "Provider": + return receiver; + case "then": + return; + } + throw Error( + "Cannot access " + + String(name) + + " on the server. You cannot dot into a temporary client reference from a server component. You can only pass the value through to the client." + ); + }, + set: function () { + throw Error( + "Cannot assign to a temporary client reference from a server module." + ); + } + }, + SuspenseException = Error( + "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`." + ), + suspendedThenable = null, + currentRequest$1 = null, + thenableIndexCounter = 0, + thenableState = null, + currentComponentDebugInfo = null, + HooksDispatcher = { + readContext: unsupportedContext, + use: function (usable) { + if ( + (null !== usable && "object" === typeof usable) || + "function" === typeof usable + ) { + if ("function" === typeof usable.then) { + var index = thenableIndexCounter; + thenableIndexCounter += 1; + null === thenableState && (thenableState = []); + return trackUsedThenable(thenableState, usable, index); + } + usable.$$typeof === REACT_CONTEXT_TYPE && unsupportedContext(); + } + if (isClientReference(usable)) { + if ( + null != usable.value && + usable.value.$$typeof === REACT_CONTEXT_TYPE + ) + throw Error( + "Cannot read a Client Context from a Server Component." + ); + throw Error("Cannot use() an already resolved Client Reference."); + } + throw Error( + "An unsupported type was passed to use(): " + String(usable) + ); + }, + useCallback: function (callback) { + return callback; + }, + useContext: unsupportedContext, + useEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useLayoutEffect: unsupportedHook, + useInsertionEffect: unsupportedHook, + useMemo: function (nextCreate) { + return nextCreate(); + }, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useId: function () { + if (null === currentRequest$1) + throw Error("useId can only be used while React is rendering"); + var id = currentRequest$1.identifierCount++; + return ( + "_" + + currentRequest$1.identifierPrefix + + "S_" + + id.toString(32) + + "_" + ); + }, + useHostTransitionStatus: unsupportedHook, + useFormState: unsupportedHook, + useActionState: unsupportedHook, + useOptimistic: unsupportedHook, + useMemoCache: function (size) { + for (var data = Array(size), i = 0; i < size; i++) + data[i] = REACT_MEMO_CACHE_SENTINEL; + return data; + }, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useEffectEvent: unsupportedHook + }, + DefaultAsyncDispatcher = { + getCacheForType: function (resourceType) { + var cache = (cache = resolveRequest()) ? cache.cache : new Map(); + var entry = cache.get(resourceType); + void 0 === entry && + ((entry = resourceType()), cache.set(resourceType, entry)); + return entry; + }, + cacheSignal: function () { + var request = resolveRequest(); + return request ? request.cacheController.signal : null; + } + }; + DefaultAsyncDispatcher.getOwner = resolveOwner; + var ReactSharedInternalsServer = + React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + if (!ReactSharedInternalsServer) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); + var prefix, suffix; + new ("function" === typeof WeakMap ? WeakMap : Map)(); + var lastResetTime = 0; + if ( + "object" === typeof performance && + "function" === typeof performance.now + ) { + var localPerformance = performance; + var getCurrentTime = function () { + return localPerformance.now(); + }; + } else { + var localDate = Date; + getCurrentTime = function () { + return localDate.now(); + }; + } + var callComponent = { + react_stack_bottom_frame: function ( + Component, + props, + componentDebugInfo + ) { + currentOwner = componentDebugInfo; + try { + return Component(props, void 0); + } finally { + currentOwner = null; + } + } + }, + callComponentInDEV = + callComponent.react_stack_bottom_frame.bind(callComponent), + callLazyInit = { + react_stack_bottom_frame: function (lazy) { + var init = lazy._init; + return init(lazy._payload); + } + }, + callLazyInitInDEV = + callLazyInit.react_stack_bottom_frame.bind(callLazyInit), + callIterator = { + react_stack_bottom_frame: function (iterator, progress, error) { + iterator.next().then(progress, error); + } + }, + callIteratorInDEV = + callIterator.react_stack_bottom_frame.bind(callIterator), + isArrayImpl = Array.isArray, + getPrototypeOf = Object.getPrototypeOf, + jsxPropsParents = new WeakMap(), + jsxChildrenParents = new WeakMap(), + CLIENT_REFERENCE_TAG = Symbol.for("react.client.reference"), + hasOwnProperty = Object.prototype.hasOwnProperty, + doNotLimit = new WeakSet(); + (function () { + async_hooks + .createHook({ + init: function (asyncId, type, triggerAsyncId, resource) { + var trigger = pendingOperations.get(triggerAsyncId); + if ("PROMISE" === type) + if ( + ((type = async_hooks.executionAsyncId()), + type !== triggerAsyncId) + ) { + if (void 0 === trigger) return; + triggerAsyncId = null; + if ( + null === trigger.stack || + (2 !== trigger.tag && 4 !== trigger.tag) + ) { + resource = new WeakRef(resource); + var request = resolveRequest(); + null !== request && + ((triggerAsyncId = parseStackTracePrivate(Error(), 5)), + null === triggerAsyncId || + isAwaitInUserspace(request, triggerAsyncId) || + (triggerAsyncId = null)); + } else + (triggerAsyncId = emptyStack), + (resource = + void 0 !== resource._debugInfo + ? new WeakRef(resource) + : trigger.promise); + type = pendingOperations.get(type); + trigger = { + tag: 4, + owner: resolveOwner(), + stack: triggerAsyncId, + start: performance.now(), + end: -1.1, + promise: resource, + awaited: trigger, + previous: void 0 === type ? null : type + }; + } else + (type = resolveOwner()), + (trigger = { + tag: 3, + owner: type, + stack: + null === type ? null : parseStackTracePrivate(Error(), 5), + start: performance.now(), + end: -1.1, + promise: new WeakRef(resource), + awaited: void 0 === trigger ? null : trigger, + previous: null + }); + else if ( + "bound-anonymous-fn" === type || + "Microtask" === type || + "TickObject" === type || + "Immediate" === type + ) { + if (void 0 === trigger) return; + } else if (void 0 === trigger) + (trigger = resolveOwner()), + (trigger = { + tag: 0, + owner: trigger, + stack: + null === trigger + ? parseStackTracePrivate(Error(), 3) + : null, + start: performance.now(), + end: -1.1, + promise: null, + awaited: null, + previous: null + }); + else if (2 === trigger.tag || 4 === trigger.tag) + (resource = resolveOwner()), + (trigger = { + tag: 0, + owner: resource, + stack: + null === resource + ? parseStackTracePrivate(Error(), 3) + : null, + start: performance.now(), + end: -1.1, + promise: null, + awaited: null, + previous: trigger + }); + pendingOperations.set(asyncId, trigger); + }, + before: function (asyncId) { + var node = pendingOperations.get(asyncId); + if (void 0 !== node) + switch (node.tag) { + case 0: + lastRanAwait = null; + 0 > node.end + ? (node.end = performance.now()) + : ((node = { + tag: 0, + owner: node.owner, + stack: node.stack, + start: node.start, + end: performance.now(), + promise: node.promise, + awaited: node.awaited, + previous: node.previous + }), + pendingOperations.set(asyncId, node)); + break; + case 4: + lastRanAwait = resolvePromiseOrAwaitNode( + node, + performance.now() + ); + break; + case 2: + lastRanAwait = node; + break; + case 3: + resolvePromiseOrAwaitNode(node, performance.now()).previous = + lastRanAwait; + lastRanAwait = null; + break; + default: + lastRanAwait = null; + } + }, + promiseResolve: function (asyncId) { + var node = pendingOperations.get(asyncId); + if (void 0 !== node) { + switch (node.tag) { + case 4: + case 3: + node = resolvePromiseOrAwaitNode(node, performance.now()); + break; + case 2: + case 1: + break; + default: + throw Error( + "A Promise should never be an IO_NODE. This is a bug in React." + ); + } + var currentAsyncId = async_hooks.executionAsyncId(); + asyncId !== currentAsyncId && + ((asyncId = pendingOperations.get(currentAsyncId)), + 1 === node.tag + ? (node.awaited = void 0 === asyncId ? null : asyncId) + : void 0 !== asyncId && + ((currentAsyncId = { + tag: 2, + owner: node.owner, + stack: node.stack, + start: node.start, + end: node.end, + promise: node.promise, + awaited: node.awaited, + previous: node.previous + }), + (node.start = node.end), + (node.end = performance.now()), + (node.previous = currentAsyncId), + (node.awaited = asyncId))); + } + }, + destroy: function (asyncId) { + pendingOperations.delete(asyncId); + } + }) + .enable(); + })(); + "object" === typeof console && + null !== console && + (patchConsole(console, "assert"), + patchConsole(console, "debug"), + patchConsole(console, "dir"), + patchConsole(console, "dirxml"), + patchConsole(console, "error"), + patchConsole(console, "group"), + patchConsole(console, "groupCollapsed"), + patchConsole(console, "groupEnd"), + patchConsole(console, "info"), + patchConsole(console, "log"), + patchConsole(console, "table"), + patchConsole(console, "trace"), + patchConsole(console, "warn")); + var ObjectPrototype$1 = Object.prototype, + stringify = JSON.stringify, + PENDING$1 = 0, + COMPLETED = 1, + ABORTED = 3, + ERRORED$1 = 4, + RENDERING = 5, + __PROTO__$1 = "__proto__", + OPENING = 10, + ABORTING = 12, + CLOSING = 13, + CLOSED = 14, + PRERENDER = 21, + NEXT_TWO_CHUNKS_ARE_ATOMIC = Symbol(), + currentRequest = null, + canEmitDebugInfo = !1, + serializedSize = 0, + MAX_ROW_SIZE = 3200, + modelRoot = !1, + CONSTRUCTOR_MARKER = Symbol(), + debugModelRoot = null, + debugNoOutline = null, + emptyRoot = {}, + decoderOptions = { stream: !0 }, + chunkCache = new Map(), + RESPONSE_SYMBOL = Symbol(); + ReactPromise.prototype = Object.create(Promise.prototype); + Object.defineProperty(ReactPromise.prototype, "then", { + writable: !0, + enumerable: !0, + configurable: !0, + value: function (resolve, reject) { + switch (this.status) { + case "resolved_model": + initializeModelChunk(this); + } + switch (this.status) { + case "fulfilled": + if ("function" === typeof resolve) { + for ( + var inspectedValue = this.value, + cycleProtection = 0, + visited = new Set(); + inspectedValue instanceof ReactPromise; + + ) { + cycleProtection++; + if ( + inspectedValue === this || + visited.has(inspectedValue) || + 1e3 < cycleProtection + ) { + "function" === typeof reject && + reject(Error("Cannot have cyclic thenables.")); + return; + } + visited.add(inspectedValue); + if ("fulfilled" === inspectedValue.status) + inspectedValue = inspectedValue.value; + else break; + } + resolve(this.value); + } + break; + case "pending": + case "blocked": + "function" === typeof resolve && + (null === this.value && (this.value = []), + this.value.push(resolve)); + "function" === typeof reject && + (null === this.reason && (this.reason = []), + this.reason.push(reject)); + break; + default: + "function" === typeof reject && reject(this.reason); + } + } + }); + var ObjectPrototype = Object.prototype, + ArrayPrototype = Array.prototype, + initializingHandler = null; + FlightIterator.prototype = {}; + FlightIterator.prototype[ASYNC_ITERATOR] = function () { + return this; + }; + var MAX_BIGINT_DIGITS = 300, + MAX_BOUND_ARGS = 1e3; + exports.createServerEntry = function (value, resource) { + var entryJsFiles = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.entryJsFiles || [], + entryCssFiles = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.entryCssFiles[resource] || []; + ("function" === typeof value || + ("object" === typeof value && null !== value)) && + assign(value, { + resource: resource, + entryJsFiles: entryJsFiles, + entryCssFiles: entryCssFiles + }); + return value; + }; + exports.createTemporaryReferenceSet = function () { + return new WeakMap(); + }; + exports.decodeAction = function (body) { + return decodeAction$1(body, {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest); + }; + exports.decodeFormState = function (actionResult, body) { + return decodeFormState$1( + actionResult, + body, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest + ); + }; + exports.decodeReply = function (body, options) { + if ("string" === typeof body) { + var form = new FormData(); + form.append("0", body); + body = form; + } + body = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + body, + options ? options.arraySizeLimit : void 0 + ); + options = getChunk(body, 0); + close(body); + return options; + }; + exports.decodeReplyFromAsyncIterable = function (iterable, options) { + function progress(entry) { + if (entry.done) close(response); + else { + var _entry$value = entry.value; + entry = _entry$value[0]; + _entry$value = _entry$value[1]; + "string" === typeof _entry$value + ? resolveField(response, entry, _entry$value) + : appendBackingEntry(response._formData, entry, _entry$value); + iterator.next().then(progress, error); + } + } + function error(reason) { + reportGlobalError(response, reason); + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop); + } + var iterator = iterable[ASYNC_ITERATOR](), + response = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + void 0, + options ? options.arraySizeLimit : void 0 + ); + iterator.next().then(progress, error); + return getChunk(response, 0); + }; + exports.decodeReplyFromBusboy = function (busboyStream, options) { + function flush() { + for (; null !== head; ) { + var current = head; + if (!current.complete) return; + try { + var response = response$jscomp$0, + key = current.name, + handle = current.file, + blob = new Blob(handle.chunks, { type: handle.mime }), + backingStore = response._formData; + response = key; + backingStore.data.append(response, blob, handle.filename); + var keys = backingStore.keys; + null === keys + ? ((backingStore.keys = Array.from(backingStore.data.keys())), + (backingStore.keyPointer = 0)) + : keys.push(response); + var queuedFields = current.queuedFields; + if (null !== queuedFields) + for (response = 0; response < queuedFields.length; response += 2) + resolveField( + response$jscomp$0, + queuedFields[response], + queuedFields[response + 1] + ); + } catch (error) { + busboyStream.destroy(error); + return; + } + head = current.next; + } + tail = null; + bodyFinished && !closed && ((closed = !0), close(response$jscomp$0)); + } + var response$jscomp$0 = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + void 0, + options ? options.arraySizeLimit : void 0 + ), + head = null, + tail = null, + bodyFinished = !1, + closed = !1; + busboyStream.on("field", function (name, value) { + if (null !== tail) + null === tail.queuedFields && (tail.queuedFields = []), + tail.queuedFields.push(name, value); + else + try { + resolveField(response$jscomp$0, name, value); + } catch (error) { + busboyStream.destroy(error); + } + }); + busboyStream.on("file", function (name, value, _ref2) { + var filename = _ref2.filename, + mimeType = _ref2.mimeType; + if ("base64" === _ref2.encoding.toLowerCase()) + busboyStream.destroy( + Error( + "React doesn't accept base64 encoded file uploads because we don't expect form data passed from a browser to ever encode data that way. If that's the wrong assumption, we can easily fix it." + ) + ); + else { + var file = { chunks: [], filename: filename, mime: mimeType }, + pendingFile = { + name: name, + file: file, + complete: !1, + queuedFields: null, + next: null + }; + null === tail ? (head = pendingFile) : (tail.next = pendingFile); + tail = pendingFile; + value.on("data", function (chunk) { + try { + file.chunks.push(chunk); + } catch (error) { + busboyStream.destroy(error); + } + }); + value.on("error", function (error) { + busboyStream.destroy(error); + }); + value.on("end", function () { + pendingFile.complete = !0; + flush(); + }); + } + }); + busboyStream.on("finish", function () { + bodyFinished = !0; + flush(); + closed || + reportGlobalError( + response$jscomp$0, + Error("Reply finished with incomplete file part.") + ); + }); + busboyStream.on("error", function (err) { + reportGlobalError(response$jscomp$0, err); + }); + return getChunk(response$jscomp$0, 0); + }; + exports.decryptServerActionBoundArgs = function ( + actionId, + encryptedPromise + ) { + return currentStrategy.decrypt(actionId, encryptedPromise); + }; + exports.encryptServerActionBoundArgs = function (actionId) { + for ( + var _currentStrategy, + _len2 = arguments.length, + args = Array(1 < _len2 ? _len2 - 1 : 0), + _key2 = 1; + _key2 < _len2; + _key2++ + ) + args[_key2 - 1] = arguments[_key2]; + return (_currentStrategy = currentStrategy).encrypt.apply( + _currentStrategy, + [actionId].concat(args) + ); + }; + exports.ensureServerActions = function (actions) { + for (var i = 0; i < actions.length; i++) { + var action = actions[i]; + if ("function" !== typeof action) + throw Error( + 'A "use server" file can only export async functions, found ' + + typeof action + + "." + ); + } + }; + exports.loadServerAction = function (actionId) { + var actionModId = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest[actionId].id; + if (!actionModId) + throw Error( + 'Failed to find Server Action "' + + actionId + + '". This request might be from an older or newer deployment.' + ); + actionId = __webpack_require__(actionModId)[actionId]; + if ("function" !== typeof actionId) + throw Error("Server actions must be functions"); + return actionId; + }; + exports.prerender = function (model, options) { + return new Promise(function (resolve, reject) { + var request = createPrerenderRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + function () { + var writable, + stream = new ReadableStream( + { + type: "bytes", + start: function (controller) { + writable = + createFakeWritableFromReadableStreamController( + controller + ); + }, + pull: function () { + startFlowing(request, writable); + }, + cancel: function (reason) { + request.destination = null; + abort(request, reason); + } + }, + { highWaterMark: 0 } + ); + resolve({ prelude: stream }); + }, + reject, + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0, + options ? options.startTime : void 0, + options ? options.environmentName : void 0, + options ? options.filterStackFrame : void 0, + !1 + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + startWork(request); + }); + }; + exports.prerenderToNodeStream = function (model, options) { + return new Promise(function (resolve, reject) { + var request = createPrerenderRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + function () { + var readable = new stream.Readable({ + read: function () { + startFlowing(request, writable); + } + }), + writable = createFakeWritableFromNodeReadable(readable); + resolve({ prelude: readable }); + }, + reject, + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0, + options ? options.startTime : void 0, + options ? options.environmentName : void 0, + options ? options.filterStackFrame : void 0, + !1 + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + startWork(request); + }); + }; + exports.registerClientReference = function ( + proxyImplementation, + id, + exportName + ) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { value: CLIENT_REFERENCE_TAG$1 }, + $$id: { value: id + "#" + exportName }, + $$async: { value: !1 } + }); + }; + exports.registerServerReference = function (reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { value: SERVER_REFERENCE_TAG }, + $$id: { + value: null === exportName ? id : id + "#" + exportName, + configurable: !0 + }, + $$bound: { value: null, configurable: !0 }, + $$location: { value: Error("react-stack-top-frame"), configurable: !0 }, + bind: { value: bind, configurable: !0 }, + toString: serverReferenceToString + }); + }; + exports.renderToPipeableStream = function (model, options) { + var debugChannel = options ? options.debugChannel : void 0, + debugChannelReadable = + void 0 === debugChannel || + ("function" !== typeof debugChannel.read && + "number" !== typeof debugChannel.readyState) + ? void 0 + : debugChannel; + debugChannel = + void 0 !== debugChannel + ? "function" === typeof debugChannel.write + ? debugChannel + : "function" === typeof debugChannel.send + ? createFakeWritableFromWebSocket(debugChannel) + : void 0 + : void 0; + var request = createRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0, + options ? options.startTime : void 0, + options ? options.environmentName : void 0, + options ? options.filterStackFrame : void 0, + void 0 !== debugChannelReadable + ), + hasStartedFlowing = !1; + startWork(request); + void 0 !== debugChannel && startFlowingDebug(request, debugChannel); + void 0 !== debugChannelReadable && + startReadingFromDebugChannelReadable(request, debugChannelReadable); + return { + pipe: function (destination) { + if (hasStartedFlowing) + throw Error( + "React currently only supports piping to one writable stream." + ); + hasStartedFlowing = !0; + startFlowing(request, destination); + destination.on("drain", createDrainHandler(destination, request)); + destination.on( + "error", + createCancelHandler( + request, + "The destination stream errored while writing data." + ) + ); + if (void 0 === debugChannelReadable) + destination.on( + "close", + createCancelHandler( + request, + "The destination stream closed early." + ) + ); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; + }; + exports.renderToReadableStream = function (model, options) { + var debugChannelReadable = + options && options.debugChannel + ? options.debugChannel.readable + : void 0, + debugChannelWritable = + options && options.debugChannel + ? options.debugChannel.writable + : void 0, + request = createRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0, + options ? options.startTime : void 0, + options ? options.environmentName : void 0, + options ? options.filterStackFrame : void 0, + void 0 !== debugChannelReadable + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + if (void 0 !== debugChannelWritable) { + var debugWritable; + new ReadableStream( + { + type: "bytes", + start: function (controller) { + debugWritable = + createFakeWritableFromReadableStreamController(controller); + }, + pull: function () { + startFlowingDebug(request, debugWritable); + } + }, + { highWaterMark: 0 } + ).pipeTo(debugChannelWritable); + } + void 0 !== debugChannelReadable && + startReadingFromDebugChannelReadableStream( + request, + debugChannelReadable + ); + var writable; + return new ReadableStream( + { + type: "bytes", + start: function (controller) { + writable = + createFakeWritableFromReadableStreamController(controller); + startWork(request); + }, + pull: function () { + startFlowing(request, writable); + }, + cancel: function (reason) { + request.destination = null; + abort(request, reason); + } + }, + { highWaterMark: 0 } + ); + }; + exports.setServerActionBoundArgsEncryption = function (strategy) { + currentStrategy = strategy; + }; + })(); + + +}, +"./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-server-dom-rspack-server.node.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var ReactDOM = __webpack_require__("./node_modules/react-dom/react-dom.react-server.js"), + stream = __webpack_require__("stream"), + util = __webpack_require__("util"); +__webpack_require__("crypto"); +var async_hooks = __webpack_require__("async_hooks"), + React = __webpack_require__("./node_modules/react/react.react-server.js"), + assign = Object.assign, + CLIENT_REFERENCE_TAG$1 = Symbol.for("react.client.reference"), + SERVER_REFERENCE_TAG = Symbol.for("react.server.reference"), + FunctionBind = Function.prototype.bind, + ArraySlice = Array.prototype.slice; +function bind() { + var newFn = FunctionBind.apply(this, arguments); + if (this.$$typeof === SERVER_REFERENCE_TAG) { + var args = ArraySlice.call(arguments, 1), + $$typeof = { value: SERVER_REFERENCE_TAG }, + $$id = { value: this.$$id }; + args = { value: this.$$bound ? this.$$bound.concat(args) : args }; + return Object.defineProperties(newFn, { + $$typeof: $$typeof, + $$id: $$id, + $$bound: args, + bind: { value: bind, configurable: !0 } + }); + } + return newFn; +} +var serverReferenceToString = { + value: function () { + return "function () { [omitted code] }"; + }, + configurable: !0, + writable: !0 +}; +function createClientManifest( + clientManifest, + moduleLoading, + cssLinkPrecedence +) { + return { + clientManifest: clientManifest, + moduleLoading: moduleLoading, + cssLinkPrecedence: cssLinkPrecedence + }; +} +var currentStrategy = { + encrypt: function (_actionId) { + for ( + var _len = arguments.length, + args = Array(1 < _len ? _len - 1 : 0), + _key = 1; + _key < _len; + _key++ + ) + args[_key - 1] = arguments[_key]; + return Promise.resolve(args); + }, + decrypt: function (_actionId, payloadPromise) { + return payloadPromise; + } +}; +function noop() {} +var REACT_LEGACY_ELEMENT_TYPE = Symbol.for("react.element"), + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_MEMO_CACHE_SENTINEL = Symbol.for("react.memo_cache_sentinel"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; +} +var ASYNC_ITERATOR = Symbol.asyncIterator, + REACT_OPTIMISTIC_KEY = Symbol.for("react.optimistic_key"), + scheduleMicrotask = queueMicrotask, + currentView = null, + writtenBytes = 0, + destinationHasCapacity = !0; +function writeChunk(destination, chunk) { + if ("string" === typeof chunk) { + if (0 !== chunk.length) + if (4096 < 3 * chunk.length) + 0 < writtenBytes && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + writeToDestination(destination, chunk); + else { + var target = currentView; + 0 < writtenBytes && (target = currentView.subarray(writtenBytes)); + target = textEncoder.encodeInto(chunk, target); + var read = target.read; + writtenBytes += target.written; + read < chunk.length && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = textEncoder.encodeInto( + chunk.slice(read), + currentView + ).written)); + 4096 === writtenBytes && + (writeToDestination(destination, currentView), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)); + } + } else + 0 !== chunk.byteLength && + (4096 < chunk.byteLength + ? (0 < writtenBytes && + (writeToDestination( + destination, + currentView.subarray(0, writtenBytes) + ), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + writeToDestination(destination, chunk)) + : ((target = currentView.length - writtenBytes), + target < chunk.byteLength && + (0 === target + ? writeToDestination(destination, currentView) + : (currentView.set(chunk.subarray(0, target), writtenBytes), + (writtenBytes += target), + writeToDestination(destination, currentView), + (chunk = chunk.subarray(target))), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)), + currentView.set(chunk, writtenBytes), + (writtenBytes += chunk.byteLength), + 4096 === writtenBytes && + (writeToDestination(destination, currentView), + (currentView = new Uint8Array(4096)), + (writtenBytes = 0)))); +} +function writeToDestination(destination, view) { + destination = destination.write(view); + destinationHasCapacity = destinationHasCapacity && destination; +} +function writeChunkAndReturn(destination, chunk) { + writeChunk(destination, chunk); + return destinationHasCapacity; +} +var textEncoder = new util.TextEncoder(); +function byteLengthOfChunk(chunk) { + return "string" === typeof chunk + ? Buffer.byteLength(chunk, "utf8") + : chunk.byteLength; +} +var ReactDOMSharedInternals = + ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + previousDispatcher = ReactDOMSharedInternals.d; +ReactDOMSharedInternals.d = { + f: previousDispatcher.f, + r: previousDispatcher.r, + D: prefetchDNS, + C: preconnect, + L: preload, + m: preloadModule$1, + X: preinitScript, + S: preinitStyle, + M: preinitModuleScript +}; +function prefetchDNS(href) { + if ("string" === typeof href && href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "D|" + href; + hints.has(key) || (hints.add(key), emitHint(request, "D", href)); + } else previousDispatcher.D(href); + } +} +function preconnect(href, crossOrigin) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "C|" + (null == crossOrigin ? "null" : crossOrigin) + "|" + href; + hints.has(key) || + (hints.add(key), + "string" === typeof crossOrigin + ? emitHint(request, "C", [href, crossOrigin]) + : emitHint(request, "C", href)); + } else previousDispatcher.C(href, crossOrigin); + } +} +function preload(href, as, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "L"; + if ("image" === as && options) { + var imageSrcSet = options.imageSrcSet, + imageSizes = options.imageSizes, + uniquePart = ""; + "string" === typeof imageSrcSet && "" !== imageSrcSet + ? ((uniquePart += "[" + imageSrcSet + "]"), + "string" === typeof imageSizes && + (uniquePart += "[" + imageSizes + "]")) + : (uniquePart += "[][]" + href); + key += "[image]" + uniquePart; + } else key += "[" + as + "]" + href; + hints.has(key) || + (hints.add(key), + (options = trimOptions(options)) + ? emitHint(request, "L", [href, as, options]) + : emitHint(request, "L", [href, as])); + } else previousDispatcher.L(href, as, options); + } +} +function preloadModule$1(href, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "m|" + href; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "m", [href, options]) + : emitHint(request, "m", href); + } + previousDispatcher.m(href, options); + } +} +function preinitStyle(href, precedence, options) { + if ("string" === typeof href) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "S|" + href; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "S", [ + href, + "string" === typeof precedence ? precedence : 0, + options + ]) + : "string" === typeof precedence + ? emitHint(request, "S", [href, precedence]) + : emitHint(request, "S", href); + } + previousDispatcher.S(href, precedence, options); + } +} +function preinitScript(src, options) { + if ("string" === typeof src) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "X|" + src; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "X", [src, options]) + : emitHint(request, "X", src); + } + previousDispatcher.X(src, options); + } +} +function preinitModuleScript(src, options) { + if ("string" === typeof src) { + var request = resolveRequest(); + if (request) { + var hints = request.hints, + key = "M|" + src; + if (hints.has(key)) return; + hints.add(key); + return (options = trimOptions(options)) + ? emitHint(request, "M", [src, options]) + : emitHint(request, "M", src); + } + previousDispatcher.M(src, options); + } +} +function trimOptions(options) { + if (null == options) return null; + var hasProperties = !1, + trimmed = {}, + key; + for (key in options) + null != options[key] && + ((hasProperties = !0), (trimmed[key] = options[key])); + return hasProperties ? trimmed : null; +} +function getChildFormatContext(parentContext, type, props) { + switch (type) { + case "img": + type = props.src; + var srcSet = props.srcSet; + if ( + !( + "lazy" === props.loading || + (!type && !srcSet) || + ("string" !== typeof type && null != type) || + ("string" !== typeof srcSet && null != srcSet) || + "low" === props.fetchPriority || + parentContext & 3 + ) && + ("string" !== typeof type || + ":" !== type[4] || + ("d" !== type[0] && "D" !== type[0]) || + ("a" !== type[1] && "A" !== type[1]) || + ("t" !== type[2] && "T" !== type[2]) || + ("a" !== type[3] && "A" !== type[3])) && + ("string" !== typeof srcSet || + ":" !== srcSet[4] || + ("d" !== srcSet[0] && "D" !== srcSet[0]) || + ("a" !== srcSet[1] && "A" !== srcSet[1]) || + ("t" !== srcSet[2] && "T" !== srcSet[2]) || + ("a" !== srcSet[3] && "A" !== srcSet[3])) + ) { + var sizes = "string" === typeof props.sizes ? props.sizes : void 0; + var input = props.crossOrigin; + preload(type || "", "image", { + imageSrcSet: srcSet, + imageSizes: sizes, + crossOrigin: + "string" === typeof input + ? "use-credentials" === input + ? input + : "" + : void 0, + integrity: props.integrity, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy + }); + } + return parentContext; + case "link": + type = props.rel; + srcSet = props.href; + if ( + !( + parentContext & 1 || + null != props.itemProp || + "string" !== typeof type || + "string" !== typeof srcSet || + "" === srcSet + ) + ) + switch (type) { + case "preload": + preload(srcSet, props.as, { + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy, + imageSrcSet: props.imageSrcSet, + imageSizes: props.imageSizes, + media: props.media + }); + break; + case "modulepreload": + preloadModule$1(srcSet, { + as: props.as, + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce + }); + break; + case "stylesheet": + preload(srcSet, "style", { + crossOrigin: props.crossOrigin, + integrity: props.integrity, + nonce: props.nonce, + type: props.type, + fetchPriority: props.fetchPriority, + referrerPolicy: props.referrerPolicy, + media: props.media + }); + } + return parentContext; + case "picture": + return parentContext | 2; + case "noscript": + return parentContext | 1; + default: + return parentContext; + } +} +var requestStorage = new async_hooks.AsyncLocalStorage(), + TEMPORARY_REFERENCE_TAG = Symbol.for("react.temporary.reference"), + proxyHandlers = { + get: function (target, name, receiver) { + switch (name) { + case "$$typeof": + return target.$$typeof; + case "name": + return; + case "displayName": + return; + case "defaultProps": + return; + case "_debugInfo": + return; + case "toJSON": + return; + case Symbol.toPrimitive: + return Object.prototype[Symbol.toPrimitive]; + case Symbol.toStringTag: + return Object.prototype[Symbol.toStringTag]; + case "Provider": + return receiver; + case "then": + return; + } + throw Error( + "Cannot access " + + String(name) + + " on the server. You cannot dot into a temporary client reference from a server component. You can only pass the value through to the client." + ); + }, + set: function () { + throw Error( + "Cannot assign to a temporary client reference from a server module." + ); + } + }; +function createTemporaryReference(temporaryReferences, id) { + var reference = Object.defineProperties( + function () { + throw Error( + "Attempted to call a temporary Client Reference from the server but it is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component." + ); + }, + { $$typeof: { value: TEMPORARY_REFERENCE_TAG } } + ); + reference = new Proxy(reference, proxyHandlers); + temporaryReferences.set(reference, id); + return reference; +} +var SuspenseException = Error( + "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`." +); +function trackUsedThenable(thenableState, thenable, index) { + index = thenableState[index]; + void 0 === index + ? thenableState.push(thenable) + : index !== thenable && (thenable.then(noop, noop), (thenable = index)); + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + thenableState = thenable.reason; + if (void 0 === thenableState && !("reason" in thenable)) + throw Error( + "A rejected Promise was passed to React without a `reason` property. React threw a generic error from where the Promise was used to assist in identifying the problematic Promise. Make sure that instrumented Promises correctly set the `reason` property when setting `status` to `'rejected'`." + ); + throw thenableState; + default: + "string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenableState = thenable), + (thenableState.status = "pending"), + thenableState.then( + function (fulfilledValue) { + if ("pending" === thenable.status) { + var fulfilledThenable = thenable; + fulfilledThenable.status = "fulfilled"; + fulfilledThenable.value = fulfilledValue; + } + }, + function (error) { + if ("pending" === thenable.status) { + var rejectedThenable = thenable; + rejectedThenable.status = "rejected"; + rejectedThenable.reason = error; + } + } + )); + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + suspendedThenable = thenable; + throw SuspenseException; + } +} +var suspendedThenable = null; +function getSuspendedThenable() { + if (null === suspendedThenable) + throw Error( + "Expected a suspended thenable. This is a bug in React. Please file an issue." + ); + var thenable = suspendedThenable; + suspendedThenable = null; + return thenable; +} +var currentRequest$1 = null, + thenableIndexCounter = 0, + thenableState = null; +function getThenableStateAfterSuspending() { + var state = thenableState || []; + thenableState = null; + return state; +} +var HooksDispatcher = { + readContext: unsupportedContext, + use: use, + useCallback: function (callback) { + return callback; + }, + useContext: unsupportedContext, + useEffect: unsupportedHook, + useImperativeHandle: unsupportedHook, + useLayoutEffect: unsupportedHook, + useInsertionEffect: unsupportedHook, + useMemo: function (nextCreate) { + return nextCreate(); + }, + useReducer: unsupportedHook, + useRef: unsupportedHook, + useState: unsupportedHook, + useDebugValue: function () {}, + useDeferredValue: unsupportedHook, + useTransition: unsupportedHook, + useSyncExternalStore: unsupportedHook, + useId: useId, + useHostTransitionStatus: unsupportedHook, + useFormState: unsupportedHook, + useActionState: unsupportedHook, + useOptimistic: unsupportedHook, + useMemoCache: function (size) { + for (var data = Array(size), i = 0; i < size; i++) + data[i] = REACT_MEMO_CACHE_SENTINEL; + return data; + }, + useCacheRefresh: function () { + return unsupportedRefresh; + }, + useEffectEvent: unsupportedHook +}; +function unsupportedHook() { + throw Error("This Hook is not supported in Server Components."); +} +function unsupportedRefresh() { + throw Error("Refreshing the cache is not supported in Server Components."); +} +function unsupportedContext() { + throw Error("Cannot read a Client Context from a Server Component."); +} +function useId() { + if (null === currentRequest$1) + throw Error("useId can only be used while React is rendering"); + var id = currentRequest$1.identifierCount++; + return "_" + currentRequest$1.identifierPrefix + "S_" + id.toString(32) + "_"; +} +function use(usable) { + if ( + (null !== usable && "object" === typeof usable) || + "function" === typeof usable + ) { + if ("function" === typeof usable.then) { + var index = thenableIndexCounter; + thenableIndexCounter += 1; + null === thenableState && (thenableState = []); + return trackUsedThenable(thenableState, usable, index); + } + usable.$$typeof === REACT_CONTEXT_TYPE && unsupportedContext(); + } + if (usable.$$typeof === CLIENT_REFERENCE_TAG$1) { + if (null != usable.value && usable.value.$$typeof === REACT_CONTEXT_TYPE) + throw Error("Cannot read a Client Context from a Server Component."); + throw Error("Cannot use() an already resolved Client Reference."); + } + throw Error("An unsupported type was passed to use(): " + String(usable)); +} +var DefaultAsyncDispatcher = { + getCacheForType: function (resourceType) { + var JSCompiler_inline_result = (JSCompiler_inline_result = + resolveRequest()) + ? JSCompiler_inline_result.cache + : new Map(); + var entry = JSCompiler_inline_result.get(resourceType); + void 0 === entry && + ((entry = resourceType()), + JSCompiler_inline_result.set(resourceType, entry)); + return entry; + }, + cacheSignal: function () { + var request = resolveRequest(); + return request ? request.cacheController.signal : null; + } + }, + ReactSharedInternalsServer = + React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; +if (!ReactSharedInternalsServer) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); +var isArrayImpl = Array.isArray, + getPrototypeOf = Object.getPrototypeOf; +function objectName(object) { + object = Object.prototype.toString.call(object); + return object.slice(8, object.length - 1); +} +function describeValueForErrorMessage(value) { + switch (typeof value) { + case "string": + return JSON.stringify( + 10 >= value.length ? value : value.slice(0, 10) + "..." + ); + case "object": + if (isArrayImpl(value)) return "[...]"; + if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG) + return "client"; + value = objectName(value); + return "Object" === value ? "{...}" : value; + case "function": + return value.$$typeof === CLIENT_REFERENCE_TAG + ? "client" + : (value = value.displayName || value.name) + ? "function " + value + : "function"; + default: + return String(value); + } +} +function describeElementType(type) { + if ("string" === typeof type) return type; + switch (type) { + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + case REACT_MEMO_TYPE: + return describeElementType(type.type); + case REACT_LAZY_TYPE: + var payload = type._payload; + type = type._init; + try { + return describeElementType(type(payload)); + } catch (x) {} + } + return ""; +} +var CLIENT_REFERENCE_TAG = Symbol.for("react.client.reference"); +function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + if ("Object" !== objKind && "Array" !== objKind) return objKind; + objKind = -1; + var length = 0; + if (isArrayImpl(objectOrArray)) { + var str = "["; + for (var i = 0; i < objectOrArray.length; i++) { + 0 < i && (str += ", "); + var value = objectOrArray[i]; + value = + "object" === typeof value && null !== value + ? describeObjectForErrorMessage(value) + : describeValueForErrorMessage(value); + "" + i === expandedName + ? ((objKind = str.length), (length = value.length), (str += value)) + : (str = + 10 > value.length && 40 > str.length + value.length + ? str + value + : str + "..."); + } + str += "]"; + } else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) + str = "<" + describeElementType(objectOrArray.type) + "/>"; + else { + if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client"; + str = "{"; + i = Object.keys(objectOrArray); + for (value = 0; value < i.length; value++) { + 0 < value && (str += ", "); + var name = i[value], + encodedKey = JSON.stringify(name); + str += ('"' + name + '"' === encodedKey ? name : encodedKey) + ": "; + encodedKey = objectOrArray[name]; + encodedKey = + "object" === typeof encodedKey && null !== encodedKey + ? describeObjectForErrorMessage(encodedKey) + : describeValueForErrorMessage(encodedKey); + name === expandedName + ? ((objKind = str.length), + (length = encodedKey.length), + (str += encodedKey)) + : (str = + 10 > encodedKey.length && 40 > str.length + encodedKey.length + ? str + encodedKey + : str + "..."); + } + str += "}"; + } + return void 0 === expandedName + ? str + : -1 < objKind && 0 < length + ? ((objectOrArray = " ".repeat(objKind) + "^".repeat(length)), + "\n " + str + "\n " + objectOrArray) + : "\n " + str; +} +var hasOwnProperty = Object.prototype.hasOwnProperty, + ObjectPrototype$1 = Object.prototype, + stringify = JSON.stringify, + NEXT_TWO_CHUNKS_ARE_ATOMIC = Symbol(); +function defaultErrorHandler(error) { + console.error(error); +} +function RequestInstance( + type, + model, + bundlerConfig, + onError, + onAllReady, + onFatalError, + identifierPrefix, + temporaryReferences +) { + if ( + null !== ReactSharedInternalsServer.A && + ReactSharedInternalsServer.A !== DefaultAsyncDispatcher + ) + throw Error("Currently React only supports one RSC renderer at a time."); + ReactSharedInternalsServer.A = DefaultAsyncDispatcher; + var abortSet = new Set(), + pingedTasks = [], + hints = new Set(); + this.type = type; + this.status = 10; + this.flushScheduled = !1; + this.destination = this.fatalError = null; + this.bundlerConfig = bundlerConfig; + this.cache = new Map(); + this.cacheController = new AbortController(); + this.pendingChunks = this.nextChunkId = 0; + this.hints = hints; + this.abortableTasks = abortSet; + this.pingedTasks = pingedTasks; + this.completedImportChunks = []; + this.completedHintChunks = []; + this.completedRegularChunks = []; + this.completedErrorChunks = []; + this.writtenSymbols = new Map(); + this.writtenClientReferences = new Map(); + this.writtenServerReferences = new Map(); + this.writtenObjects = new WeakMap(); + this.temporaryReferences = temporaryReferences; + this.identifierPrefix = identifierPrefix || ""; + this.identifierCount = 1; + this.taintCleanupQueue = []; + this.onError = void 0 === onError ? defaultErrorHandler : onError; + this.onAllReady = onAllReady; + this.onFatalError = onFatalError; + type = createTask(this, model, null, !1, 0, abortSet); + pingedTasks.push(type); +} +function createRequest( + model, + bundlerConfig, + onError, + identifierPrefix, + temporaryReferences +) { + return new RequestInstance( + 20, + model, + bundlerConfig, + onError, + noop, + noop, + identifierPrefix, + temporaryReferences + ); +} +function createPrerenderRequest( + model, + bundlerConfig, + onAllReady, + onFatalError, + onError, + identifierPrefix, + temporaryReferences +) { + return new RequestInstance( + 21, + model, + bundlerConfig, + onError, + onAllReady, + onFatalError, + identifierPrefix, + temporaryReferences + ); +} +var currentRequest = null; +function resolveRequest() { + if (currentRequest) return currentRequest; + var store = requestStorage.getStore(); + return store ? store : null; +} +function serializeThenable(request, task, thenable) { + switch (thenable.status) { + case "fulfilled": + return ( + (task = createTask( + request, + thenable, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + )), + (task.model = thenable.value), + pingTask(request, task), + task.id + ); + case "rejected": + return ( + (task = createTask( + request, + thenable, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + )), + erroredTask(request, task, thenable.reason), + task.id + ); + default: + var newTask$12 = createTask( + request, + thenable, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + ); + if (12 === request.status) + return ( + request.abortableTasks.delete(newTask$12), + 21 === request.type + ? (haltTask(newTask$12), finishHaltedTask(newTask$12, request)) + : ((task = request.fatalError), + abortTask(newTask$12), + finishAbortedTask(newTask$12, request, task)), + newTask$12.id + ); + "string" !== typeof thenable.status && + ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + )); + thenable.then( + function (value) { + newTask$12.model = value; + pingTask(request, newTask$12); + }, + function (reason) { + 0 === newTask$12.status && + (erroredTask(request, newTask$12, reason), enqueueFlush(request)); + } + ); + return newTask$12.id; + } +} +function serializeReadableStream(request, task, stream) { + function progress(entry) { + if (0 === streamTask.status) + if (entry.done) + (streamTask.status = 1), + (entry = streamTask.id.toString(16) + ":C\n"), + request.completedRegularChunks.push(entry), + request.abortableTasks.delete(streamTask), + request.cacheController.signal.removeEventListener( + "abort", + abortStream + ), + enqueueFlush(request), + callOnAllReadyIfReady(request); + else + try { + request.pendingChunks++, + (streamTask.model = entry.value), + isByteStream + ? emitTypedArrayChunk( + request, + streamTask.id, + "b", + streamTask.model, + !1 + ) + : tryStreamTask(request, streamTask), + enqueueFlush(request), + reader.read().then(progress, error); + } catch (x$13) { + error(x$13); + } + } + function error(reason) { + 0 === streamTask.status && + (request.cacheController.signal.removeEventListener("abort", abortStream), + erroredTask(request, streamTask, reason), + enqueueFlush(request), + reader.cancel(reason).then(error, error)); + } + function abortStream() { + if (0 === streamTask.status) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortStream); + signal = signal.reason; + 21 === request.type + ? (request.abortableTasks.delete(streamTask), + haltTask(streamTask), + finishHaltedTask(streamTask, request)) + : (erroredTask(request, streamTask, signal), enqueueFlush(request)); + reader.cancel(signal).then(error, error); + } + } + var supportsBYOB = stream.supportsBYOB; + if (void 0 === supportsBYOB) + try { + stream.getReader({ mode: "byob" }).releaseLock(), (supportsBYOB = !0); + } catch (x) { + supportsBYOB = !1; + } + var isByteStream = supportsBYOB, + reader = stream.getReader(), + streamTask = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + ); + request.pendingChunks++; + task = streamTask.id.toString(16) + ":" + (isByteStream ? "r" : "R") + "\n"; + request.completedRegularChunks.push(task); + request.cacheController.signal.addEventListener("abort", abortStream); + reader.read().then(progress, error); + return serializeByValueID(streamTask.id); +} +function serializeAsyncIterable(request, task, iterable, iterator) { + function progress(entry) { + if (0 === streamTask.status) + if (entry.done) { + streamTask.status = 1; + if (void 0 === entry.value) + var endStreamRow = streamTask.id.toString(16) + ":C\n"; + else + try { + var chunkId = outlineModelWithFormatContext( + request, + entry.value, + 0 + ); + endStreamRow = + streamTask.id.toString(16) + + ":C" + + stringify(serializeByValueID(chunkId)) + + "\n"; + } catch (x) { + error(x); + return; + } + request.completedRegularChunks.push(endStreamRow); + request.abortableTasks.delete(streamTask); + request.cacheController.signal.removeEventListener( + "abort", + abortIterable + ); + enqueueFlush(request); + callOnAllReadyIfReady(request); + } else + try { + (streamTask.model = entry.value), + request.pendingChunks++, + tryStreamTask(request, streamTask), + enqueueFlush(request), + iterator.next().then(progress, error); + } catch (x$14) { + error(x$14); + } + } + function error(reason) { + 0 === streamTask.status && + (request.cacheController.signal.removeEventListener( + "abort", + abortIterable + ), + erroredTask(request, streamTask, reason), + enqueueFlush(request), + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop)); + } + function abortIterable() { + if (0 === streamTask.status) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortIterable); + var reason = signal.reason; + 21 === request.type + ? (request.abortableTasks.delete(streamTask), + haltTask(streamTask), + finishHaltedTask(streamTask, request)) + : (erroredTask(request, streamTask, signal.reason), + enqueueFlush(request)); + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop); + } + } + iterable = iterable === iterator; + var streamTask = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + ); + request.pendingChunks++; + task = streamTask.id.toString(16) + ":" + (iterable ? "x" : "X") + "\n"; + request.completedRegularChunks.push(task); + request.cacheController.signal.addEventListener("abort", abortIterable); + iterator.next().then(progress, error); + return serializeByValueID(streamTask.id); +} +function emitHint(request, code, model) { + model = stringify(model); + request.completedHintChunks.push(":H" + code + model + "\n"); + enqueueFlush(request); +} +function readThenable(thenable) { + if ("fulfilled" === thenable.status) return thenable.value; + if ("rejected" === thenable.status) throw thenable.reason; + throw thenable; +} +function createLazyWrapperAroundWakeable(request, task, wakeable) { + switch (wakeable.status) { + case "fulfilled": + return wakeable.value; + case "rejected": + break; + default: + "string" !== typeof wakeable.status && + ((wakeable.status = "pending"), + wakeable.then( + function (fulfilledValue) { + "pending" === wakeable.status && + ((wakeable.status = "fulfilled"), + (wakeable.value = fulfilledValue)); + }, + function (error) { + "pending" === wakeable.status && + ((wakeable.status = "rejected"), (wakeable.reason = error)); + } + )); + } + return { $$typeof: REACT_LAZY_TYPE, _payload: wakeable, _init: readThenable }; +} +function voidHandler() {} +function processServerComponentReturnValue(request, task, Component, result) { + if ( + "object" !== typeof result || + null === result || + result.$$typeof === CLIENT_REFERENCE_TAG$1 + ) + return result; + if ("function" === typeof result.then) + return createLazyWrapperAroundWakeable(request, task, result); + var iteratorFn = getIteratorFn(result); + return iteratorFn + ? ((request = {}), + (request[Symbol.iterator] = function () { + return iteratorFn.call(result); + }), + request) + : "function" !== typeof result[ASYNC_ITERATOR] || + ("function" === typeof ReadableStream && + result instanceof ReadableStream) + ? result + : ((request = {}), + (request[ASYNC_ITERATOR] = function () { + return result[ASYNC_ITERATOR](); + }), + request); +} +function renderFunctionComponent(request, task, key, Component, props) { + var prevThenableState = task.thenableState; + task.thenableState = null; + thenableIndexCounter = 0; + thenableState = prevThenableState; + props = Component(props, void 0); + if (12 === request.status) + throw ( + ("object" === typeof props && + null !== props && + "function" === typeof props.then && + props.$$typeof !== CLIENT_REFERENCE_TAG$1 && + props.then(voidHandler, voidHandler), + null) + ); + props = processServerComponentReturnValue(request, task, Component, props); + Component = task.keyPath; + prevThenableState = task.implicitSlot; + null !== key + ? (task.keyPath = + key === REACT_OPTIMISTIC_KEY || Component === REACT_OPTIMISTIC_KEY + ? REACT_OPTIMISTIC_KEY + : null === Component + ? key + : Component + "," + key) + : null === Component && (task.implicitSlot = !0); + request = renderModelDestructive(request, task, emptyRoot, "", props); + task.keyPath = Component; + task.implicitSlot = prevThenableState; + return request; +} +function renderFragment(request, task, children) { + return null !== task.keyPath + ? ((request = [ + REACT_ELEMENT_TYPE, + REACT_FRAGMENT_TYPE, + task.keyPath, + { children: children } + ]), + task.implicitSlot ? [request] : request) + : children; +} +var serializedSize = 0; +function deferTask(request, task) { + task = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + ); + pingTask(request, task); + return serializeLazyID(task.id); +} +function renderElement(request, task, type, key, ref, props) { + if (null !== ref && void 0 !== ref) + throw Error( + "Refs cannot be used in Server Components, nor passed to Client Components." + ); + if ( + "function" === typeof type && + type.$$typeof !== CLIENT_REFERENCE_TAG$1 && + type.$$typeof !== TEMPORARY_REFERENCE_TAG + ) + return renderFunctionComponent(request, task, key, type, props); + if (type === REACT_FRAGMENT_TYPE && null === key) + return ( + (type = task.implicitSlot), + null === task.keyPath && (task.implicitSlot = !0), + (props = renderModelDestructive( + request, + task, + emptyRoot, + "", + props.children + )), + (task.implicitSlot = type), + props + ); + if ( + null != type && + "object" === typeof type && + type.$$typeof !== CLIENT_REFERENCE_TAG$1 + ) + switch (type.$$typeof) { + case REACT_LAZY_TYPE: + var init = type._init; + type = init(type._payload); + if (12 === request.status) throw null; + return renderElement(request, task, type, key, ref, props); + case REACT_FORWARD_REF_TYPE: + return renderFunctionComponent(request, task, key, type.render, props); + case REACT_MEMO_TYPE: + return renderElement(request, task, type.type, key, ref, props); + } + else + "string" === typeof type && + ((ref = task.formatContext), + (init = getChildFormatContext(ref, type, props)), + ref !== init && + null != props.children && + outlineModelWithFormatContext(request, props.children, init)); + request = key; + key = task.keyPath; + null === request + ? (request = key) + : null !== key && + (request = + key === REACT_OPTIMISTIC_KEY || request === REACT_OPTIMISTIC_KEY + ? REACT_OPTIMISTIC_KEY + : key + "," + request); + props = [REACT_ELEMENT_TYPE, type, request, props]; + task = task.implicitSlot && null !== request ? [props] : props; + return task; +} +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + 1 === pingedTasks.length && + ((request.flushScheduled = null !== request.destination), + 21 === request.type || 10 === request.status + ? scheduleMicrotask(function () { + return performWork(request); + }) + : setImmediate(function () { + return performWork(request); + })); +} +function createTask( + request, + model, + keyPath, + implicitSlot, + formatContext, + abortSet +) { + return createTaskWithID( + request, + request.nextChunkId++, + model, + keyPath, + implicitSlot, + formatContext, + abortSet + ); +} +function createTaskWithID( + request, + id, + model, + keyPath, + implicitSlot, + formatContext, + abortSet +) { + request.pendingChunks++; + "object" !== typeof model || + null === model || + null !== keyPath || + implicitSlot || + request.writtenObjects.set(model, serializeByValueID(id)); + var task = { + id: id, + status: 0, + model: model, + keyPath: keyPath, + implicitSlot: implicitSlot, + formatContext: formatContext, + ping: function () { + return pingTask(request, task); + }, + thenableState: null + }; + abortSet.add(task); + return task; +} +function resolveModel(request, task, parent, parentPropertyName, value) { + var jsonValue = value; + null !== value && + "object" === typeof value && + "function" === typeof value.toJSON && + (jsonValue = value.toJSON(parentPropertyName)); + serializedSize += parentPropertyName.length; + value = task.keyPath; + var prevImplicitSlot = task.implicitSlot; + try { + var JSCompiler_inline_result = renderModelDestructive( + request, + task, + parent, + parentPropertyName, + jsonValue + ); + } catch (thrownValue) { + (parent = task.model), + (parent = + "object" === typeof parent && + null !== parent && + (parent.$$typeof === REACT_ELEMENT_TYPE || + parent.$$typeof === REACT_LAZY_TYPE)), + 12 === request.status + ? ((task.status = 3), + 21 === request.type + ? ((value = request.nextChunkId++), + (value = parent + ? serializeLazyID(value) + : serializeByValueID(value)), + (JSCompiler_inline_result = value)) + : ((value = request.fatalError), + (JSCompiler_inline_result = parent + ? serializeLazyID(value) + : serializeByValueID(value)))) + : ((parentPropertyName = + thrownValue === SuspenseException + ? getSuspendedThenable() + : thrownValue), + "object" === typeof parentPropertyName && + null !== parentPropertyName && + "function" === typeof parentPropertyName.then + ? ((jsonValue = createTask( + request, + task.model, + task.keyPath, + task.implicitSlot, + task.formatContext, + request.abortableTasks + )), + (JSCompiler_inline_result = jsonValue.ping), + parentPropertyName.then( + JSCompiler_inline_result, + JSCompiler_inline_result + ), + (jsonValue.thenableState = getThenableStateAfterSuspending()), + (task.keyPath = value), + (task.implicitSlot = prevImplicitSlot), + (JSCompiler_inline_result = parent + ? serializeLazyID(jsonValue.id) + : serializeByValueID(jsonValue.id))) + : ((task.keyPath = value), + (task.implicitSlot = prevImplicitSlot), + request.pendingChunks++, + (value = request.nextChunkId++), + (prevImplicitSlot = logRecoverableError( + request, + parentPropertyName, + task + )), + emitErrorChunk(request, value, prevImplicitSlot), + (JSCompiler_inline_result = parent + ? serializeLazyID(value) + : serializeByValueID(value)))); + } + value = JSCompiler_inline_result; + if (null === value || "object" !== typeof value) return value; + if (isArrayImpl(value)) { + var resolved$16 = []; + for ( + prevImplicitSlot = 0; + prevImplicitSlot < value.length; + prevImplicitSlot++ + ) + resolved$16[prevImplicitSlot] = resolveModel( + request, + task, + value, + "" + prevImplicitSlot, + value[prevImplicitSlot] + ); + return resolved$16; + } + prevImplicitSlot = {}; + for (resolved$16 in value) + hasOwnProperty.call(value, resolved$16) && + ((parent = resolveModel( + request, + task, + value, + resolved$16, + value[resolved$16] + )), + "__proto__" === resolved$16 + ? Object.defineProperty(prevImplicitSlot, resolved$16, { + value: parent, + enumerable: !0, + writable: !0, + configurable: !0 + }) + : (prevImplicitSlot[resolved$16] = parent)); + return prevImplicitSlot; +} +function serializeByValueID(id) { + return "$" + id.toString(16); +} +function serializeLazyID(id) { + return "$L" + id.toString(16); +} +function encodeReferenceChunk(request, id, reference) { + request = stringify(reference); + return id.toString(16) + ":" + request + "\n"; +} +function serializeClientReference( + request, + parent, + parentPropertyName, + clientReference +) { + var clientReferenceKey = clientReference.$$async + ? clientReference.$$id + "#async" + : clientReference.$$id, + writtenClientReferences = request.writtenClientReferences, + existingId = writtenClientReferences.get(clientReferenceKey); + if (void 0 !== existingId) + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(existingId) + : serializeByValueID(existingId); + try { + var config = request.bundlerConfig, + modulePath = clientReference.$$id, + clientManifest = config.clientManifest, + exportSeparatorIndex = modulePath.lastIndexOf("#"), + clientReferenceId = + -1 === exportSeparatorIndex + ? modulePath + : modulePath.slice(0, exportSeparatorIndex); + existingId = ""; + var resolvedModuleData = clientManifest[modulePath]; + if (resolvedModuleData) existingId = resolvedModuleData.name; + else if ( + (-1 !== exportSeparatorIndex && + ((existingId = modulePath.slice(exportSeparatorIndex + 1)), + (resolvedModuleData = clientManifest[clientReferenceId])), + !resolvedModuleData) + ) + throw Error( + 'Could not find the module "' + + modulePath + + '" in the React Client Manifest. This is probably a bug in the React Server Components bundler.' + ); + var cssFiles = resolvedModuleData.cssFiles || [], + configuredPrecedence = config.cssLinkPrecedence; + config = + void 0 === configuredPrecedence + ? "rspack-rsc/client-reference" + : !1 === configuredPrecedence + ? void 0 + : configuredPrecedence; + for (clientManifest = 0; clientManifest < cssFiles.length; clientManifest++) + ReactDOM.preinit(cssFiles[clientManifest], { + as: "style", + precedence: config + }); + if (!0 === resolvedModuleData.async && !0 === clientReference.$$async) + throw Error( + 'The module "' + + modulePath + + '" is marked as an async ESM module but was loaded as a CJS proxy. This is probably a bug in the React Server Components bundler.' + ); + var JSCompiler_inline_result = + !0 === resolvedModuleData.async || !0 === clientReference.$$async + ? [resolvedModuleData.id, resolvedModuleData.chunks, existingId, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, existingId]; + request.pendingChunks++; + var importId = request.nextChunkId++, + json = stringify(JSCompiler_inline_result), + processedChunk = importId.toString(16) + ":I" + json + "\n"; + request.completedImportChunks.push(processedChunk); + writtenClientReferences.set(clientReferenceKey, importId); + return parent[0] === REACT_ELEMENT_TYPE && "1" === parentPropertyName + ? serializeLazyID(importId) + : serializeByValueID(importId); + } catch (x) { + return ( + request.pendingChunks++, + (parent = request.nextChunkId++), + (parentPropertyName = logRecoverableError(request, x, null)), + emitErrorChunk(request, parent, parentPropertyName), + serializeByValueID(parent) + ); + } +} +function outlineModelWithFormatContext(request, value, formatContext) { + value = createTask( + request, + value, + null, + !1, + formatContext, + request.abortableTasks + ); + retryTask(request, value); + return value.id; +} +function serializeTypedArray(request, tag, typedArray) { + request.pendingChunks++; + var bufferId = request.nextChunkId++; + emitTypedArrayChunk(request, bufferId, tag, typedArray, !1); + return serializeByValueID(bufferId); +} +function serializeBlob(request, blob) { + function progress(entry) { + if (0 === newTask.status) + if (entry.done) + request.cacheController.signal.removeEventListener("abort", abortBlob), + pingTask(request, newTask); + else + return ( + model.push(entry.value), reader.read().then(progress).catch(error) + ); + } + function error(reason) { + 0 === newTask.status && + (request.cacheController.signal.removeEventListener("abort", abortBlob), + erroredTask(request, newTask, reason), + enqueueFlush(request), + reader.cancel(reason).then(error, error)); + } + function abortBlob() { + if (0 === newTask.status) { + var signal = request.cacheController.signal; + signal.removeEventListener("abort", abortBlob); + signal = signal.reason; + 21 === request.type + ? (request.abortableTasks.delete(newTask), + haltTask(newTask), + finishHaltedTask(newTask, request)) + : (erroredTask(request, newTask, signal), enqueueFlush(request)); + reader.cancel(signal).then(error, error); + } + } + var model = [blob.type], + newTask = createTask(request, model, null, !1, 0, request.abortableTasks), + reader = blob.stream().getReader(); + request.cacheController.signal.addEventListener("abort", abortBlob); + reader.read().then(progress).catch(error); + return "$B" + newTask.id.toString(16); +} +var modelRoot = !1; +function renderModelDestructive( + request, + task, + parent, + parentPropertyName, + value +) { + task.model = value; + if (value === REACT_ELEMENT_TYPE) return "$"; + if (null === value) return null; + if ("object" === typeof value) { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + var elementReference = null, + writtenObjects = request.writtenObjects; + if (null === task.keyPath && !task.implicitSlot) { + var existingReference = writtenObjects.get(value); + if (void 0 !== existingReference) + if (modelRoot === value) modelRoot = null; + else return existingReference; + else + -1 === parentPropertyName.indexOf(":") && + ((parent = writtenObjects.get(parent)), + void 0 !== parent && + ((elementReference = parent + ":" + parentPropertyName), + writtenObjects.set(value, elementReference))); + } + if (3200 < serializedSize) return deferTask(request, task); + parentPropertyName = value.props; + parent = parentPropertyName.ref; + request = renderElement( + request, + task, + value.type, + value.key, + void 0 !== parent ? parent : null, + parentPropertyName + ); + "object" === typeof request && + null !== request && + null !== elementReference && + (writtenObjects.has(request) || + writtenObjects.set(request, elementReference)); + return request; + case REACT_LAZY_TYPE: + if (3200 < serializedSize) return deferTask(request, task); + task.thenableState = null; + elementReference = value._init; + value = elementReference(value._payload); + if (12 === request.status) throw null; + return renderModelDestructive( + request, + task, + parent, + parentPropertyName, + value + ); + case REACT_LEGACY_ELEMENT_TYPE: + throw Error( + 'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.' + ); + } + if (value.$$typeof === CLIENT_REFERENCE_TAG$1) + return serializeClientReference( + request, + parent, + parentPropertyName, + value + ); + if ( + void 0 !== request.temporaryReferences && + ((elementReference = request.temporaryReferences.get(value)), + void 0 !== elementReference) + ) + return "$T" + elementReference; + elementReference = request.writtenObjects; + writtenObjects = elementReference.get(value); + if ("function" === typeof value.then) { + if (void 0 !== writtenObjects) { + if (null !== task.keyPath || task.implicitSlot) + return "$@" + serializeThenable(request, task, value).toString(16); + if (modelRoot === value) modelRoot = null; + else return writtenObjects; + } + request = "$@" + serializeThenable(request, task, value).toString(16); + elementReference.set(value, request); + return request; + } + if (void 0 !== writtenObjects) + if (modelRoot === value) { + if (writtenObjects !== serializeByValueID(task.id)) + return writtenObjects; + modelRoot = null; + } else return writtenObjects; + else if ( + -1 === parentPropertyName.indexOf(":") && + ((writtenObjects = elementReference.get(parent)), + void 0 !== writtenObjects) + ) { + existingReference = parentPropertyName; + if (isArrayImpl(parent) && parent[0] === REACT_ELEMENT_TYPE) + switch (parentPropertyName) { + case "1": + existingReference = "type"; + break; + case "2": + existingReference = "key"; + break; + case "3": + existingReference = "props"; + break; + case "4": + existingReference = "_owner"; + } + elementReference.set(value, writtenObjects + ":" + existingReference); + } + if (isArrayImpl(value)) return renderFragment(request, task, value); + if (value instanceof Map) + return ( + (value = Array.from(value)), + "$Q" + outlineModelWithFormatContext(request, value, 0).toString(16) + ); + if (value instanceof Set) + return ( + (value = Array.from(value)), + "$W" + outlineModelWithFormatContext(request, value, 0).toString(16) + ); + if ("function" === typeof FormData && value instanceof FormData) + return ( + (value = Array.from(value.entries())), + "$K" + outlineModelWithFormatContext(request, value, 0).toString(16) + ); + if (value instanceof Error) return "$Z"; + if (value instanceof ArrayBuffer) + return serializeTypedArray(request, "A", new Uint8Array(value)); + if (value instanceof Int8Array) + return serializeTypedArray(request, "O", value); + if (value instanceof Uint8Array) + return serializeTypedArray(request, "o", value); + if (value instanceof Uint8ClampedArray) + return serializeTypedArray(request, "U", value); + if (value instanceof Int16Array) + return serializeTypedArray(request, "S", value); + if (value instanceof Uint16Array) + return serializeTypedArray(request, "s", value); + if (value instanceof Int32Array) + return serializeTypedArray(request, "L", value); + if (value instanceof Uint32Array) + return serializeTypedArray(request, "l", value); + if (value instanceof Float32Array) + return serializeTypedArray(request, "G", value); + if (value instanceof Float64Array) + return serializeTypedArray(request, "g", value); + if (value instanceof BigInt64Array) + return serializeTypedArray(request, "M", value); + if (value instanceof BigUint64Array) + return serializeTypedArray(request, "m", value); + if (value instanceof DataView) + return serializeTypedArray(request, "V", value); + if ("function" === typeof Blob && value instanceof Blob) + return serializeBlob(request, value); + if ((elementReference = getIteratorFn(value))) + return ( + (parentPropertyName = elementReference.call(value)), + parentPropertyName === value + ? ((value = Array.from(parentPropertyName)), + "$i" + + outlineModelWithFormatContext(request, value, 0).toString(16)) + : renderFragment(request, task, Array.from(parentPropertyName)) + ); + if ("function" === typeof ReadableStream && value instanceof ReadableStream) + return serializeReadableStream(request, task, value); + elementReference = value[ASYNC_ITERATOR]; + if ("function" === typeof elementReference) + return ( + null !== task.keyPath + ? ((request = [ + REACT_ELEMENT_TYPE, + REACT_FRAGMENT_TYPE, + task.keyPath, + { children: value } + ]), + (request = task.implicitSlot ? [request] : request)) + : ((parentPropertyName = elementReference.call(value)), + (request = serializeAsyncIterable( + request, + task, + value, + parentPropertyName + ))), + request + ); + if (value instanceof Date) return "$D" + value.toJSON(); + request = getPrototypeOf(value); + if ( + request !== ObjectPrototype$1 && + (null === request || null !== getPrototypeOf(request)) + ) + throw Error( + "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + return value; + } + if ("string" === typeof value) { + serializedSize += value.length; + if ( + "Z" === value[value.length - 1] && + parent[parentPropertyName] instanceof Date + ) + return "$D" + value; + if (1024 <= value.length && null !== byteLengthOfChunk) + return ( + request.pendingChunks++, + (task = request.nextChunkId++), + emitTextChunk(request, task, value, !1), + serializeByValueID(task) + ); + request = "$" === value[0] ? "$" + value : value; + return request; + } + if ("boolean" === typeof value) return value; + if ("number" === typeof value) + return Number.isFinite(value) + ? 0 === value && -Infinity === 1 / value + ? "$-0" + : value + : Infinity === value + ? "$Infinity" + : -Infinity === value + ? "$-Infinity" + : "$NaN"; + if ("undefined" === typeof value) return "$undefined"; + if ("function" === typeof value) { + if (value.$$typeof === CLIENT_REFERENCE_TAG$1) + return serializeClientReference( + request, + parent, + parentPropertyName, + value + ); + if (value.$$typeof === SERVER_REFERENCE_TAG) + return ( + (task = request.writtenServerReferences), + (parentPropertyName = task.get(value)), + void 0 !== parentPropertyName + ? (request = "$h" + parentPropertyName.toString(16)) + : ((parentPropertyName = value.$$bound), + (parentPropertyName = + null === parentPropertyName + ? null + : Promise.resolve(parentPropertyName)), + (request = outlineModelWithFormatContext( + request, + { id: value.$$id, bound: parentPropertyName }, + 0 + )), + task.set(value, request), + (request = "$h" + request.toString(16))), + request + ); + if ( + void 0 !== request.temporaryReferences && + ((request = request.temporaryReferences.get(value)), void 0 !== request) + ) + return "$T" + request; + if (value.$$typeof === TEMPORARY_REFERENCE_TAG) + throw Error( + "Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server." + ); + if (/^on[A-Z]/.test(parentPropertyName)) + throw Error( + "Event handlers cannot be passed to Client Component props." + + describeObjectForErrorMessage(parent, parentPropertyName) + + "\nIf you need interactivity, consider converting part of this to a Client Component." + ); + throw Error( + 'Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.' + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + } + if ("symbol" === typeof value) { + task = request.writtenSymbols; + elementReference = task.get(value); + if (void 0 !== elementReference) + return serializeByValueID(elementReference); + elementReference = value.description; + if (Symbol.for(elementReference) !== value) + throw Error( + "Only global symbols received from Symbol.for(...) can be passed to Client Components. The symbol Symbol.for(" + + (value.description + ") cannot be found among global symbols.") + + describeObjectForErrorMessage(parent, parentPropertyName) + ); + request.pendingChunks++; + parentPropertyName = request.nextChunkId++; + parent = encodeReferenceChunk( + request, + parentPropertyName, + "$S" + elementReference + ); + request.completedImportChunks.push(parent); + task.set(value, parentPropertyName); + return serializeByValueID(parentPropertyName); + } + if ("bigint" === typeof value) return "$n" + value.toString(10); + throw Error( + "Type " + + typeof value + + " is not supported in Client Component props." + + describeObjectForErrorMessage(parent, parentPropertyName) + ); +} +function logRecoverableError(request, error) { + var prevRequest = currentRequest; + currentRequest = null; + try { + var errorDigest = requestStorage.run(void 0, request.onError, error); + } finally { + currentRequest = prevRequest; + } + if (null != errorDigest && "string" !== typeof errorDigest) + throw Error( + 'onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + + typeof errorDigest + + '" instead' + ); + return errorDigest || ""; +} +function fatalError(request, error) { + var onFatalError = request.onFatalError; + onFatalError(error); + null !== request.destination + ? ((request.status = 14), request.destination.destroy(error)) + : ((request.status = 13), (request.fatalError = error)); + request.cacheController.abort( + Error("The render was aborted due to a fatal error.", { cause: error }) + ); +} +function emitErrorChunk(request, id, digest) { + digest = { digest: digest }; + id = id.toString(16) + ":E" + stringify(digest) + "\n"; + request.completedErrorChunks.push(id); +} +function emitTypedArrayChunk(request, id, tag, typedArray, debug) { + debug ? request.pendingDebugChunks++ : request.pendingChunks++; + typedArray = new Uint8Array( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength + ); + debug = typedArray.byteLength; + id = id.toString(16) + ":" + tag + debug.toString(16) + ","; + request.completedRegularChunks.push( + NEXT_TWO_CHUNKS_ARE_ATOMIC, + id, + typedArray + ); +} +function emitTextChunk(request, id, text, debug) { + if (null === byteLengthOfChunk) + throw Error( + "Existence of byteLengthOfChunk should have already been checked. This is a bug in React." + ); + debug ? request.pendingDebugChunks++ : request.pendingChunks++; + debug = byteLengthOfChunk(text); + id = id.toString(16) + ":T" + debug.toString(16) + ","; + request.completedRegularChunks.push(NEXT_TWO_CHUNKS_ARE_ATOMIC, id, text); +} +function emitChunk(request, task, value) { + var id = task.id; + "string" === typeof value && null !== byteLengthOfChunk + ? emitTextChunk(request, id, value, !1) + : value instanceof ArrayBuffer + ? emitTypedArrayChunk(request, id, "A", new Uint8Array(value), !1) + : value instanceof Int8Array + ? emitTypedArrayChunk(request, id, "O", value, !1) + : value instanceof Uint8Array + ? emitTypedArrayChunk(request, id, "o", value, !1) + : value instanceof Uint8ClampedArray + ? emitTypedArrayChunk(request, id, "U", value, !1) + : value instanceof Int16Array + ? emitTypedArrayChunk(request, id, "S", value, !1) + : value instanceof Uint16Array + ? emitTypedArrayChunk(request, id, "s", value, !1) + : value instanceof Int32Array + ? emitTypedArrayChunk(request, id, "L", value, !1) + : value instanceof Uint32Array + ? emitTypedArrayChunk(request, id, "l", value, !1) + : value instanceof Float32Array + ? emitTypedArrayChunk(request, id, "G", value, !1) + : value instanceof Float64Array + ? emitTypedArrayChunk(request, id, "g", value, !1) + : value instanceof BigInt64Array + ? emitTypedArrayChunk(request, id, "M", value, !1) + : value instanceof BigUint64Array + ? emitTypedArrayChunk(request, id, "m", value, !1) + : value instanceof DataView + ? emitTypedArrayChunk(request, id, "V", value, !1) + : ((value = resolveModel( + request, + task, + { "": value }, + "", + value + )), + (value = stringify(value)), + (task = + task.id.toString(16) + ":" + value + "\n"), + request.completedRegularChunks.push(task)); +} +function erroredTask(request, task, error) { + task.status = 4; + error = logRecoverableError(request, error, task); + emitErrorChunk(request, task.id, error); + request.abortableTasks.delete(task); + callOnAllReadyIfReady(request); +} +var emptyRoot = {}; +function retryTask(request, task) { + if (0 === task.status) { + task.status = 5; + var parentSerializedSize = serializedSize; + try { + modelRoot = task.model; + var resolvedModel = renderModelDestructive( + request, + task, + emptyRoot, + "", + task.model + ); + modelRoot = resolvedModel; + task.keyPath = null; + task.implicitSlot = !1; + if ("object" === typeof resolvedModel && null !== resolvedModel) + request.writtenObjects.set(resolvedModel, serializeByValueID(task.id)), + emitChunk(request, task, resolvedModel); + else { + var json = stringify(resolvedModel), + processedChunk = task.id.toString(16) + ":" + json + "\n"; + request.completedRegularChunks.push(processedChunk); + } + task.status = 1; + request.abortableTasks.delete(task); + callOnAllReadyIfReady(request); + } catch (thrownValue) { + if (12 === request.status) + if ( + (request.abortableTasks.delete(task), + (task.status = 0), + 21 === request.type) + ) + haltTask(task), finishHaltedTask(task, request); + else { + var errorId = request.fatalError; + abortTask(task); + finishAbortedTask(task, request, errorId); + } + else { + var x = + thrownValue === SuspenseException + ? getSuspendedThenable() + : thrownValue; + if ( + "object" === typeof x && + null !== x && + "function" === typeof x.then + ) { + task.status = 0; + task.thenableState = getThenableStateAfterSuspending(); + var ping = task.ping; + x.then(ping, ping); + } else erroredTask(request, task, x); + } + } finally { + serializedSize = parentSerializedSize; + } + } +} +function tryStreamTask(request, task) { + var parentSerializedSize = serializedSize; + try { + emitChunk(request, task, task.model); + } finally { + serializedSize = parentSerializedSize; + } +} +function performWork(request) { + var prevDispatcher = ReactSharedInternalsServer.H; + ReactSharedInternalsServer.H = HooksDispatcher; + var prevRequest = currentRequest; + currentRequest$1 = currentRequest = request; + try { + var pingedTasks = request.pingedTasks; + request.pingedTasks = []; + for (var i = 0; i < pingedTasks.length; i++) + retryTask(request, pingedTasks[i]); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } finally { + (ReactSharedInternalsServer.H = prevDispatcher), + (currentRequest$1 = null), + (currentRequest = prevRequest); + } +} +function abortTask(task) { + 0 === task.status && (task.status = 3); +} +function finishAbortedTask(task, request, errorId) { + 3 === task.status && + ((errorId = serializeByValueID(errorId)), + (task = encodeReferenceChunk(request, task.id, errorId)), + request.completedErrorChunks.push(task)); +} +function haltTask(task) { + 0 === task.status && (task.status = 3); +} +function finishHaltedTask(task, request) { + 3 === task.status && request.pendingChunks--; +} +function flushCompletedChunks(request) { + var destination = request.destination; + if (null !== destination) { + currentView = new Uint8Array(4096); + writtenBytes = 0; + destinationHasCapacity = !0; + try { + for ( + var importsChunks = request.completedImportChunks, i = 0; + i < importsChunks.length; + i++ + ) + if ( + (request.pendingChunks--, + !writeChunkAndReturn(destination, importsChunks[i])) + ) { + request.destination = null; + i++; + break; + } + importsChunks.splice(0, i); + var hintChunks = request.completedHintChunks; + for (i = 0; i < hintChunks.length; i++) + if (!writeChunkAndReturn(destination, hintChunks[i])) { + request.destination = null; + i++; + break; + } + hintChunks.splice(0, i); + var regularChunks = request.completedRegularChunks; + for (i = 0; i < regularChunks.length; i++) { + var item = regularChunks[i]; + importsChunks = void 0; + if (item === NEXT_TWO_CHUNKS_ARE_ATOMIC) { + if (i + 2 >= regularChunks.length) + throw Error("A chunk pair is incomplete. This is a bug in React."); + request.pendingChunks -= 2; + writeChunk(destination, regularChunks[i + 1]); + importsChunks = writeChunkAndReturn( + destination, + regularChunks[i + 2] + ); + i += 2; + } else + request.pendingChunks--, + (importsChunks = writeChunkAndReturn(destination, item)); + if (!importsChunks) { + request.destination = null; + i++; + break; + } + } + regularChunks.splice(0, i); + var errorChunks = request.completedErrorChunks; + for (i = 0; i < errorChunks.length; i++) + if ( + (request.pendingChunks--, + !writeChunkAndReturn(destination, errorChunks[i])) + ) { + request.destination = null; + i++; + break; + } + errorChunks.splice(0, i); + } finally { + (request.flushScheduled = !1), + currentView && + 0 < writtenBytes && + destination.write(currentView.subarray(0, writtenBytes)), + (currentView = null), + (writtenBytes = 0), + (destinationHasCapacity = !0); + } + "function" === typeof destination.flush && destination.flush(); + } + 0 === request.pendingChunks && + (12 > request.status && + request.cacheController.abort( + Error( + "This render completed successfully. All cacheSignals are now aborted to allow clean up of any unused resources." + ) + ), + null !== request.destination && + ((request.status = 14), + request.destination.end(), + (request.destination = null))); +} +function startWork(request) { + request.flushScheduled = null !== request.destination; + scheduleMicrotask(function () { + requestStorage.run(request, performWork, request); + }); + setImmediate(function () { + 10 === request.status && (request.status = 11); + }); +} +function enqueueFlush(request) { + !1 === request.flushScheduled && + 0 === request.pingedTasks.length && + null !== request.destination && + ((request.flushScheduled = !0), + setImmediate(function () { + request.flushScheduled = !1; + flushCompletedChunks(request); + })); +} +function callOnAllReadyIfReady(request) { + 0 === request.abortableTasks.size && + ((request = request.onAllReady), request()); +} +function startFlowing(request, destination) { + if (13 === request.status) + (request.status = 14), destination.destroy(request.fatalError); + else if (14 !== request.status && null === request.destination) { + request.destination = destination; + try { + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } + } +} +function finishHalt(request, abortedTasks) { + try { + abortedTasks.forEach(function (task) { + return finishHaltedTask(task, request); + }); + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } +} +function finishAbort(request, abortedTasks, errorId) { + try { + abortedTasks.forEach(function (task) { + return finishAbortedTask(task, request, errorId); + }); + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } catch (error) { + logRecoverableError(request, error, null), fatalError(request, error); + } +} +function abort(request, reason) { + if (!(11 < request.status)) + try { + request.status = 12; + request.cacheController.abort(reason); + var abortableTasks = request.abortableTasks; + if (0 < abortableTasks.size) + if (21 === request.type) + abortableTasks.forEach(function (task) { + return haltTask(task, request); + }), + setImmediate(function () { + return finishHalt(request, abortableTasks); + }); + else { + var error = + void 0 === reason + ? Error( + "The render was aborted by the server without a reason." + ) + : "object" === typeof reason && + null !== reason && + "function" === typeof reason.then + ? Error( + "The render was aborted by the server with a promise." + ) + : reason, + digest = logRecoverableError(request, error, null), + errorId = request.nextChunkId++; + request.fatalError = errorId; + request.pendingChunks++; + emitErrorChunk(request, errorId, digest, error, !1, null); + abortableTasks.forEach(function (task) { + return abortTask(task, request, errorId); + }); + setImmediate(function () { + return finishAbort(request, abortableTasks, errorId); + }); + } + else { + var onAllReady = request.onAllReady; + onAllReady(); + flushCompletedChunks(request); + } + } catch (error$28) { + logRecoverableError(request, error$28, null), + fatalError(request, error$28); + } +} +function resolveServerReference(bundlerConfig, id) { + var name = "", + resolvedModuleData = bundlerConfig[id]; + if (resolvedModuleData) name = resolvedModuleData.name; + else { + var idx = id.lastIndexOf("#"); + -1 !== idx && + ((name = id.slice(idx + 1)), + (resolvedModuleData = bundlerConfig[id.slice(0, idx)])); + if (!resolvedModuleData) + throw Error( + 'Could not find the module "' + + id + + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.' + ); + } + return resolvedModuleData.async + ? [resolvedModuleData.id, resolvedModuleData.chunks, name, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, name]; +} +var chunkCache = new Map(); +function requireAsyncModule(id) { + var promise = __webpack_require__(id); + if ("function" !== typeof promise.then || "fulfilled" === promise.status) + return null; + promise.then( + function (value) { + promise.status = "fulfilled"; + promise.value = value; + }, + function (reason) { + promise.status = "rejected"; + promise.reason = reason; + } + ); + return promise; +} +function ignoreReject() {} +function preloadModule(metadata) { + for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) { + var chunkId = chunks[i++]; + chunks[i++]; + var entry = chunkCache.get(chunkId); + if (void 0 === entry) { + entry = __webpack_require__.e(chunkId); + promises.push(entry); + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + entry.then(resolve, ignoreReject); + chunkCache.set(chunkId, entry); + } else null !== entry && promises.push(entry); + } + return 4 === metadata.length + ? 0 === promises.length + ? requireAsyncModule(metadata[0]) + : Promise.all(promises).then(function () { + return requireAsyncModule(metadata[0]); + }) + : 0 < promises.length + ? Promise.all(promises) + : null; +} +function requireModule(metadata) { + var moduleExports = __webpack_require__(metadata[0]); + if (4 === metadata.length && "function" === typeof moduleExports.then) + if ("fulfilled" === moduleExports.status) + moduleExports = moduleExports.value; + else throw moduleExports.reason; + if ("*" === metadata[2]) return moduleExports; + if ("" === metadata[2]) + return moduleExports.__esModule ? moduleExports.default : moduleExports; + if (hasOwnProperty.call(moduleExports, metadata[2])) + return moduleExports[metadata[2]]; +} +function appendBackingEntry(backingStore, key, value) { + backingStore.data.append(key, value); + value = backingStore.keys; + null === value + ? ((backingStore.keys = Array.from(backingStore.data.keys())), + (backingStore.keyPointer = 0)) + : value.push(key); +} +var RESPONSE_SYMBOL = Symbol(); +function ReactPromise(status, value, reason) { + this.status = status; + this.value = value; + this.reason = reason; +} +ReactPromise.prototype = Object.create(Promise.prototype); +Object.defineProperty(ReactPromise.prototype, "then", { + writable: !0, + enumerable: !0, + configurable: !0, + value: function (resolve, reject) { + switch (this.status) { + case "resolved_model": + initializeModelChunk(this); + } + switch (this.status) { + case "fulfilled": + if ("function" === typeof resolve) { + for ( + var inspectedValue = this.value, + cycleProtection = 0, + visited = new Set(); + inspectedValue instanceof ReactPromise; + + ) { + cycleProtection++; + if ( + inspectedValue === this || + visited.has(inspectedValue) || + 1e3 < cycleProtection + ) { + "function" === typeof reject && + reject(Error("Cannot have cyclic thenables.")); + return; + } + visited.add(inspectedValue); + if ("fulfilled" === inspectedValue.status) + inspectedValue = inspectedValue.value; + else break; + } + resolve(this.value); + } + break; + case "pending": + case "blocked": + "function" === typeof resolve && + (null === this.value && (this.value = []), this.value.push(resolve)); + "function" === typeof reject && + (null === this.reason && (this.reason = []), + this.reason.push(reject)); + break; + default: + "function" === typeof reject && reject(this.reason); + } + } +}); +var ObjectPrototype = Object.prototype, + ArrayPrototype = Array.prototype; +function wakeChunk(response, listeners, value, chunk) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk.reason); + } +} +function rejectChunk(response, listeners, error) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(error) + : rejectReference(response, listener.handler, error); + } +} +function triggerErrorOnChunk(response, chunk, error) { + if ("pending" !== chunk.status && "blocked" !== chunk.status) + chunk.reason.error(error); + else { + var listeners = chunk.reason; + chunk.status = "rejected"; + chunk.reason = error; + null !== listeners && rejectChunk(response, listeners, error); + } +} +function createResolvedModelChunk(response, value, id) { + var $jscomp$compprop2 = {}; + return new ReactPromise( + "resolved_model", + value, + (($jscomp$compprop2.id = id), + ($jscomp$compprop2[RESPONSE_SYMBOL] = response), + $jscomp$compprop2) + ); +} +function resolveModelChunk(response, chunk, value, id) { + if ("pending" !== chunk.status) + (chunk = chunk.reason), + "C" === value[0] + ? chunk.close("C" === value ? '"$undefined"' : value.slice(1)) + : chunk.enqueueModel(value); + else { + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_model"; + chunk.value = value; + value = {}; + chunk.reason = + ((value.id = id), (value[RESPONSE_SYMBOL] = response), value); + if (null !== resolveListeners) + switch ((initializeModelChunk(chunk), chunk.status)) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + break; + case "blocked": + case "pending": + if (chunk.value) + for (response = 0; response < resolveListeners.length; response++) + chunk.value.push(resolveListeners[response]); + else chunk.value = resolveListeners; + if (chunk.reason) { + if (rejectListeners) + for ( + resolveListeners = 0; + resolveListeners < rejectListeners.length; + resolveListeners++ + ) + chunk.reason.push(rejectListeners[resolveListeners]); + } else chunk.reason = rejectListeners; + break; + case "rejected": + rejectListeners && + rejectChunk(response, rejectListeners, chunk.reason); + } + } +} +function createResolvedIteratorResultChunk(response, value, done) { + var $jscomp$compprop4 = {}; + return new ReactPromise( + "resolved_model", + (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", + (($jscomp$compprop4.id = -1), + ($jscomp$compprop4[RESPONSE_SYMBOL] = response), + $jscomp$compprop4) + ); +} +function resolveIteratorResultChunk(response, chunk, value, done) { + resolveModelChunk( + response, + chunk, + (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", + -1 + ); +} +function loadServerReference$1(response, metaData, parentObject, key) { + function reject(error) { + var rejectListeners = blockedPromise.reason, + erroredPromise = blockedPromise; + erroredPromise.status = "rejected"; + erroredPromise.value = null; + erroredPromise.reason = error; + null !== rejectListeners && rejectChunk(response, rejectListeners, error); + rejectReference(response, handler, error); + } + var id = metaData.id; + if ("string" !== typeof id || "then" === key) return null; + var cachedPromise = metaData.$$promise; + if (void 0 !== cachedPromise) { + if ("fulfilled" === cachedPromise.status) + return ( + (cachedPromise = cachedPromise.value), + "__proto__" === key ? null : (parentObject[key] = cachedPromise) + ); + initializingHandler + ? ((id = initializingHandler), id.deps++) + : (id = initializingHandler = + { chunk: null, value: null, reason: null, deps: 1, errored: !1 }); + cachedPromise.then( + resolveReference.bind(null, response, id, parentObject, key), + rejectReference.bind(null, response, id) + ); + return null; + } + var blockedPromise = new ReactPromise("blocked", null, null); + metaData.$$promise = blockedPromise; + var serverReference = resolveServerReference(response._bundlerConfig, id); + cachedPromise = metaData.bound; + if ((id = preloadModule(serverReference))) + cachedPromise instanceof ReactPromise && + (id = Promise.all([id, cachedPromise])); + else if (cachedPromise instanceof ReactPromise) + id = Promise.resolve(cachedPromise); + else + return ( + (cachedPromise = requireModule(serverReference)), + (id = blockedPromise), + (id.status = "fulfilled"), + (id.value = cachedPromise), + (id.reason = null), + cachedPromise + ); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + id.then(function () { + var resolvedValue = requireModule(serverReference); + if (metaData.bound) { + var promiseValue = metaData.bound.value; + promiseValue = isArrayImpl(promiseValue) ? promiseValue.slice(0) : []; + if (1e3 < promiseValue.length) { + reject( + Error( + "Server Function has too many bound arguments. Received " + + promiseValue.length + + " but the limit is 1000." + ) + ); + return; + } + promiseValue.unshift(null); + resolvedValue = resolvedValue.bind.apply(resolvedValue, promiseValue); + } + promiseValue = blockedPromise.value; + var initializedPromise = blockedPromise; + initializedPromise.status = "fulfilled"; + initializedPromise.value = resolvedValue; + initializedPromise.reason = null; + null !== promiseValue && + wakeChunk(response, promiseValue, resolvedValue, initializedPromise); + resolveReference(response, handler, parentObject, key, resolvedValue); + }, reject); + return null; +} +function reviveModel( + response, + parentObj, + parentKey, + value, + reference, + arrayRoot +) { + if ("string" === typeof value) + return parseModelString( + response, + parentObj, + parentKey, + value, + reference, + arrayRoot + ); + if ("object" === typeof value && null !== value) + if ( + (void 0 !== reference && + void 0 !== response._temporaryReferences && + response._temporaryReferences.set(value, reference), + isArrayImpl(value)) + ) { + if (null === arrayRoot) { + var childContext = { count: 0, fork: !1 }; + response._rootArrayContexts.set(value, childContext); + } else childContext = arrayRoot; + 1 < value.length && (childContext.fork = !0); + bumpArrayCount(childContext, value.length + 1, response); + for (parentObj = 0; parentObj < value.length; parentObj++) + value[parentObj] = reviveModel( + response, + value, + "" + parentObj, + value[parentObj], + void 0 !== reference ? reference + ":" + parentObj : void 0, + childContext + ); + } else + for (childContext in value) + hasOwnProperty.call(value, childContext) && + ("__proto__" === childContext + ? delete value[childContext] + : ((parentObj = + void 0 !== reference && -1 === childContext.indexOf(":") + ? reference + ":" + childContext + : void 0), + (parentObj = reviveModel( + response, + value, + childContext, + value[childContext], + parentObj, + null + )), + void 0 !== parentObj + ? (value[childContext] = parentObj) + : delete value[childContext])); + return value; +} +function bumpArrayCount(arrayContext, slots, response) { + if ( + (arrayContext.count += slots) > response._arraySizeLimit && + arrayContext.fork + ) + throw Error( + "Maximum array nesting exceeded. Large nested arrays can be dangerous. Try adding intermediate objects." + ); +} +var initializingHandler = null; +function initializeModelChunk(chunk) { + var prevHandler = initializingHandler; + initializingHandler = null; + var _chunk$reason = chunk.reason, + response = _chunk$reason[RESPONSE_SYMBOL]; + _chunk$reason = _chunk$reason.id; + _chunk$reason = -1 === _chunk$reason ? void 0 : _chunk$reason.toString(16); + var resolvedModel = chunk.value; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + try { + var rawModel = JSON.parse(resolvedModel); + resolvedModel = { count: 0, fork: !1 }; + var value = reviveModel( + response, + { "": rawModel }, + "", + rawModel, + _chunk$reason, + resolvedModel + ), + resolveListeners = chunk.value; + if (null !== resolveListeners) + for ( + chunk.value = null, chunk.reason = null, rawModel = 0; + rawModel < resolveListeners.length; + rawModel++ + ) { + var listener = resolveListeners[rawModel]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, resolvedModel); + } + if (null !== initializingHandler) { + if (initializingHandler.errored) throw initializingHandler.reason; + if (0 < initializingHandler.deps) { + initializingHandler.value = value; + initializingHandler.reason = resolvedModel; + initializingHandler.chunk = chunk; + return; + } + } + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = resolvedModel; + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } finally { + initializingHandler = prevHandler; + } +} +function reportGlobalError(response, error) { + response._closed = !0; + response._closedReason = error; + response._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? triggerErrorOnChunk(response, chunk, error) + : "fulfilled" === chunk.status && + null !== chunk.reason && + ((chunk = chunk.reason), + "function" === typeof chunk.error && chunk.error(error)); + }); +} +function getChunk(response, id) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk || + ((chunk = response._formData.data.get(response._prefix + id)), + (chunk = + "string" === typeof chunk + ? createResolvedModelChunk(response, chunk, id) + : response._closed + ? new ReactPromise("rejected", null, response._closedReason) + : new ReactPromise("pending", null, null)), + chunks.set(id, chunk)); + return chunk; +} +function fulfillReference(response, reference, value, arrayRoot) { + var handler = reference.handler, + parentObject = reference.parentObject, + key = reference.key, + map = reference.map, + path = reference.path; + try { + for ( + var localLength = 0, + rootArrayContexts = response._rootArrayContexts, + i = 1; + i < path.length; + i++ + ) { + var name = path[i]; + if ( + "object" !== typeof value || + null === value || + (getPrototypeOf(value) !== ObjectPrototype && + getPrototypeOf(value) !== ArrayPrototype) || + !hasOwnProperty.call(value, name) + ) + throw Error("Invalid reference."); + value = value[name]; + if (isArrayImpl(value)) + (localLength = 0), + (arrayRoot = rootArrayContexts.get(value) || arrayRoot); + else if (((arrayRoot = null), "string" === typeof value)) + localLength = value.length; + else if ("bigint" === typeof value) { + var n = Math.abs(Number(value)); + localLength = 0 === n ? 1 : Math.floor(Math.log10(n)) + 1; + } else localLength = ArrayBuffer.isView(value) ? value.byteLength : 0; + } + var resolvedValue = map(response, value, parentObject, key); + var referenceArrayRoot = reference.arrayRoot; + null !== referenceArrayRoot && + (null !== arrayRoot + ? (arrayRoot.fork && (referenceArrayRoot.fork = !0), + bumpArrayCount(referenceArrayRoot, arrayRoot.count, response)) + : 0 < localLength && + bumpArrayCount(referenceArrayRoot, localLength, response)); + } catch (error) { + rejectReference(response, handler, error); + return; + } + resolveReference(response, handler, parentObject, key, resolvedValue); +} +function resolveReference(response, handler, parentObject, key, resolvedValue) { + "__proto__" !== key && (parentObject[key] = resolvedValue); + "" === key && null === handler.value && (handler.value = resolvedValue); + handler.deps--; + 0 === handler.deps && + ((parentObject = handler.chunk), + null !== parentObject && + "blocked" === parentObject.status && + ((key = parentObject.value), + (parentObject.status = "fulfilled"), + (parentObject.value = handler.value), + (parentObject.reason = handler.reason), + null !== key && wakeChunk(response, key, handler.value, parentObject))); +} +function rejectReference(response, handler, error) { + handler.errored || + ((handler.errored = !0), + (handler.value = null), + (handler.reason = error), + (handler = handler.chunk), + null !== handler && + "blocked" === handler.status && + triggerErrorOnChunk(response, handler, error)); +} +function getOutlinedModel( + response, + reference, + parentObject, + key, + referenceArrayRoot, + map +) { + reference = reference.split(":"); + var id = parseInt(reference[0], 16), + chunk = getChunk(response, id); + switch (chunk.status) { + case "resolved_model": + initializeModelChunk(chunk); + } + switch (chunk.status) { + case "fulfilled": + id = chunk.value; + chunk = chunk.reason; + if (null !== chunk && "error" in chunk) + throw Error( + "Expected an initialized chunk but got an initialized stream chunk instead. This payload may have been submitted by an older version of React." + ); + for ( + var localLength = 0, + rootArrayContexts = response._rootArrayContexts, + i = 1; + i < reference.length; + i++ + ) { + localLength = reference[i]; + if ( + "object" !== typeof id || + null === id || + (getPrototypeOf(id) !== ObjectPrototype && + getPrototypeOf(id) !== ArrayPrototype) || + !hasOwnProperty.call(id, localLength) + ) + throw Error("Invalid reference."); + id = id[localLength]; + isArrayImpl(id) + ? ((localLength = 0), (chunk = rootArrayContexts.get(id) || chunk)) + : ((chunk = null), + "string" === typeof id + ? (localLength = id.length) + : "bigint" === typeof id + ? ((localLength = Math.abs(Number(id))), + (localLength = + 0 === localLength + ? 1 + : Math.floor(Math.log10(localLength)) + 1)) + : (localLength = ArrayBuffer.isView(id) ? id.byteLength : 0)); + } + parentObject = map(response, id, parentObject, key); + null !== referenceArrayRoot && + (null !== chunk + ? (chunk.fork && (referenceArrayRoot.fork = !0), + bumpArrayCount(referenceArrayRoot, chunk.count, response)) + : 0 < localLength && + bumpArrayCount(referenceArrayRoot, localLength, response)); + return parentObject; + case "blocked": + return ( + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (response = initializingHandler = + { chunk: null, value: null, reason: null, deps: 1, errored: !1 }), + (referenceArrayRoot = { + handler: response, + parentObject: parentObject, + key: key, + map: map, + path: reference, + arrayRoot: referenceArrayRoot + }), + null === chunk.value + ? (chunk.value = [referenceArrayRoot]) + : chunk.value.push(referenceArrayRoot), + null === chunk.reason + ? (chunk.reason = [referenceArrayRoot]) + : chunk.reason.push(referenceArrayRoot), + null + ); + case "pending": + throw Error("Invalid forward reference."); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = chunk.reason)) + : (initializingHandler = { + chunk: null, + value: null, + reason: chunk.reason, + deps: 0, + errored: !0 + }), + null + ); + } +} +function createMap(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Map initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Map."); + model.$$consumed = !0; + return new Map(model); +} +function createSet(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Set initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Set."); + model.$$consumed = !0; + return new Set(model); +} +function extractIterator(response, model) { + if (!isArrayImpl(model)) throw Error("Invalid Iterator initializer."); + if (!0 === model.$$consumed) throw Error("Already initialized Iterator."); + model.$$consumed = !0; + return model[Symbol.iterator](); +} +function createModel(response, model, parentObject, key) { + return "then" === key && "function" === typeof model ? null : model; +} +function parseTypedArray( + response, + reference, + constructor, + bytesPerElement, + parentObject, + parentKey, + referenceArrayRoot +) { + function reject(error) { + if (!handler.errored) { + handler.errored = !0; + handler.value = null; + handler.reason = error; + var chunk = handler.chunk; + null !== chunk && + "blocked" === chunk.status && + triggerErrorOnChunk(response, chunk, error); + } + } + reference = parseInt(reference.slice(2), 16); + var key = response._prefix + reference; + bytesPerElement = response._chunks; + if (bytesPerElement.has(reference)) + throw Error("Already initialized typed array."); + bytesPerElement.set( + reference, + new ReactPromise( + "rejected", + null, + Error("Already initialized typed array.") + ) + ); + reference = response._formData.data.get(key).arrayBuffer(); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + reference.then(function (buffer) { + try { + null !== referenceArrayRoot && + bumpArrayCount(referenceArrayRoot, buffer.byteLength, response); + var resolvedValue = + constructor === ArrayBuffer ? buffer : new constructor(buffer); + "__proto__" !== key && (parentObject[parentKey] = resolvedValue); + "" === parentKey && + null === handler.value && + (handler.value = resolvedValue); + } catch (x) { + reject(x); + return; + } + handler.deps--; + 0 === handler.deps && + ((buffer = handler.chunk), + null !== buffer && + "blocked" === buffer.status && + ((resolvedValue = buffer.value), + (buffer.status = "fulfilled"), + (buffer.value = handler.value), + (buffer.reason = null), + null !== resolvedValue && + wakeChunk(response, resolvedValue, handler.value, buffer))); + }, reject); + return null; +} +function resolveStream(response, id, stream, controller) { + var chunks = response._chunks; + stream = new ReactPromise("fulfilled", stream, controller); + chunks.set(id, stream); + response = response._formData.data.getAll(response._prefix + id); + for (id = 0; id < response.length; id++) + (chunks = response[id]), + "string" === typeof chunks && + ("C" === chunks[0] + ? controller.close("C" === chunks ? '"$undefined"' : chunks.slice(1)) + : controller.enqueueModel(chunks)); +} +function parseReadableStream(response, reference, type) { + function enqueue(value) { + "bytes" !== type || ArrayBuffer.isView(value) + ? controller.enqueue(value) + : flightController.error(Error("Invalid data for bytes stream.")); + } + reference = parseInt(reference.slice(2), 16); + if (response._chunks.has(reference)) + throw Error("Already initialized stream."); + var controller = null, + closed = !1, + stream = new ReadableStream({ + type: type, + start: function (c) { + controller = c; + } + }), + previousBlockedChunk = null, + flightController = { + enqueueModel: function (json) { + if (null === previousBlockedChunk) { + var chunk = createResolvedModelChunk(response, json, -1); + initializeModelChunk(chunk); + "fulfilled" === chunk.status + ? enqueue(chunk.value) + : (chunk.then(enqueue, flightController.error), + (previousBlockedChunk = chunk)); + } else { + chunk = previousBlockedChunk; + var chunk$33 = new ReactPromise("pending", null, null); + chunk$33.then(enqueue, flightController.error); + previousBlockedChunk = chunk$33; + chunk.then(function () { + previousBlockedChunk === chunk$33 && (previousBlockedChunk = null); + resolveModelChunk(response, chunk$33, json, -1); + }); + } + }, + close: function () { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.close(); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.close(); + }); + } + }, + error: function (error) { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.error(error); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.error(error); + }); + } + } + }; + resolveStream(response, reference, stream, flightController); + return stream; +} +function FlightIterator(next) { + this.next = next; +} +FlightIterator.prototype = {}; +FlightIterator.prototype[ASYNC_ITERATOR] = function () { + return this; +}; +function parseAsyncIterable(response, reference, iterator) { + reference = parseInt(reference.slice(2), 16); + if (response._chunks.has(reference)) + throw Error("Already initialized stream."); + var buffer = [], + closed = !1, + nextWriteIndex = 0, + $jscomp$compprop5 = {}; + $jscomp$compprop5 = + (($jscomp$compprop5[ASYNC_ITERATOR] = function () { + var nextReadIndex = 0; + return new FlightIterator(function (arg) { + if (void 0 !== arg) + throw Error( + "Values cannot be passed to next() of AsyncIterables passed to Client Components." + ); + if (nextReadIndex === buffer.length) { + if (closed) + return new ReactPromise( + "fulfilled", + { done: !0, value: void 0 }, + null + ); + buffer[nextReadIndex] = new ReactPromise("pending", null, null); + } + return buffer[nextReadIndex++]; + }); + }), + $jscomp$compprop5); + iterator = iterator ? $jscomp$compprop5[ASYNC_ITERATOR]() : $jscomp$compprop5; + resolveStream(response, reference, iterator, { + enqueueModel: function (value) { + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !1 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !1 + ); + nextWriteIndex++; + }, + close: function (value) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !0 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !0 + ), + nextWriteIndex++; + nextWriteIndex < buffer.length; + + ) + resolveIteratorResultChunk( + response, + buffer[nextWriteIndex++], + '"$undefined"', + !0 + ); + }, + error: function (error) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length && + (buffer[nextWriteIndex] = new ReactPromise( + "pending", + null, + null + )); + nextWriteIndex < buffer.length; + + ) + triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); + } + }); + return iterator; +} +function parseModelString(response, obj, key, value, reference, arrayRoot) { + if ("$" === value[0]) { + switch (value[1]) { + case "$": + return ( + null !== arrayRoot && + bumpArrayCount(arrayRoot, value.length - 1, response), + value.slice(1) + ); + case "@": + return (obj = parseInt(value.slice(2), 16)), getChunk(response, obj); + case "h": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel( + response, + arrayRoot, + obj, + key, + null, + loadServerReference$1 + ) + ); + case "T": + if (void 0 === reference || void 0 === response._temporaryReferences) + throw Error( + "Could not reference an opaque temporary reference. This is likely due to misconfiguring the temporaryReferences options on the server." + ); + return createTemporaryReference( + response._temporaryReferences, + reference + ); + case "Q": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel(response, arrayRoot, obj, key, null, createMap) + ); + case "W": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel(response, arrayRoot, obj, key, null, createSet) + ); + case "K": + key = value.slice(2); + obj = response._prefix + "_"; + key = obj + key + "_"; + arrayRoot = new FormData(); + for (response = response._formData; ; ) { + value = response.keys; + null === value && + ((value = response.keys = Array.from(response.data.keys())), + (response.keyPointer = 0)); + value = value[response.keyPointer]; + if (void 0 === value) break; + if (value.startsWith(key)) { + reference = response.data.getAll(value); + for ( + var referencedFormDataKey = value.slice(key.length), i = 0; + i < reference.length; + i++ + ) + arrayRoot.append(referencedFormDataKey, reference[i]); + response.data.delete(value); + response.keyPointer++; + } else if (value.startsWith(obj)) break; + else response.keyPointer++; + } + return arrayRoot; + case "i": + return ( + (arrayRoot = value.slice(2)), + getOutlinedModel(response, arrayRoot, obj, key, null, extractIterator) + ); + case "I": + return Infinity; + case "-": + return "$-0" === value ? -0 : -Infinity; + case "N": + return NaN; + case "u": + return; + case "D": + return new Date(Date.parse(value.slice(2))); + case "n": + obj = value.slice(2); + if (300 < obj.length) + throw Error( + "BigInt is too large. Received " + + obj.length + + " digits but the limit is 300." + ); + null !== arrayRoot && bumpArrayCount(arrayRoot, obj.length, response); + return BigInt(obj); + case "A": + return parseTypedArray( + response, + value, + ArrayBuffer, + 1, + obj, + key, + arrayRoot + ); + case "O": + return parseTypedArray( + response, + value, + Int8Array, + 1, + obj, + key, + arrayRoot + ); + case "o": + return parseTypedArray( + response, + value, + Uint8Array, + 1, + obj, + key, + arrayRoot + ); + case "U": + return parseTypedArray( + response, + value, + Uint8ClampedArray, + 1, + obj, + key, + arrayRoot + ); + case "S": + return parseTypedArray( + response, + value, + Int16Array, + 2, + obj, + key, + arrayRoot + ); + case "s": + return parseTypedArray( + response, + value, + Uint16Array, + 2, + obj, + key, + arrayRoot + ); + case "L": + return parseTypedArray( + response, + value, + Int32Array, + 4, + obj, + key, + arrayRoot + ); + case "l": + return parseTypedArray( + response, + value, + Uint32Array, + 4, + obj, + key, + arrayRoot + ); + case "G": + return parseTypedArray( + response, + value, + Float32Array, + 4, + obj, + key, + arrayRoot + ); + case "g": + return parseTypedArray( + response, + value, + Float64Array, + 8, + obj, + key, + arrayRoot + ); + case "M": + return parseTypedArray( + response, + value, + BigInt64Array, + 8, + obj, + key, + arrayRoot + ); + case "m": + return parseTypedArray( + response, + value, + BigUint64Array, + 8, + obj, + key, + arrayRoot + ); + case "V": + return parseTypedArray( + response, + value, + DataView, + 1, + obj, + key, + arrayRoot + ); + case "B": + obj = parseInt(value.slice(2), 16); + response = response._formData.data.get(response._prefix + obj); + if (!(response instanceof Blob)) + throw Error("Referenced Blob is not a Blob."); + return response; + case "R": + return parseReadableStream(response, value, void 0); + case "r": + return parseReadableStream(response, value, "bytes"); + case "X": + return parseAsyncIterable(response, value, !1); + case "x": + return parseAsyncIterable(response, value, !0); + } + value = value.slice(1); + return getOutlinedModel(response, value, obj, key, arrayRoot, createModel); + } + null !== arrayRoot && bumpArrayCount(arrayRoot, value.length, response); + return value; +} +function createResponse(bundlerConfig, formFieldPrefix, temporaryReferences) { + var backingFormData = + 3 < arguments.length && void 0 !== arguments[3] + ? arguments[3] + : new FormData(), + arraySizeLimit = + 4 < arguments.length && void 0 !== arguments[4] ? arguments[4] : 1e6, + chunks = new Map(); + return { + _bundlerConfig: bundlerConfig, + _prefix: formFieldPrefix, + _formData: { data: backingFormData, keyPointer: -1, keys: null }, + _chunks: chunks, + _closed: !1, + _closedReason: null, + _temporaryReferences: temporaryReferences, + _rootArrayContexts: new WeakMap(), + _arraySizeLimit: arraySizeLimit + }; +} +function resolveField(response, key, value) { + appendBackingEntry(response._formData, key, value); + var prefix = response._prefix; + if (key.startsWith(prefix)) { + var chunks = response._chunks; + key = +key.slice(prefix.length); + (chunks = chunks.get(key)) && + resolveModelChunk(response, chunks, value, key); + } +} +function close(response) { + reportGlobalError(response, Error("Connection closed.")); +} +function loadServerReference(bundlerConfig, metaData) { + var id = metaData.id; + if ("string" !== typeof id) return null; + var serverReference = resolveServerReference(bundlerConfig, id); + bundlerConfig = preloadModule(serverReference); + metaData = metaData.bound; + return metaData instanceof Promise + ? Promise.all([metaData, bundlerConfig]).then(function (_ref) { + _ref = _ref[0]; + var fn = requireModule(serverReference); + if (1e3 < _ref.length) + throw Error( + "Server Function has too many bound arguments. Received " + + _ref.length + + " but the limit is 1000." + ); + return fn.bind.apply(fn, [null].concat(_ref)); + }) + : bundlerConfig + ? Promise.resolve(bundlerConfig).then(function () { + return requireModule(serverReference); + }) + : Promise.resolve(requireModule(serverReference)); +} +function decodeBoundActionMetaData( + body, + serverManifest, + formFieldPrefix, + arraySizeLimit +) { + body = createResponse( + serverManifest, + formFieldPrefix, + void 0, + body, + arraySizeLimit + ); + close(body); + body = getChunk(body, 0); + body.then(function () {}); + if ("fulfilled" !== body.status) throw body.reason; + return body.value; +} +function decodeAction$1(body, serverManifest) { + var formData = new FormData(), + maybeActionKey = null; + body.forEach(function (value, key) { + key.startsWith("$ACTION_") + ? key.startsWith("$ACTION_REF_") + ? (maybeActionKey = key) + : key.startsWith("$ACTION_ID_") && (maybeActionKey = key) + : formData.append(key, value); + }); + if (null === maybeActionKey) return null; + var actionKey = maybeActionKey, + action = null; + if (actionKey.startsWith("$ACTION_REF_")) + (actionKey = "$ACTION_" + actionKey.slice(12) + ":"), + (body = decodeBoundActionMetaData(body, serverManifest, actionKey)), + (action = loadServerReference(serverManifest, body)); + else if (actionKey.startsWith("$ACTION_ID_")) + (body = actionKey.slice(11)), + (action = loadServerReference(serverManifest, { id: body, bound: null })); + else throw Error("Cannot handle action key. This is a bug in React."); + return action.then(function (fn) { + return fn.bind(null, formData); + }); +} +function decodeFormState$1(actionResult, body, serverManifest) { + var keyPath = body.get("$ACTION_KEY"); + if ("string" !== typeof keyPath) return Promise.resolve(null); + var actionKey = null; + body.forEach(function (value, key) { + key.startsWith("$ACTION_REF_") && (actionKey = key); + }); + if (null === actionKey) return Promise.resolve(null); + var formFieldPrefix = "$ACTION_" + actionKey.slice(12) + ":"; + body = decodeBoundActionMetaData(body, serverManifest, formFieldPrefix); + var referenceId = body.id; + return Promise.resolve(body.bound).then(function (bound) { + return null === bound + ? null + : [actionResult, keyPath, referenceId, bound.length - 1]; + }); +} +function createDrainHandler(destination, request) { + return function () { + return startFlowing(request, destination); + }; +} +function createCancelHandler(request, reason) { + return function () { + request.destination = null; + abort(request, Error(reason)); + }; +} +function createFakeWritableFromReadableStreamController(controller) { + return { + write: function (chunk) { + "string" === typeof chunk && (chunk = textEncoder.encode(chunk)); + controller.enqueue(chunk); + return !0; + }, + end: function () { + controller.close(); + }, + destroy: function (error) { + "function" === typeof controller.error + ? controller.error(error) + : controller.close(); + } + }; +} +function createFakeWritableFromNodeReadable(readable) { + return { + write: function (chunk) { + return readable.push(chunk); + }, + end: function () { + readable.push(null); + }, + destroy: function (error) { + readable.destroy(error); + } + }; +} +exports.createServerEntry = function (value, resource) { + var entryJsFiles = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.entryJsFiles || [], + entryCssFiles = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.entryCssFiles[resource] || []; + ("function" === typeof value || + ("object" === typeof value && null !== value)) && + assign(value, { + resource: resource, + entryJsFiles: entryJsFiles, + entryCssFiles: entryCssFiles + }); + return value; +}; +exports.createTemporaryReferenceSet = function () { + return new WeakMap(); +}; +exports.decodeAction = function (body) { + return decodeAction$1(body, {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest); +}; +exports.decodeFormState = function (actionResult, body) { + return decodeFormState$1( + actionResult, + body, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest + ); +}; +exports.decodeReply = function (body, options) { + if ("string" === typeof body) { + var form = new FormData(); + form.append("0", body); + body = form; + } + body = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + body, + options ? options.arraySizeLimit : void 0 + ); + options = getChunk(body, 0); + close(body); + return options; +}; +exports.decodeReplyFromAsyncIterable = function (iterable, options) { + function progress(entry) { + if (entry.done) close(response); + else { + var _entry$value = entry.value; + entry = _entry$value[0]; + _entry$value = _entry$value[1]; + "string" === typeof _entry$value + ? resolveField(response, entry, _entry$value) + : appendBackingEntry(response._formData, entry, _entry$value); + iterator.next().then(progress, error); + } + } + function error(reason) { + reportGlobalError(response, reason); + "function" === typeof iterator.throw && + iterator.throw(reason).then(noop, noop); + } + var iterator = iterable[ASYNC_ITERATOR](), + response = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + void 0, + options ? options.arraySizeLimit : void 0 + ); + iterator.next().then(progress, error); + return getChunk(response, 0); +}; +exports.decodeReplyFromBusboy = function (busboyStream, options) { + function flush() { + for (; null !== head; ) { + var current = head; + if (!current.complete) return; + try { + var key = current.name, + handle = current.file, + blob = new Blob(handle.chunks, { type: handle.mime }), + backingStore = response._formData, + key$jscomp$0 = key; + backingStore.data.append(key$jscomp$0, blob, handle.filename); + var keys = backingStore.keys; + null === keys + ? ((backingStore.keys = Array.from(backingStore.data.keys())), + (backingStore.keyPointer = 0)) + : keys.push(key$jscomp$0); + var queuedFields = current.queuedFields; + if (null !== queuedFields) + for ( + key$jscomp$0 = 0; + key$jscomp$0 < queuedFields.length; + key$jscomp$0 += 2 + ) + resolveField( + response, + queuedFields[key$jscomp$0], + queuedFields[key$jscomp$0 + 1] + ); + } catch (error) { + busboyStream.destroy(error); + return; + } + head = current.next; + } + tail = null; + bodyFinished && !closed && ((closed = !0), close(response)); + } + var response = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + "", + options ? options.temporaryReferences : void 0, + void 0, + options ? options.arraySizeLimit : void 0 + ), + head = null, + tail = null, + bodyFinished = !1, + closed = !1; + busboyStream.on("field", function (name, value) { + if (null !== tail) + null === tail.queuedFields && (tail.queuedFields = []), + tail.queuedFields.push(name, value); + else + try { + resolveField(response, name, value); + } catch (error) { + busboyStream.destroy(error); + } + }); + busboyStream.on("file", function (name, value, _ref2) { + var filename = _ref2.filename, + mimeType = _ref2.mimeType; + if ("base64" === _ref2.encoding.toLowerCase()) + busboyStream.destroy( + Error( + "React doesn't accept base64 encoded file uploads because we don't expect form data passed from a browser to ever encode data that way. If that's the wrong assumption, we can easily fix it." + ) + ); + else { + var file = { chunks: [], filename: filename, mime: mimeType }, + pendingFile = { + name: name, + file: file, + complete: !1, + queuedFields: null, + next: null + }; + null === tail ? (head = pendingFile) : (tail.next = pendingFile); + tail = pendingFile; + value.on("data", function (chunk) { + try { + file.chunks.push(chunk); + } catch (error) { + busboyStream.destroy(error); + } + }); + value.on("error", function (error) { + busboyStream.destroy(error); + }); + value.on("end", function () { + pendingFile.complete = !0; + flush(); + }); + } + }); + busboyStream.on("finish", function () { + bodyFinished = !0; + flush(); + closed || + reportGlobalError( + response, + Error("Reply finished with incomplete file part.") + ); + }); + busboyStream.on("error", function (err) { + reportGlobalError(response, err); + }); + return getChunk(response, 0); +}; +exports.decryptServerActionBoundArgs = function (actionId, encryptedPromise) { + return currentStrategy.decrypt(actionId, encryptedPromise); +}; +exports.encryptServerActionBoundArgs = function (actionId) { + for ( + var _currentStrategy, + _len2 = arguments.length, + args = Array(1 < _len2 ? _len2 - 1 : 0), + _key2 = 1; + _key2 < _len2; + _key2++ + ) + args[_key2 - 1] = arguments[_key2]; + return (_currentStrategy = currentStrategy).encrypt.apply( + _currentStrategy, + [actionId].concat(args) + ); +}; +exports.ensureServerActions = function (actions) { + for (var i = 0; i < actions.length; i++) { + var action = actions[i]; + if ("function" !== typeof action) + throw Error( + 'A "use server" file can only export async functions, found ' + + typeof action + + "." + ); + } +}; +exports.loadServerAction = function (actionId) { + var actionModId = {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest[actionId].id; + if (!actionModId) + throw Error( + 'Failed to find Server Action "' + + actionId + + '". This request might be from an older or newer deployment.' + ); + actionId = __webpack_require__(actionModId)[actionId]; + if ("function" !== typeof actionId) + throw Error("Server actions must be functions"); + return actionId; +}; +exports.prerender = function (model, options) { + return new Promise(function (resolve, reject) { + var request = createPrerenderRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + function () { + var writable, + stream = new ReadableStream( + { + type: "bytes", + start: function (controller) { + writable = + createFakeWritableFromReadableStreamController(controller); + }, + pull: function () { + startFlowing(request, writable); + }, + cancel: function (reason) { + request.destination = null; + abort(request, reason); + } + }, + { highWaterMark: 0 } + ); + resolve({ prelude: stream }); + }, + reject, + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0 + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + startWork(request); + }); +}; +exports.prerenderToNodeStream = function (model, options) { + return new Promise(function (resolve, reject) { + var request = createPrerenderRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + function () { + var readable = new stream.Readable({ + read: function () { + startFlowing(request, writable); + } + }), + writable = createFakeWritableFromNodeReadable(readable); + resolve({ prelude: readable }); + }, + reject, + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0 + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + startWork(request); + }); +}; +exports.registerClientReference = function ( + proxyImplementation, + id, + exportName +) { + return Object.defineProperties(proxyImplementation, { + $$typeof: { value: CLIENT_REFERENCE_TAG$1 }, + $$id: { value: id + "#" + exportName }, + $$async: { value: !1 } + }); +}; +exports.registerServerReference = function (reference, id, exportName) { + return Object.defineProperties(reference, { + $$typeof: { value: SERVER_REFERENCE_TAG }, + $$id: { + value: null === exportName ? id : id + "#" + exportName, + configurable: !0 + }, + $$bound: { value: null, configurable: !0 }, + bind: { value: bind, configurable: !0 }, + toString: serverReferenceToString + }); +}; +exports.renderToPipeableStream = function (model, options) { + var request = createRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0 + ), + hasStartedFlowing = !1; + startWork(request); + return { + pipe: function (destination) { + if (hasStartedFlowing) + throw Error( + "React currently only supports piping to one writable stream." + ); + hasStartedFlowing = !0; + startFlowing(request, destination); + destination.on("drain", createDrainHandler(destination, request)); + destination.on( + "error", + createCancelHandler( + request, + "The destination stream errored while writing data." + ) + ); + destination.on( + "close", + createCancelHandler(request, "The destination stream closed early.") + ); + return destination; + }, + abort: function (reason) { + abort(request, reason); + } + }; +}; +exports.renderToReadableStream = function (model, options) { + var request = createRequest( + model, + createClientManifest( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.clientManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + options ? options.cssLinkPrecedence : void 0 + ), + options ? options.onError : void 0, + options ? options.identifierPrefix : void 0, + options ? options.temporaryReferences : void 0 + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(request, signal.reason); + else { + var listener = function () { + abort(request, signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + var writable; + return new ReadableStream( + { + type: "bytes", + start: function (controller) { + writable = createFakeWritableFromReadableStreamController(controller); + startWork(request); + }, + pull: function () { + startFlowing(request, writable); + }, + cancel: function (reason) { + request.destination = null; + abort(request, reason); + } + }, + { highWaterMark: 0 } + ); +}; +exports.setServerActionBoundArgsEncryption = function (strategy) { + currentStrategy = strategy; +}; + + +}, +"./node_modules/react-server-dom-rspack/server.node.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; + + +var s; +if (process.env.NODE_ENV === 'production') { + s = __webpack_require__("./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.production.js"); +} else { + s = __webpack_require__("./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-server.node.development.js"); +} + +exports.WK = s.renderToReadableStream; +__rspack_unused_export = s.renderToPipeableStream; +__rspack_unused_export = s.decodeReply; +__rspack_unused_export = s.decodeReplyFromBusboy; +__rspack_unused_export = s.decodeReplyFromAsyncIterable; +__rspack_unused_export = s.decodeAction; +__rspack_unused_export = s.decodeFormState; +__rspack_unused_export = s.registerServerReference; +__rspack_unused_export = s.registerClientReference; +__rspack_unused_export = s.createTemporaryReferenceSet; + +__rspack_unused_export = + s.setServerActionBoundArgsEncryption; +__rspack_unused_export = s.encryptServerActionBoundArgs; +__rspack_unused_export = s.decryptServerActionBoundArgs; +__rspack_unused_export = s.loadServerAction; +__rspack_unused_export = s.createServerEntry; +__rspack_unused_export = s.ensureServerActions; + + +}, +"./node_modules/react/cjs/react-jsx-runtime.react-server.development.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; +/** + * @license React + * react-jsx-runtime.react-server.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE + ? null + : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch ( + ("number" === typeof type.tag && + console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), + type.$$typeof) + ) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || + ((type = innerType.displayName || innerType.name || ""), + (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); + return type; + case REACT_MEMO_TYPE: + return ( + (innerType = type.displayName || null), + null !== innerType + ? innerType + : getComponentNameFromType(type.type) || "Memo" + ); + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) {} + } + return null; + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = !1; + } catch (e) { + JSCompiler_inline_result = !0; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = + ("function" === typeof Symbol && + Symbol.toStringTag && + value[Symbol.toStringTag]) || + value.constructor.name || + "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ( + "object" === typeof type && + null !== type && + type.$$typeof === REACT_LAZY_TYPE + ) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternalsServer.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return !1; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || + ((specialPropKeyWarningShown = !0), + console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = !0; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: !0 + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || + ((didWarnAboutElementRef[componentName] = !0), + console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + props: props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) + ? Object.defineProperty(type, "ref", { + enumerable: !1, + get: elementRefGetterWithDeprecationWarning + }) + : Object.defineProperty(type, "ref", { enumerable: !1, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function jsxDEVImpl( + type, + config, + maybeKey, + isStaticChildren, + debugStack, + debugTask + ) { + var children = config.children; + if (void 0 !== children) + if (isStaticChildren) + if (isArrayImpl(children)) { + for ( + isStaticChildren = 0; + isStaticChildren < children.length; + isStaticChildren++ + ) + validateChildKeys(children[isStaticChildren]); + Object.freeze && Object.freeze(children); + } else + console.error( + "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." + ); + else validateChildKeys(children); + if (hasOwnProperty.call(config, "key")) { + children = getComponentNameFromType(type); + var keys = Object.keys(config).filter(function (k) { + return "key" !== k; + }); + isStaticChildren = + 0 < keys.length + ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" + : "{key: someKey}"; + didWarnAboutKeySpread[children + isStaticChildren] || + ((keys = + 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}"), + console.error( + 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', + isStaticChildren, + children, + keys, + children + ), + (didWarnAboutKeySpread[children + isStaticChildren] = !0)); + } + children = null; + void 0 !== maybeKey && + (checkKeyStringCoercion(maybeKey), (children = "" + maybeKey)); + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (children = "" + config.key)); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + children && + defineKeyPropWarningGetter( + maybeKey, + "function" === typeof type + ? type.displayName || type.name || "Unknown" + : type + ); + return ReactElement( + type, + children, + maybeKey, + getOwner(), + debugStack, + debugTask + ); + } + function validateChildKeys(node) { + isValidElement(node) + ? node._store && (node._store.validated = 1) + : "object" === typeof node && + null !== node && + node.$$typeof === REACT_LAZY_TYPE && + ("fulfilled" === node._payload.status + ? isValidElement(node._payload.value) && + node._payload.value._store && + (node._payload.value._store.validated = 1) + : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + } + var React = __webpack_require__("./node_modules/react/react.react-server.js"), + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), + ReactSharedInternalsServer = + React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + if (!ReactSharedInternalsServer) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); + var hasOwnProperty = Object.prototype.hasOwnProperty, + isArrayImpl = Array.isArray, + createTask = console.createTask + ? console.createTask + : function () { + return null; + }; + React = { + react_stack_bottom_frame: function (callStackForError) { + return callStackForError(); + } + }; + var specialPropKeyWarningShown; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind( + React, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutKeySpread = {}; + __rspack_unused_export = REACT_FRAGMENT_TYPE; + exports.jsx = function (type, config, maybeKey) { + var trackActualOwner = + 1e4 > ReactSharedInternalsServer.recentlyCreatedOwnerStacks++; + if (trackActualOwner) { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + var debugStackDEV = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + } else debugStackDEV = unknownOwnerDebugStack; + return jsxDEVImpl( + type, + config, + maybeKey, + !1, + debugStackDEV, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + __rspack_unused_export = function (type, config, maybeKey, isStaticChildren) { + var trackActualOwner = + 1e4 > ReactSharedInternalsServer.recentlyCreatedOwnerStacks++; + if (trackActualOwner) { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + var debugStackDEV = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + } else debugStackDEV = unknownOwnerDebugStack; + return jsxDEVImpl( + type, + config, + maybeKey, + isStaticChildren, + debugStackDEV, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + __rspack_unused_export = function (type, config, maybeKey) { + var trackActualOwner = + 1e4 > ReactSharedInternalsServer.recentlyCreatedOwnerStacks++; + if (trackActualOwner) { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + var debugStackDEV = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + } else debugStackDEV = unknownOwnerDebugStack; + return jsxDEVImpl( + type, + config, + maybeKey, + !0, + debugStackDEV, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + })(); + + +}, +"./node_modules/react/cjs/react-jsx-runtime.react-server.production.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; +/** + * @license React + * react-jsx-runtime.react-server.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var React = __webpack_require__("./node_modules/react/react.react-server.js"), + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); +if (!React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) + throw Error( + 'The "react" package in this environment is not configured correctly. The "react-server" condition must be enabled in any environment that runs React Server Components.' + ); +function jsxProd(type, config, maybeKey) { + var key = null; + void 0 !== maybeKey && (key = "" + maybeKey); + void 0 !== config.key && (key = "" + config.key); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + config = maybeKey.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + ref: void 0 !== config ? config : null, + props: maybeKey + }; +} +__rspack_unused_export = REACT_FRAGMENT_TYPE; +exports.jsx = jsxProd; +__rspack_unused_export = void 0; +__rspack_unused_export = jsxProd; + + +}, +"./node_modules/react/cjs/react.react-server.development.js"(__unused_rspack_module, exports) { +/** + * @license React + * react.react-server.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function noop() {} + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) + return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = !1; + } catch (e) { + JSCompiler_inline_result = !0; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = + ("function" === typeof Symbol && + Symbol.toStringTag && + value[Symbol.toStringTag]) || + value.constructor.name || + "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE + ? null + : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch ( + ("number" === typeof type.tag && + console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), + type.$$typeof) + ) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || + ((type = innerType.displayName || innerType.name || ""), + (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); + return type; + case REACT_MEMO_TYPE: + return ( + (innerType = type.displayName || null), + null !== innerType + ? innerType + : getComponentNameFromType(type.type) || "Memo" + ); + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) {} + } + return null; + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ( + "object" === typeof type && + null !== type && + type.$$typeof === REACT_LAZY_TYPE + ) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternals.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return !1; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || + ((specialPropKeyWarningShown = !0), + console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = !0; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: !0 + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || + ((didWarnAboutElementRef[componentName] = !0), + console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + props: props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) + ? Object.defineProperty(type, "ref", { + enumerable: !1, + get: elementRefGetterWithDeprecationWarning + }) + : Object.defineProperty(type, "ref", { enumerable: !1, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function cloneAndReplaceKey(oldElement, newKey) { + newKey = ReactElement( + oldElement.type, + newKey, + oldElement.props, + oldElement._owner, + oldElement._debugStack, + oldElement._debugTask + ); + oldElement._store && + (newKey._store.validated = oldElement._store.validated); + return newKey; + } + function validateChildKeys(node) { + isValidElement(node) + ? node._store && (node._store.validated = 1) + : "object" === typeof node && + null !== node && + node.$$typeof === REACT_LAZY_TYPE && + ("fulfilled" === node._payload.status + ? isValidElement(node._payload.value) && + node._payload.value._store && + (node._payload.value._store.validated = 1) + : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + } + function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return ( + "$" + + key.replace(/[=:]/g, function (match) { + return escaperLookup[match]; + }) + ); + } + function getElementKey(element, index) { + return "object" === typeof element && + null !== element && + null != element.key + ? (checkKeyStringCoercion(element.key), escape("" + element.key)) + : index.toString(36); + } + function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ( + ("string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), + (thenable.reason = error)); + } + )), + thenable.status) + ) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = !1; + if (null === children) invokeCallback = !0; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = !0; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = !0; + break; + case REACT_LAZY_TYPE: + return ( + (invokeCallback = children._init), + mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ) + ); + } + } + if (invokeCallback) { + invokeCallback = children; + callback = callback(invokeCallback); + var childKey = + "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar; + isArrayImpl(callback) + ? ((escapedPrefix = ""), + null != childKey && + (escapedPrefix = + childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), + mapIntoArray(callback, array, escapedPrefix, "", function (c) { + return c; + })) + : null != callback && + (isValidElement(callback) && + (null != callback.key && + ((invokeCallback && invokeCallback.key === callback.key) || + checkKeyStringCoercion(callback.key)), + (escapedPrefix = cloneAndReplaceKey( + callback, + escapedPrefix + + (null == callback.key || + (invokeCallback && invokeCallback.key === callback.key) + ? "" + : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + + childKey + )), + "" !== nameSoFar && + null != invokeCallback && + isValidElement(invokeCallback) && + null == invokeCallback.key && + invokeCallback._store && + !invokeCallback._store.validated && + (escapedPrefix._store.validated = 2), + (callback = escapedPrefix)), + array.push(callback)); + return 1; + } + invokeCallback = 0; + childKey = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + (nameSoFar = children[i]), + (type = childKey + getElementKey(nameSoFar, i)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if (((i = getIteratorFn(children)), "function" === typeof i)) + for ( + i === children.entries && + (didWarnAboutMaps || + console.warn( + "Using Maps as children is not supported. Use an array of keyed ReactElements instead." + ), + (didWarnAboutMaps = !0)), + children = i.call(children), + i = 0; + !(nameSoFar = children.next()).done; + + ) + (nameSoFar = nameSoFar.value), + (type = childKey + getElementKey(nameSoFar, i++)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === array + ? "object with keys {" + Object.keys(children).join(", ") + "}" + : array) + + "). If you meant to render a collection of children, use an array instead." + ); + } + return invokeCallback; + } + function mapChildren(children, func, context) { + if (null == children) return children; + var result = [], + count = 0; + mapIntoArray(children, result, "", "", function (child) { + return func.call(context, child, count++); + }); + return result; + } + function resolveDispatcher() { + var dispatcher = ReactSharedInternals.H; + null === dispatcher && + console.error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return dispatcher; + } + function lazyInitializer(payload) { + if (-1 === payload._status) { + var resolveDebugValue = null, + rejectDebugValue = null, + ioInfo = payload._ioInfo; + null != ioInfo && + ((ioInfo.start = ioInfo.end = performance.now()), + (ioInfo.value = new Promise(function (resolve, reject) { + resolveDebugValue = resolve; + rejectDebugValue = reject; + }))); + ioInfo = payload._result; + var thenable = ioInfo(); + thenable.then( + function (moduleObject) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 1; + payload._result = moduleObject; + var _ioInfo = payload._ioInfo; + if (null != _ioInfo) { + _ioInfo.end = performance.now(); + var debugValue = + null == moduleObject ? void 0 : moduleObject.default; + resolveDebugValue(debugValue); + _ioInfo.value.status = "fulfilled"; + _ioInfo.value.value = debugValue; + } + void 0 === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = moduleObject)); + } + }, + function (error) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 2; + payload._result = error; + var _ioInfo2 = payload._ioInfo; + null != _ioInfo2 && + ((_ioInfo2.end = performance.now()), + _ioInfo2.value.then(noop, noop), + rejectDebugValue(error), + (_ioInfo2.value.status = "rejected"), + (_ioInfo2.value.reason = error)); + void 0 === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + } + ); + ioInfo = payload._ioInfo; + if (null != ioInfo) { + var displayName = thenable.displayName; + "string" === typeof displayName && (ioInfo.name = displayName); + } + -1 === payload._status && + ((payload._status = 0), (payload._result = thenable)); + } + if (1 === payload._status) + return ( + (ioInfo = payload._result), + void 0 === ioInfo && + console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", + ioInfo + ), + "default" in ioInfo || + console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", + ioInfo + ), + ioInfo.default + ); + throw payload._result; + } + function createCacheRoot() { + return new WeakMap(); + } + function createCacheNode() { + return { s: 0, v: void 0, o: null, p: null }; + } + var ReactSharedInternals = { + H: null, + A: null, + getCurrentStack: null, + recentlyCreatedOwnerStacks: 0 + }, + isArrayImpl = Array.isArray, + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator, + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), + hasOwnProperty = Object.prototype.hasOwnProperty, + assign = Object.assign, + createTask = console.createTask + ? console.createTask + : function () { + return null; + }, + createFakeCallStack = { + react_stack_bottom_frame: function (callStackForError) { + return callStackForError(); + } + }, + specialPropKeyWarningShown, + didWarnAboutOldJSXRuntime; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = + createFakeCallStack.react_stack_bottom_frame.bind( + createFakeCallStack, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutMaps = !1, + userProvidedKeyEscapeRegex = /\/+/g; + createFakeCallStack = { + map: mapChildren, + forEach: function (children, forEachFunc, forEachContext) { + mapChildren( + children, + function () { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function (children) { + var n = 0; + mapChildren(children, function () { + n++; + }); + return n; + }, + toArray: function (children) { + return ( + mapChildren(children, function (child) { + return child; + }) || [] + ); + }, + only: function (children) { + if (!isValidElement(children)) + throw Error( + "React.Children.only expected to receive a single React element child." + ); + return children; + } + }; + exports.Activity = REACT_ACTIVITY_TYPE; + exports.Children = createFakeCallStack; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.ViewTransition = REACT_VIEW_TRANSITION_TYPE; + exports.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + ReactSharedInternals; + exports.cache = function (fn) { + return function () { + var dispatcher = ReactSharedInternals.A; + if (!dispatcher) return fn.apply(null, arguments); + var fnMap = dispatcher.getCacheForType(createCacheRoot); + dispatcher = fnMap.get(fn); + void 0 === dispatcher && + ((dispatcher = createCacheNode()), fnMap.set(fn, dispatcher)); + fnMap = 0; + for (var l = arguments.length; fnMap < l; fnMap++) { + var arg = arguments[fnMap]; + if ( + "function" === typeof arg || + ("object" === typeof arg && null !== arg) + ) { + var objectCache = dispatcher.o; + null === objectCache && + (dispatcher.o = objectCache = new WeakMap()); + dispatcher = objectCache.get(arg); + void 0 === dispatcher && + ((dispatcher = createCacheNode()), + objectCache.set(arg, dispatcher)); + } else + (objectCache = dispatcher.p), + null === objectCache && (dispatcher.p = objectCache = new Map()), + (dispatcher = objectCache.get(arg)), + void 0 === dispatcher && + ((dispatcher = createCacheNode()), + objectCache.set(arg, dispatcher)); + } + if (1 === dispatcher.s) return dispatcher.v; + if (2 === dispatcher.s) throw dispatcher.v; + try { + var result = fn.apply(null, arguments); + fnMap = dispatcher; + fnMap.s = 1; + return (fnMap.v = result); + } catch (error) { + throw ( + ((result = dispatcher), (result.s = 2), (result.v = error), error) + ); + } + }; + }; + exports.cacheSignal = function () { + var dispatcher = ReactSharedInternals.A; + return dispatcher ? dispatcher.cacheSignal() : null; + }; + exports.captureOwnerStack = function () { + var getCurrentStack = ReactSharedInternals.getCurrentStack; + return null === getCurrentStack ? null : getCurrentStack(); + }; + exports.cloneElement = function (element, config, children) { + if (null === element || void 0 === element) + throw Error( + "The argument must be a React element, but you passed " + + element + + "." + ); + var props = assign({}, element.props), + key = element.key, + owner = element._owner; + if (null != config) { + var JSCompiler_inline_result; + a: { + if ( + hasOwnProperty.call(config, "ref") && + (JSCompiler_inline_result = Object.getOwnPropertyDescriptor( + config, + "ref" + ).get) && + JSCompiler_inline_result.isReactWarning + ) { + JSCompiler_inline_result = !1; + break a; + } + JSCompiler_inline_result = void 0 !== config.ref; + } + JSCompiler_inline_result && (owner = getOwner()); + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (key = "" + config.key)); + for (propName in config) + !hasOwnProperty.call(config, propName) || + "key" === propName || + "__self" === propName || + "__source" === propName || + ("ref" === propName && void 0 === config.ref) || + (props[propName] = config[propName]); + } + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + JSCompiler_inline_result = Array(propName); + for (var i = 0; i < propName; i++) + JSCompiler_inline_result[i] = arguments[i + 2]; + props.children = JSCompiler_inline_result; + } + props = ReactElement( + element.type, + key, + props, + owner, + element._debugStack, + element._debugTask + ); + for (key = 2; key < arguments.length; key++) + validateChildKeys(arguments[key]); + return props; + }; + exports.createElement = function (type, config, children) { + for (var i = 2; i < arguments.length; i++) + validateChildKeys(arguments[i]); + var propName; + i = {}; + var key = null; + if (null != config) + for (propName in (didWarnAboutOldJSXRuntime || + !("__self" in config) || + "key" in config || + ((didWarnAboutOldJSXRuntime = !0), + console.warn( + "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform" + )), + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (key = "" + config.key)), + config)) + hasOwnProperty.call(config, propName) && + "key" !== propName && + "__self" !== propName && + "__source" !== propName && + (i[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) i.children = children; + else if (1 < childrenLength) { + for ( + var childArray = Array(childrenLength), _i = 0; + _i < childrenLength; + _i++ + ) + childArray[_i] = arguments[_i + 2]; + Object.freeze && Object.freeze(childArray); + i.children = childArray; + } + if (type && type.defaultProps) + for (propName in ((childrenLength = type.defaultProps), childrenLength)) + void 0 === i[propName] && (i[propName] = childrenLength[propName]); + key && + defineKeyPropWarningGetter( + i, + "function" === typeof type + ? type.displayName || type.name || "Unknown" + : type + ); + (propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++) + ? ((childArray = Error.stackTraceLimit), + (Error.stackTraceLimit = 10), + (childrenLength = Error("react-stack-top-frame")), + (Error.stackTraceLimit = childArray)) + : (childrenLength = unknownOwnerDebugStack); + return ReactElement( + type, + key, + i, + getOwner(), + childrenLength, + propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + exports.createRef = function () { + var refObject = { current: null }; + Object.seal(refObject); + return refObject; + }; + exports.forwardRef = function (render) { + null != render && render.$$typeof === REACT_MEMO_TYPE + ? console.error( + "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))." + ) + : "function" !== typeof render + ? console.error( + "forwardRef requires a render function but was given %s.", + null === render ? "null" : typeof render + ) + : 0 !== render.length && + 2 !== render.length && + console.error( + "forwardRef render functions accept exactly two parameters: props and ref. %s", + 1 === render.length + ? "Did you forget to use the ref parameter?" + : "Any additional parameter will be undefined." + ); + null != render && + null != render.defaultProps && + console.error( + "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?" + ); + var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render }, + ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: !1, + configurable: !0, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; + render.name || + render.displayName || + (Object.defineProperty(render, "name", { value: name }), + (render.displayName = name)); + } + }); + return elementType; + }; + exports.isValidElement = isValidElement; + exports.lazy = function (ctor) { + ctor = { _status: -1, _result: ctor }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: ctor, + _init: lazyInitializer + }, + ioInfo = { + name: "lazy", + start: -1, + end: -1, + value: null, + owner: null, + debugStack: Error("react-stack-top-frame"), + debugTask: console.createTask ? console.createTask("lazy()") : null + }; + ctor._ioInfo = ioInfo; + lazyType._debugInfo = [{ awaited: ioInfo }]; + return lazyType; + }; + exports.memo = function (type, compare) { + null == type && + console.error( + "memo: The first argument must be a component. Instead received: %s", + null === type ? "null" : typeof type + ); + compare = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: void 0 === compare ? null : compare + }; + var ownName; + Object.defineProperty(compare, "displayName", { + enumerable: !1, + configurable: !0, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; + type.name || + type.displayName || + (Object.defineProperty(type, "name", { value: name }), + (type.displayName = name)); + } + }); + return compare; + }; + exports.use = function (usable) { + return resolveDispatcher().use(usable); + }; + exports.useCallback = function (callback, deps) { + return resolveDispatcher().useCallback(callback, deps); + }; + exports.useDebugValue = function (value, formatterFn) { + return resolveDispatcher().useDebugValue(value, formatterFn); + }; + exports.useId = function () { + return resolveDispatcher().useId(); + }; + exports.useMemo = function (create, deps) { + return resolveDispatcher().useMemo(create, deps); + }; + exports.version = "19.3.0"; + })(); + + +}, +"./node_modules/react/cjs/react.react-server.production.js"(__unused_rspack_module, exports) { +/** + * @license React + * react.react-server.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var ReactSharedInternals = { H: null, A: null }; +function formatProdErrorMessage(code) { + var url = "https://react.dev/errors/" + code; + if (1 < arguments.length) { + url += "?args[]=" + encodeURIComponent(arguments[1]); + for (var i = 2; i < arguments.length; i++) + url += "&args[]=" + encodeURIComponent(arguments[i]); + } + return ( + "Minified React error #" + + code + + "; visit " + + url + + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings." + ); +} +var isArrayImpl = Array.isArray; +function noop() {} +var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; +} +var hasOwnProperty = Object.prototype.hasOwnProperty, + assign = Object.assign; +function ReactElement(type, key, props) { + var refProp = props.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + ref: void 0 !== refProp ? refProp : null, + props: props + }; +} +function cloneAndReplaceKey(oldElement, newKey) { + return ReactElement(oldElement.type, newKey, oldElement.props); +} +function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); +} +function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return ( + "$" + + key.replace(/[=:]/g, function (match) { + return escaperLookup[match]; + }) + ); +} +var userProvidedKeyEscapeRegex = /\/+/g; +function getElementKey(element, index) { + return "object" === typeof element && null !== element && null != element.key + ? escape("" + element.key) + : index.toString(36); +} +function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ( + ("string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + )), + thenable.status) + ) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; +} +function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = !1; + if (null === children) invokeCallback = !0; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = !0; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = !0; + break; + case REACT_LAZY_TYPE: + return ( + (invokeCallback = children._init), + mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ) + ); + } + } + if (invokeCallback) + return ( + (callback = callback(children)), + (invokeCallback = + "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar), + isArrayImpl(callback) + ? ((escapedPrefix = ""), + null != invokeCallback && + (escapedPrefix = + invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), + mapIntoArray(callback, array, escapedPrefix, "", function (c) { + return c; + })) + : null != callback && + (isValidElement(callback) && + (callback = cloneAndReplaceKey( + callback, + escapedPrefix + + (null == callback.key || + (children && children.key === callback.key) + ? "" + : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + + invokeCallback + )), + array.push(callback)), + 1 + ); + invokeCallback = 0; + var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + (nameSoFar = children[i]), + (type = nextNamePrefix + getElementKey(nameSoFar, i)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if (((i = getIteratorFn(children)), "function" === typeof i)) + for ( + children = i.call(children), i = 0; + !(nameSoFar = children.next()).done; + + ) + (nameSoFar = nameSoFar.value), + (type = nextNamePrefix + getElementKey(nameSoFar, i++)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + formatProdErrorMessage( + 31, + "[object Object]" === array + ? "object with keys {" + Object.keys(children).join(", ") + "}" + : array + ) + ); + } + return invokeCallback; +} +function mapChildren(children, func, context) { + if (null == children) return children; + var result = [], + count = 0; + mapIntoArray(children, result, "", "", function (child) { + return func.call(context, child, count++); + }); + return result; +} +function lazyInitializer(payload) { + if (-1 === payload._status) { + var ctor = payload._result, + thenable = ctor(); + thenable.then( + function (moduleObject) { + if (0 === payload._status || -1 === payload._status) + (payload._status = 1), + (payload._result = moduleObject), + void 0 === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = moduleObject)); + }, + function (error) { + if (0 === payload._status || -1 === payload._status) + (payload._status = 2), + (payload._result = error), + void 0 === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + ); + -1 === payload._status && + ((payload._status = 0), (payload._result = thenable)); + } + if (1 === payload._status) return payload._result.default; + throw payload._result; +} +function createCacheRoot() { + return new WeakMap(); +} +function createCacheNode() { + return { s: 0, v: void 0, o: null, p: null }; +} +var Children = { + map: mapChildren, + forEach: function (children, forEachFunc, forEachContext) { + mapChildren( + children, + function () { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function (children) { + var n = 0; + mapChildren(children, function () { + n++; + }); + return n; + }, + toArray: function (children) { + return ( + mapChildren(children, function (child) { + return child; + }) || [] + ); + }, + only: function (children) { + if (!isValidElement(children)) throw Error(formatProdErrorMessage(143)); + return children; + } +}; +exports.Activity = REACT_ACTIVITY_TYPE; +exports.Children = Children; +exports.Fragment = REACT_FRAGMENT_TYPE; +exports.Profiler = REACT_PROFILER_TYPE; +exports.StrictMode = REACT_STRICT_MODE_TYPE; +exports.Suspense = REACT_SUSPENSE_TYPE; +exports.ViewTransition = REACT_VIEW_TRANSITION_TYPE; +exports.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + ReactSharedInternals; +exports.cache = function (fn) { + return function () { + var dispatcher = ReactSharedInternals.A; + if (!dispatcher) return fn.apply(null, arguments); + var fnMap = dispatcher.getCacheForType(createCacheRoot); + dispatcher = fnMap.get(fn); + void 0 === dispatcher && + ((dispatcher = createCacheNode()), fnMap.set(fn, dispatcher)); + fnMap = 0; + for (var l = arguments.length; fnMap < l; fnMap++) { + var arg = arguments[fnMap]; + if ( + "function" === typeof arg || + ("object" === typeof arg && null !== arg) + ) { + var objectCache = dispatcher.o; + null === objectCache && (dispatcher.o = objectCache = new WeakMap()); + dispatcher = objectCache.get(arg); + void 0 === dispatcher && + ((dispatcher = createCacheNode()), objectCache.set(arg, dispatcher)); + } else + (objectCache = dispatcher.p), + null === objectCache && (dispatcher.p = objectCache = new Map()), + (dispatcher = objectCache.get(arg)), + void 0 === dispatcher && + ((dispatcher = createCacheNode()), + objectCache.set(arg, dispatcher)); + } + if (1 === dispatcher.s) return dispatcher.v; + if (2 === dispatcher.s) throw dispatcher.v; + try { + var result = fn.apply(null, arguments); + fnMap = dispatcher; + fnMap.s = 1; + return (fnMap.v = result); + } catch (error) { + throw ((result = dispatcher), (result.s = 2), (result.v = error), error); + } + }; +}; +exports.cacheSignal = function () { + var dispatcher = ReactSharedInternals.A; + return dispatcher ? dispatcher.cacheSignal() : null; +}; +exports.captureOwnerStack = function () { + return null; +}; +exports.cloneElement = function (element, config, children) { + if (null === element || void 0 === element) + throw Error(formatProdErrorMessage(267, element)); + var props = assign({}, element.props), + key = element.key; + if (null != config) + for (propName in (void 0 !== config.key && (key = "" + config.key), config)) + !hasOwnProperty.call(config, propName) || + "key" === propName || + "__self" === propName || + "__source" === propName || + ("ref" === propName && void 0 === config.ref) || + (props[propName] = config[propName]); + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + for (var childArray = Array(propName), i = 0; i < propName; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + return ReactElement(element.type, key, props); +}; +exports.createElement = function (type, config, children) { + var propName, + props = {}, + key = null; + if (null != config) + for (propName in (void 0 !== config.key && (key = "" + config.key), config)) + hasOwnProperty.call(config, propName) && + "key" !== propName && + "__self" !== propName && + "__source" !== propName && + (props[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) props.children = children; + else if (1 < childrenLength) { + for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + if (type && type.defaultProps) + for (propName in ((childrenLength = type.defaultProps), childrenLength)) + void 0 === props[propName] && + (props[propName] = childrenLength[propName]); + return ReactElement(type, key, props); +}; +exports.createRef = function () { + return { current: null }; +}; +exports.forwardRef = function (render) { + return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; +}; +exports.isValidElement = isValidElement; +exports.lazy = function (ctor) { + return { + $$typeof: REACT_LAZY_TYPE, + _payload: { _status: -1, _result: ctor }, + _init: lazyInitializer + }; +}; +exports.memo = function (type, compare) { + return { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: void 0 === compare ? null : compare + }; +}; +exports.use = function (usable) { + return ReactSharedInternals.H.use(usable); +}; +exports.useCallback = function (callback, deps) { + return ReactSharedInternals.H.useCallback(callback, deps); +}; +exports.useDebugValue = function () {}; +exports.useId = function () { + return ReactSharedInternals.H.useId(); +}; +exports.useMemo = function (create, deps) { + return ReactSharedInternals.H.useMemo(create, deps); +}; +exports.version = "19.3.0"; + + +}, +"./node_modules/react/jsx-runtime.react-server.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react/cjs/react-jsx-runtime.react-server.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react/cjs/react-jsx-runtime.react-server.development.js"); +} + + +}, +"./node_modules/react/react.react-server.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react/cjs/react.react-server.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react/cjs/react.react-server.development.js"); +} + + +}, +"./src/cli/_shared.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_commands_js__rspack_import_0 = __webpack_require__("./src/core/commands.js"); +/* import */ var _core_store_js__rspack_import_1 = __webpack_require__("./src/core/store.js"); +/* import */ var _gbot_js__rspack_import_2 = __webpack_require__("./src/gbot.ts"); + + + + +/** Shared backend selection flags (were leading globals on the hand CLI). */ const backendFlagsSchema = zod__rspack_import_3/* .object */.Ikc({ + dir: zod__rspack_import_3/* .string */.YjP().min(1).optional().describe('Agents directory for --files mode'), + files: zod__rspack_import_3/* .boolean */.zMY().optional().describe('Force the on-disk agents store'), + gateway: zod__rspack_import_3/* .boolean */.zMY().optional().describe('Force the live gateway') +}).strict(); +/** The flat failure document `outcomeFromError` builds for `exitCode: 'result'` routes. */ const failureDocumentSchema = zod__rspack_import_3/* .object */.Ikc({ + delivery: zod__rspack_import_3/* ["enum"] */.k5n([ + 'accepted', + 'queued', + 'rejected', + 'unknown' + ]), + error: zod__rspack_import_3/* .string */.YjP(), + exitCode: zod__rspack_import_3/* .literal */.euz(1) +}).catchall(zod__rspack_import_3/* .json */.Pq9()); +// The framework prints thrown route errors verbatim; a fetch or proxy failure can echo a credential. +const redactBackendErrors = (backend)=>new Proxy(backend, { + get (target, property, receiver) { + const value = Reflect.get(target, property, receiver); + return typeof value === 'function' ? (...args)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(()=>value.apply(target, args)) : value; + } + }); +const openBackendFromInput = async (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>redactBackendErrors(await (0,_core_commands_js__rspack_import_0/* .openBackend */.f)({ + files: Boolean(input.files), + gateway: Boolean(input.gateway), + root: input.dir + }))); +const avatarShapeSchema = zod__rspack_import_3/* ["enum"] */.k5n(_core_store_js__rspack_import_1/* .AVATAR_SHAPES */.Jb); +const avatarColorSchema = zod__rspack_import_3/* ["enum"] */.k5n(_core_store_js__rspack_import_1/* .AVATAR_COLORS */.T7); +const onOffSchema = zod__rspack_import_3/* ["enum"] */.k5n([ + 'on', + 'off' +]); +const parseOnOff = (value)=>value === 'on'; +const agentSummarySchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: zod__rspack_import_3/* .string */.YjP().optional(), + avatarShape: zod__rspack_import_3/* .string */.YjP().optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + hiddenFromSidebar: zod__rspack_import_3/* .boolean */.zMY().optional(), + id: zod__rspack_import_3/* .string */.YjP(), + kind: zod__rspack_import_3/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + members: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP()).optional(), + name: zod__rspack_import_3/* .string */.YjP(), + notifyOnAgentUpdates: zod__rspack_import_3/* .boolean */.zMY().optional(), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const skillSchema = zod__rspack_import_3/* .object */.Ikc({ + description: zod__rspack_import_3/* .string */.YjP(), + id: zod__rspack_import_3/* .string */.YjP(), + name: zod__rspack_import_3/* .string */.YjP(), + pluginId: zod__rspack_import_3/* .string */.YjP().optional(), + source: zod__rspack_import_3/* .string */.YjP(), + sourceRef: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const createFieldsSchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: avatarColorSchema.optional(), + avatarShape: avatarShapeSchema.optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + name: zod__rspack_import_3/* .string */.YjP().min(1), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const updateFieldsSchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: avatarColorSchema.optional(), + avatarShape: avatarShapeSchema.optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + hidden: onOffSchema.optional(), + name: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + notify: onOffSchema.optional(), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const toCreateInput = (fields)=>({ + avatarColor: fields.avatarColor ?? '', + avatarShape: fields.avatarShape ?? '', + description: fields.description ?? '', + name: fields.name, + title: fields.title ?? '' + }); +const toUpdatePatch = (fields)=>{ + const patch = {}; + if (fields.name !== undefined) patch.name = fields.name; + if (fields.description !== undefined) patch.description = fields.description; + if (fields.title !== undefined) patch.title = fields.title; + if (fields.avatarShape !== undefined) patch.avatarShape = fields.avatarShape; + if (fields.avatarColor !== undefined) patch.avatarColor = fields.avatarColor; + if (fields.notify !== undefined) patch.notifyOnAgentUpdates = parseOnOff(fields.notify); + if (fields.hidden !== undefined) patch.hiddenFromSidebar = parseOnOff(fields.hidden); + if (Object.keys(patch).length === 0) { + throw new Error('update needs at least one of --name --description --title --avatar-shape --avatar-color --notify --hidden'); + } + return patch; +}; + +__webpack_require__.d(__webpack_exports__, { +}, { + FS: openBackendFromInput, + R9: failureDocumentSchema, + b7: skillSchema, + bY: createFieldsSchema, + cp: toCreateInput, + lK: backendFlagsSchema, + li: toUpdatePatch, + qP: updateFieldsSchema, + t_: agentSummarySchema +}); + + +}, +"./src/cli/approvals/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_grok_approval_routes_js__rspack_import_1 = __webpack_require__("./src/core/grok-approval-routes.ts"); + + + + +const config = { + description: 'List current Grok approval cards (latest 200 entries).', + positionals: [ + 'target' + ], + inputJsonSchema: { + type: 'object', + properties: { + target: { + type: 'string' + } + }, + required: [ + 'target' + ], + additionalProperties: false + } +}; +async function route({ input }) { + const out = await (0,_core_grok_approval_routes_js__rspack_import_1/* .listOperation */.gi)(input); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.cE), + resultSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/approvals/respond.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_grok_approval_routes_js__rspack_import_1 = __webpack_require__("./src/core/grok-approval-routes.ts"); + + + + +const config = { + description: 'Explicit user decision: accept a Grok request once or decline; never grant persistent permissions.', + inputJsonSchema: { + type: 'object', + properties: { + target: { + type: 'string' + }, + entryId: { + type: 'string' + }, + requestId: { + type: 'string' + }, + decision: { + type: 'string', + enum: [ + 'accept', + 'decline' + ] + } + }, + required: [ + 'target', + 'entryId', + 'requestId', + 'decision' + ], + additionalProperties: false + } +}; +async function route({ input }) { + const out = await (0,_core_grok_approval_routes_js__rspack_import_1/* .respondOperation */.lr)(input); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.v1), + resultSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/bots/create.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'Create a Grok Bot bot.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + name: { + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'name' + ], + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .createFieldsSchema */.bY).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsCreate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, ...fields } = input; + const rec = await backend.createAgent((0,_shared_js__rspack_import_1/* .toCreateInput */.cp)(fields)); + if (rec == null) throw new Error('createAgent returned no record'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_3/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: `Created bot ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsCreate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/delete.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Delete a bot or group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsDelete({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.deleteAgent(input.ref); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Deleted ${rec.isGroup ? 'group' : 'bot'} ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsDelete) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/get.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show one bot or group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsGet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsGet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'List Grok Bot bots (not groups).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .agentSummarySchema */.t_); +async function botsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const all = await backend.list(); + const rows = all.filter((r)=>!r.isGroup); + const bots = rows.map(_core_format_js__rspack_import_3/* .summarize */.eh); + const text = rows.length === 0 ? 'No bots.' : rows.map((r)=>(0,_core_format_js__rspack_import_3/* .formatRecord */.bM)(r, all)).join('\n\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: bots, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/update.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Update a bot or group profile.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + hidden: { + type: 'string' + }, + name: { + type: 'string' + }, + notify: { + type: 'string' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .updateFieldsSchema */.qP).extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsUpdate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, ref, ...fields } = input; + const rec = await backend.updateAgent(ref, (0,_shared_js__rspack_import_1/* .toUpdatePatch */.li)(fields)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated ${rec.isGroup ? 'group' : 'bot'} ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsUpdate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/bridge/respond.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge respond.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + interactionId: { + type: 'string' + }, + generation: { + type: 'string' + }, + threadId: { + type: 'string' + }, + turnId: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + exchangeId: { + type: 'string' + }, + decision: { + type: 'string', + enum: [ + 'accept', + 'decline', + 'cancel' + ] + }, + answersJson: { + type: 'string', + description: 'JSON object mapping each advertised question ID to {"answers":["answer"]}; exact IDs required.' + } + }, + required: [ + 'interactionId', + 'generation', + 'threadId', + 'turnId' + ], + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('respond', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.v1), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/run.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var node_child_process__rspack_import_1 = __webpack_require__("node:child_process"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_relay_managed_js__rspack_import_2 = __webpack_require__("./src/core/relay/managed.js"); + + + + + +const inputSchema = zod__rspack_import_3/* .object */.Ikc({ + lifetimeMs: zod__rspack_import_3/* .number */.aig().int().min(100).max(82800000).default(82800000) +}).strict(); +const resultSchema = zod__rspack_import_3/* .object */.Ikc({ + state: zod__rspack_import_3/* .string */.YjP(), + exitCode: zod__rspack_import_3/* .number */.aig() +}); +const config = { + description: 'Run a bounded foreground relay (up to 23 hours). Use the packaged gbot-relay.mjs script for unlimited service lifetime.', + exitCode: 'result', + render: { + maxElapsedMs: 86400000 + }, + inputJsonSchema: { + type: 'object', + properties: { + lifetimeMs: { + type: 'number', + description: 'Foreground lifetime in milliseconds (100..82800000; default 23h).' + } + }, + additionalProperties: false + } +}; +async function route({ signal, input }) { + const context = await (0,_agent_bundle_runtime__rspack_import_4/* .agent */.MA)(); + const script = await (0,_core_relay_managed_js__rspack_import_2/* .resolveRelayWorker */._v)({ + pluginRoot: context.plugin.state === 'available' ? context.plugin.value.root : undefined + }); + // The renderer may terminate immediately on abort. The separate worker can finish + // asynchronous socket/ledger cleanup after the synchronous termination signal. + const child = (0,node_child_process__rspack_import_1.spawn)(process.execPath, [ + script, + '--lifetime-ms', + String(input.lifetimeMs), + '--parent-pid', + String(process.pid) + ], { + stdio: [ + 'ignore', + 'ignore', + 'inherit' + ] + }); + const stop = ()=>{ + child.kill('SIGTERM'); + }; + signal.addEventListener('abort', stop, { + once: true + }); + if (signal.aborted) stop(); + let exitCode; + try { + exitCode = await new Promise((resolve, reject)=>{ + child.once('error', reject); + child.once('exit', (code)=>resolve(code ?? 1)); + }); + } finally{ + signal.removeEventListener('abort', stop); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + state: 'stopped', + exitCode + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: "Relay worker stopped." + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/bridge/start.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge start.', + exitCode: 'result', + positionals: [ + 'grokTarget' + ], + inputJsonSchema: { + type: 'object', + properties: { + grokTarget: { + type: 'string' + }, + codexThreadId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + busyPolicy: { + type: 'string', + enum: [ + 'steer', + 'reject' + ] + }, + requestId: { + type: 'string' + } + }, + required: [ + 'grokTarget' + ], + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('startBinding', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.xD), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/status.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge status.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + bindingId: { + type: 'string' + }, + limit: { + type: 'number' + } + }, + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('status', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.np), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/stop.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge stop.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + bindingId: { + type: 'string' + }, + all: { + type: 'boolean' + }, + worker: { + type: 'boolean' + } + }, + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('stop', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.d5), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/desktop-shim.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_desktop_shim_js__rspack_import_1 = __webpack_require__("./src/core/desktop-shim.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); + + + + + +const config = { + description: 'Install, remove, or check the ChatGPT Desktop shim: a CODEX_CLI_PATH wrapper that bridges Desktop stdio onto the managed Codex daemon (stock app-server proxy hangs). macOS persists via LaunchAgent; always fails open to real Codex.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + action: { + description: 'install | uninstall | status', + enum: [ + 'install', + 'uninstall', + 'status' + ], + type: 'string' + } + }, + required: [ + 'action' + ], + type: 'object' + }, + positionals: [ + 'action' + ] +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({ + action: zod__rspack_import_2/* ["enum"] */.k5n([ + 'install', + 'uninstall', + 'status' + ]) +}).strict(); +const resultSchema = zod__rspack_import_2/* .object */.Ikc({ + exitCode: zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .literal */.euz(0), + zod__rspack_import_2/* .literal */.euz(1) + ]) +}).passthrough(); +const formatWarnings = (warnings)=>warnings.length === 0 ? '' : `\nwarnings:\n${warnings.map((w)=>` - ${String(w)}`).join('\n')}`; +async function codexDesktopShim({ input }) { + switch(input.action){ + case 'install': + { + let out; + try { + out = (0,_core_desktop_shim_js__rspack_import_1/* .installDesktopShim */.B0)(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + action: 'install', + error: message, + exitCode: 1 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Desktop shim install failed: ${message}` + }) + }); + } + const text = `Installed ChatGPT Desktop shim:\n` + ` wrapper: ${out.wrapperPath}\n` + ` bridge: ${out.bridgePath}\n` + ` login env: ${out.envScriptPath}` + (out.plistPath ? `\n LaunchAgent: ${out.plistPath}` : '\n LaunchAgent: n/a (macOS-only)') + `\nFully quit and relaunch ChatGPT.app so it inherits CODEX_CLI_PATH; ` + `Desktop falls back to stock Codex if the shim is ever removed.` + formatWarnings(out.warnings); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); + } + case 'uninstall': + { + let out; + try { + out = (0,_core_desktop_shim_js__rspack_import_1/* .uninstallDesktopShim */.gM)(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + action: 'uninstall', + error: message, + exitCode: 1 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Desktop shim uninstall failed: ${message}` + }) + }); + } + const removed = out.removed.length === 0 ? '(nothing installed)' : out.removed.join(', '); + const text = `Removed ChatGPT Desktop shim: ${removed}. ` + `Desktop and Codex fall back to stock behavior; relaunch ChatGPT.app to pick it up.` + formatWarnings(out.warnings); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); + } + case 'status': + { + const out = (0,_core_desktop_shim_js__rspack_import_1/* .desktopShimStatus */.em)(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatDesktopShimStatus */.fX)(out) + }) + }); + } + default: + { + const _exhaustive = input.action; + throw new Error(`unknown desktop-shim action: ${String(_exhaustive)}`); + } + } +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexDesktopShim) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/list-threads.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_format_js__rspack_import_6 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'List Codex daemon-managed threads.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + cursor: { + description: 'Opaque pagination cursor (may start with -)', + type: 'string' + }, + limit: { + default: 20, + description: 'Max threads to list (1-200)', + type: 'number' + } + }, + type: 'object' + } +}; +const inputSchema = zod__rspack_import_4/* .object */.Ikc({ + cursor: zod__rspack_import_4/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_4/* .number */.aig().int().min(1).max(200).default(20) +}).strict(); +const resultSchema = zod__rspack_import_4/* .union */.KCZ([ + zod__rspack_import_4/* .object */.Ikc({ + exitCode: zod__rspack_import_4/* .literal */.euz(0), + limit: zod__rspack_import_4/* .number */.aig().int().min(1).max(200), + nextCursor: zod__rspack_import_4/* .string */.YjP().nullable(), + threads: zod__rspack_import_4/* .array */.YOg(zod__rspack_import_4/* .record */.g1P(zod__rspack_import_4/* .string */.YjP(), zod__rspack_import_4/* .json */.Pq9())) + }).strict(), + _shared_js__rspack_import_3/* .failureDocumentSchema */.R9 +]); +async function codexListThreads({ input }) { + let out; + try { + out = await (0,_core_codex_bridge_js__rspack_import_1/* .listCodexThreads */.X$)({ + cursor: input.cursor, + limit: input.limit + }); + } catch (error) { + const failure = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: failure, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: failure.error + }) + }); + } + const more = out.nextCursor ? `\n\nmore: --cursor ${JSON.stringify((0,_core_codex_bridge_js__rspack_import_1/* .singleLine */.pF)(out.nextCursor))}` : ''; + const text = out.threads.length === 0 ? 'No Codex threads.' : out.threads.map(_core_format_js__rspack_import_6/* .formatCodexThread */.nz).join('\n\n') + more; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexListThreads) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/queue.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_format_js__rspack_import_6 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'List the experimental Codex thread queue (GROK_BOT_CODEX_EXPERIMENTAL=1).', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + threadId: { + type: 'string' + } + }, + required: [ + 'threadId' + ], + type: 'object' + }, + positionals: [ + 'threadId' + ] +}; +const inputSchema = zod__rspack_import_4/* .object */.Ikc({ + threadId: zod__rspack_import_4/* .string */.YjP().min(1) +}).strict(); +const resultSchema = zod__rspack_import_4/* .union */.KCZ([ + zod__rspack_import_4/* .object */.Ikc({ + exitCode: zod__rspack_import_4/* .literal */.euz(0), + nextCursor: zod__rspack_import_4/* .string */.YjP().nullable(), + queued: zod__rspack_import_4/* .array */.YOg(zod__rspack_import_4/* .object */.Ikc({ + clientUserMessageId: zod__rspack_import_4/* .string */.YjP().nullable(), + id: zod__rspack_import_4/* .string */.YjP().nullable(), + text: zod__rspack_import_4/* .string */.YjP() + }).strict()), + threadId: zod__rspack_import_4/* .string */.YjP() + }).strict(), + _shared_js__rspack_import_3/* .failureDocumentSchema */.R9 +]); +async function codexQueue({ input }) { + let out; + try { + out = await (0,_core_codex_bridge_js__rspack_import_1/* .listCodexQueue */.Bt)(input.threadId); + } catch (error) { + const failure = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: failure, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: failure.error + }) + }); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_6/* .formatCodexQueue */.e_)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexQueue) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/send.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); +/* import */ var _core_relay_routes_js__rspack_import_2 = __webpack_require__("./src/core/relay/routes.ts"); + + + + + +const resultSchema = zod__rspack_import_3/* .union */.KCZ([ + _core_codex_routes_js__rspack_import_1/* .resultSchema */.FD, + _core_relay_routes_js__rspack_import_2/* .relayResultSchema */.Ax +]); +const inputSchema = zod__rspack_import_3/* .object */.Ikc({ + ..._core_codex_routes_js__rspack_import_1/* .sendFields */.at, + whenBusy: zod__rspack_import_3/* ["enum"] */.k5n([ + 'reject', + 'queue', + 'steer' + ]).optional(), + replyToGrok: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + requestId: zod__rspack_import_3/* .string */.YjP().min(1).max(128).optional(), + correlationId: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + replyTo: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + message: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP()).min(1) +}).strict(); +const config = { + description: 'Send to Codex; acceptance is distinct from completion. Options precede threadId.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId', + 'message' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + replyToGrok: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + requestId: { + type: 'string' + }, + threadId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + timeoutMs: { + type: 'number', + description: 'Observation timeout: 1-600000 milliseconds.' + }, + correlationId: { + type: 'string' + }, + envelope: { + type: 'boolean' + }, + hop: { + type: 'number' + }, + replyTo: { + type: 'string' + }, + expectedTurnId: { + type: 'string', + description: 'Required active-turn guard for steer; stale guards reject.' + }, + wait: { + type: 'boolean' + }, + maxOutputBytes: { + type: 'number', + description: 'Reply budget: 1-4194304 bytes.' + }, + whenBusy: { + type: 'string', + enum: [ + 'reject', + 'queue', + 'steer' + ] + }, + message: { + type: 'array', + items: { + type: 'string' + } + } + }, + required: [ + 'threadId', + 'message' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_4/* .agent */.MA)(); + if (input.replyToGrok || input.bindingId) { + const out = await (0,_core_relay_routes_js__rspack_import_2/* .codexReturnOperation */.lt)({ + ...input, + message: input.message.join(' ').trim() + }, context); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: out.delivery === 'rejected' ? 1 : 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: `Delivery ${out.delivery}; terminal answer returns to Grok automatically.` + }) + }); + } + const out = await (0,_core_codex_routes_js__rspack_import_1/* .sendOperation */.UP)({ + ...input, + whenBusy: input.whenBusy ?? 'reject', + message: input.message.join(' ').trim() + }, signal, (message)=>context.progress.report({ + message + }), true); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/status.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); + + + + + +const config = { + description: 'Probe the local Codex app-server daemon. Exit 0 only when it is usable.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: {}, + type: 'object' + } +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({}).strict(); +const resultSchema = zod__rspack_import_2/* .object */.Ikc({ + exitCode: zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .literal */.euz(0), + zod__rspack_import_2/* .literal */.euz(1) + ]) +}).passthrough(); +async function codexStatusCmd(_props) { + const status = await (0,_core_codex_bridge_js__rspack_import_1/* .codexStatus */.MU)(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: status, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatCodexStatus */.P2)(status) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexStatusCmd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/wait.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); + + + + +const config = { + description: 'Bounded Codex wait observation; never interrupts execution.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId', + 'turnId' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + "threadId": { + "type": "string" + }, + "expectedCwd": { + "type": "string" + }, + "timeoutMs": { + "type": "number", + "description": "Observation timeout: 1-600000 milliseconds." + }, + "turnId": { + "type": "string" + }, + "messageId": { + "type": "string" + }, + "maxOutputBytes": { + "type": "number", + "description": "Reply budget: 1-4194304 bytes." + } + }, + required: [ + 'threadId', + 'turnId' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_2/* .agent */.MA)(); + const out = await (0,_core_codex_routes_js__rspack_import_1/* .observeOperation */.gT)('wait', input, signal, (message)=>context.progress.report({ + message + })); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.jS), + resultSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/codex/watch.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); + + + + +const config = { + description: 'Bounded Codex watch observation; never interrupts execution.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + "threadId": { + "type": "string" + }, + "expectedCwd": { + "type": "string" + }, + "timeoutMs": { + "type": "number", + "description": "Observation timeout: 1-600000 milliseconds." + }, + "maxEvents": { + "type": "number", + "description": "Maximum observed events: 1-500." + } + }, + required: [ + 'threadId' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_2/* .agent */.MA)(); + const out = await (0,_core_codex_routes_js__rspack_import_1/* .observeOperation */.gT)('watch', input, signal, (message)=>context.progress.report({ + message + })); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.R9), + resultSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/doctor.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_6 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_5 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_app_session_js__rspack_import_1 = __webpack_require__("./src/core/app-session.js"); +/* import */ var _core_gateway_js__rspack_import_2 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _core_store_js__rspack_import_3 = __webpack_require__("./src/core/store.js"); +/* import */ var _shared_js__rspack_import_4 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'Show which agents root and auth sources gbot can see.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_4/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_5/* .object */.Ikc({ + candidates: zod__rspack_import_5/* .array */.YOg(zod__rspack_import_5/* .string */.YjP()), + found: zod__rspack_import_5/* .array */.YOg(zod__rspack_import_5/* .string */.YjP()), + gatewayAuthPresent: zod__rspack_import_5/* .boolean */.zMY(), + grokBotAppSession: zod__rspack_import_5/* .record */.g1P(zod__rspack_import_5/* .string */.YjP(), zod__rspack_import_5/* .json */.Pq9()), + note: zod__rspack_import_5/* .string */.YjP(), + resolved: zod__rspack_import_5/* .string */.YjP().nullable() +}).strict(); +async function doctor({ input }) { + const candidates = (0,_core_store_js__rspack_import_3/* .defaultCandidateRoots */.ye)().filter((c)=>typeof c === 'string'); + const found = candidates.filter(_core_store_js__rspack_import_3/* .looksLikeAgentsRoot */.A8); + let resolved = null; + try { + resolved = (0,_core_store_js__rspack_import_3/* .resolveAgentsRoot */.v1)(input.dir); + } catch (err) { + if (!(err instanceof _core_store_js__rspack_import_3/* .StoreError */.AD)) throw err; + } + const note = 'Live roster is on the box. Prefer CURSOR_ACCESS_TOKEN then EnsureSandBox then POST gateway /api/*.'; + const gatewayAuthPresent = (0,_core_gateway_js__rspack_import_2/* .hasGatewayAuth */.nF)(); + const grokBotAppSession = (0,_core_app_session_js__rspack_import_1/* .inspectGrokBotGatewaySession */.hd)(); + const sessionJson = { + present: grokBotAppSession.present, + usable: grokBotAppSession.usable, + ...grokBotAppSession.error === undefined ? {} : { + error: grokBotAppSession.error + }, + ...'code' in grokBotAppSession && grokBotAppSession.code != null ? { + code: grokBotAppSession.code + } : {} + }; + const value = { + resolved, + found, + candidates, + gatewayAuthPresent, + grokBotAppSession: sessionJson, + note + }; + const sessionLine = grokBotAppSession.usable ? 'Grok Bot app session: usable' : grokBotAppSession.present ? `Grok Bot app session: present but unusable: ${grokBotAppSession.error}` : 'Grok Bot app session: not found'; + const text = [ + `resolved: ${resolved ?? '(none)'}`, + `gateway auth: ${gatewayAuthPresent ? 'present' : 'no'}`, + sessionLine, + 'found:', + found.length ? found.map((p)=>` ${p}`).join('\n') : ' (none)', + 'candidates:', + ...candidates.map((c)=>` ${c}`), + note + ].join('\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_6/* .Agent.Result */.g6.Result, { + value: value, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_6/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (doctor) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/add.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Add a bot to a group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + bot: { + type: 'string' + }, + group: { + type: 'string' + } + }, + required: [ + 'group', + 'bot' + ], + type: 'object' + }, + positionals: [ + 'group', + 'bot' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + bot: zod__rspack_import_2/* .string */.YjP().min(1), + group: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsAdd({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.addGroupMember(input.group, input.bot); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Added to ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsAdd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/create.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); + + + + + +const config = { + description: 'Create a Grok Bot group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + member: { + description: 'Member bot id or name (repeatable)', + items: { + type: 'string' + }, + type: 'array' + }, + name: { + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'name', + 'member' + ], + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .createFieldsSchema */.bY).extend({ + member: zod__rspack_import_2/* .array */.YOg(zod__rspack_import_2/* .string */.YjP().min(1)).min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsCreate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, member, ...fields } = input; + const rec = await backend.createGroup({ + ...(0,_shared_js__rspack_import_1/* .toCreateInput */.cp)(fields), + memberIds: member + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Created group ${rec.name} (${rec.id}) with ${rec.memberIds.length} members` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsCreate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/delete.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Delete a group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsDelete({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group. Use bots delete.`); + const deleted = await backend.deleteAgent(input.ref); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(deleted), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Deleted group ${deleted.name} (${deleted.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsDelete) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/get.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show one group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsGet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group.`); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsGet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'List Grok Bot groups.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .agentSummarySchema */.t_); +async function groupsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const all = await backend.list(); + const rows = all.filter((r)=>r.isGroup); + const groups = rows.map(_core_format_js__rspack_import_3/* .summarize */.eh); + const text = rows.length === 0 ? 'No groups.' : rows.map((r)=>(0,_core_format_js__rspack_import_3/* .formatRecord */.bM)(r, all)).join('\n\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: groups, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/members.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show members of a group (same payload as groups get).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsMembers({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group.`); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsMembers) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/remove.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Remove a bot from a group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + bot: { + type: 'string' + }, + group: { + type: 'string' + } + }, + required: [ + 'group', + 'bot' + ], + type: 'object' + }, + positionals: [ + 'group', + 'bot' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + bot: zod__rspack_import_2/* .string */.YjP().min(1), + group: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsRemove({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.removeGroupMember(input.group, input.bot); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Removed from ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsRemove) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/set.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: "Replace a group's member list.", + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + group: { + type: 'string' + }, + member: { + description: 'Member bot id or name (repeatable)', + items: { + type: 'string' + }, + type: 'array' + } + }, + required: [ + 'group', + 'member' + ], + type: 'object' + }, + positionals: [ + 'group' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + group: zod__rspack_import_2/* .string */.YjP().min(1), + member: zod__rspack_import_2/* .array */.YOg(zod__rspack_import_2/* .string */.YjP().min(1)).min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsSet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.setGroupMembers(input.group, input.member); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsSet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/update.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Update a group profile (members stay on set/add/remove).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + hidden: { + type: 'string' + }, + name: { + type: 'string' + }, + notify: { + type: 'string' + }, + ref: { + description: 'Group id or name', + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .updateFieldsSchema */.qP).extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsUpdate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const current = await backend.resolve(input.ref); + if (!current.isGroup) throw new Error(`"${current.name}" is a bot, not a group. Use bots update.`); + const { dir: _d, files: _f, gateway: _g, ref, ...fields } = input; + const rec = await backend.updateAgent(ref, (0,_shared_js__rspack_import_1/* .toUpdatePatch */.li)(fields)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated group ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsUpdate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/history.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_history_js__rspack_import_1 = __webpack_require__("./src/core/history.js"); + + + + +const config = { + description: 'Read the opt-in local JSONL history without contacting the gateway.', + inputJsonSchema: { + additionalProperties: false, + properties: { + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + limit: { + default: 40, + description: 'Maximum matching rows (1 or more)', + type: 'number' + }, + path: { + description: 'Print the history file path', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + }, + search: { + description: 'Case-insensitive message text filter', + type: 'string' + } + }, + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({ + historyDir: zod__rspack_import_2/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_2/* .number */.aig().int().min(1).default(40), + path: zod__rspack_import_2/* .boolean */.zMY().default(false), + ref: zod__rspack_import_2/* .string */.YjP().min(1).optional(), + search: zod__rspack_import_2/* .string */.YjP().optional() +}).strict().refine((input)=>!input.path || input.ref === undefined && input.search === undefined && input.limit === 40, '--path cannot be combined with a target, --search, or --limit'); +const historyRowSchema = zod__rspack_import_2/* .record */.g1P(zod__rspack_import_2/* .string */.YjP(), zod__rspack_import_2/* .json */.Pq9()); +const resultSchema = zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .array */.YOg(historyRowSchema), + zod__rspack_import_2/* .object */.Ikc({ + path: zod__rspack_import_2/* .string */.YjP() + }).strict() +]); +async function history({ input }) { + const file = (0,_core_history_js__rspack_import_1/* .historyPath */.ae)(input.historyDir); + if (input.path) { + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + path: file + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: file + }) + }); + } + const rows = await (0,_core_history_js__rspack_import_1/* .readHistory */.Lu)(file, { + limit: input.limit, + ref: input.ref, + search: input.search + }); + const text = rows.length ? rows.map((row)=>`[${row.recordedAt}] ${row.target.name} (${row.target.id}) [${row.role}] ${row.text}`).join('\n') : 'No local history.'; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: rows, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (history) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/send.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_7 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_8 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_6 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_bridge_js__rspack_import_2 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_3 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_history_js__rspack_import_4 = __webpack_require__("./src/core/history.js"); +/* import */ var _shared_js__rspack_import_5 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + + +const config = { + description: 'Send a message to a Grok Bot bot or group by name or id.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + replyMode: { + type: 'string', + enum: [ + 'auto', + 'manual' + ] + }, + codexThreadId: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + requestId: { + type: 'string' + }, + correlationId: { + description: 'Stable correlation id for multi-hop replies', + type: 'string' + }, + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + envelope: { + description: 'Prepend the [gbot …] header', + type: 'boolean' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + hop: { + description: 'Hop count; refused at GROK_BOT_MAX_HOPS', + type: 'number' + }, + message: { + items: { + type: 'string' + }, + type: 'array' + }, + noHistory: { + description: 'Skip local history for this command', + type: 'boolean' + }, + replyTo: { + description: 'Prior message id this send replies to', + type: 'string' + }, + target: { + type: 'string' + } + }, + required: [ + 'target', + 'message' + ], + type: 'object' + }, + positionals: [ + 'target', + 'message' + ] +}; +const inputSchema = _shared_js__rspack_import_5/* .backendFlagsSchema.extend */.lK.extend({ + ..._core_relay_routes_js__rspack_import_1/* .routeFields */.zK, + replyMode: zod__rspack_import_6/* ["enum"] */.k5n([ + 'auto', + 'manual' + ]).optional(), + correlationId: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + envelope: zod__rspack_import_6/* .boolean */.zMY().default(false), + historyDir: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + hop: zod__rspack_import_6/* .number */.aig().int().min(0).optional(), + message: zod__rspack_import_6/* .array */.YOg(zod__rspack_import_6/* .string */.YjP()).min(1), + noHistory: zod__rspack_import_6/* .boolean */.zMY().default(false), + replyTo: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + target: zod__rspack_import_6/* .string */.YjP().min(1) +}).strict(); +const receiptSchema = zod__rspack_import_6/* .object */.Ikc({ + correlationId: zod__rspack_import_6/* .string */.YjP(), + delivery: zod__rspack_import_6/* ["enum"] */.k5n([ + 'accepted', + 'unknown' + ]), + envelopeId: zod__rspack_import_6/* .string */.YjP(), + exitCode: zod__rspack_import_6/* .literal */.euz(0), + hop: zod__rspack_import_6/* .number */.aig().int().min(0), + id: zod__rspack_import_6/* .string */.YjP(), + kind: zod__rspack_import_6/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + maxHops: zod__rspack_import_6/* .number */.aig().int().min(0), + messageId: zod__rspack_import_6/* .string */.YjP().optional(), + name: zod__rspack_import_6/* .string */.YjP(), + replyTo: zod__rspack_import_6/* .string */.YjP().optional(), + result: zod__rspack_import_6/* .record */.g1P(zod__rspack_import_6/* .string */.YjP(), zod__rspack_import_6/* .json */.Pq9()) +}).strict(); +// Refusals and gateway failures are the same flat document `codex send` emits. +const resultSchema = zod__rspack_import_6/* .union */.KCZ([ + receiptSchema, + _shared_js__rspack_import_5/* .failureDocumentSchema */.R9, + _core_relay_routes_js__rspack_import_1/* .relayResultSchema */.Ax +]); +const deliver = async (input)=>{ + const envelope = (0,_core_codex_bridge_js__rspack_import_2/* .buildEnvelope */.nq)({ + correlationId: input.correlationId, + envelope: input.envelope, + hop: input.hop, + replyTo: input.replyTo + }); + const message = input.message.join(' ').trim(); + const backend = await (0,_shared_js__rspack_import_5/* .openBackendFromInput */.FS)(input); + const out = await backend.send(input.target, (0,_core_codex_bridge_js__rspack_import_2/* .withEnvelopeHeader */.Mr)(message, envelope)); + (0,_core_history_js__rspack_import_4/* .saveHistory */.QX)(out, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'send', + prompt: message + }); + return { + id: out.target.id, + name: out.target.name, + kind: out.target.isGroup ? 'group' : 'bot', + result: out.result, + delivery: out.delivery === 'accepted' ? 'accepted' : 'unknown', + ...typeof out.messageId === 'string' ? { + messageId: out.messageId + } : {}, + envelopeId: envelope.messageId, + correlationId: envelope.correlationId, + ...input.replyTo ? { + replyTo: input.replyTo + } : {}, + hop: envelope.hop, + maxHops: envelope.maxHops, + exitCode: 0 + }; +}; +async function send({ input }) { + let value; + try { + if (input.replyMode === 'auto' || input.codexThreadId || input.bindingId) { + (0,_core_relay_routes_js__rspack_import_1/* .assertManagedSendOptions */.MB)(input); + if (input.files) throw Error('Automatic routes require the gateway backend'); + const out = await (0,_core_relay_routes_js__rspack_import_1/* .grokSendOperation */.bv)({ + target: input.target, + message: input.message.join(' ').trim(), + replyMode: input.replyMode ?? 'auto', + codexThreadId: input.codexThreadId, + bindingId: input.bindingId, + expectedCwd: input.expectedCwd, + requestId: input.requestId, + hop: input.hop, + correlationId: input.correlationId + }, await (0,_agent_bundle_runtime__rspack_import_7/* .agent */.MA)()); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: out.delivery === 'rejected' ? 1 : 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Text */.g6.Text, { + children: `Delivery ${out.delivery}; inspect codex bridge status for automatic reply delivery.` + }) + }); + } + value = await deliver(input); + } catch (error) { + value = (0,_core_codex_contract_js__rspack_import_3/* .outcomeFromError */.DG)(error); + } + const text = value.exitCode === 0 ? `Sent to ${value.kind} ${value.name} (${value.id})${value.messageId ? ` message ${value.messageId}` : ''}; envelope ${value.envelopeId}` : value.error; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Result */.g6.Result, { + value: value, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (send) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/add.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var node_fs_promises__rspack_import_1 = __webpack_require__("node:fs/promises"); +/* import */ var node_path__rspack_import_2 = __webpack_require__("node:path"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + +const config = { + description: 'Add a SKILL.md to the shared skill library. Every bot sees it.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + path: { + description: 'SKILL.md file, or a directory holding one', + type: 'string' + } + }, + required: [ + 'path' + ], + type: 'object' + }, + positionals: [ + 'path' + ] +}; +const inputSchema = _shared_js__rspack_import_3/* .backendFlagsSchema.extend */.lK.extend({ + path: zod__rspack_import_4/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_3/* .skillSchema */.b7; +const skillFile = async (path)=>{ + const target = (0,node_path__rspack_import_2.resolve)(path); + return (await (0,node_fs_promises__rspack_import_1.stat)(target)).isDirectory() ? (0,node_path__rspack_import_2.join)(target, 'SKILL.md') : target; +}; +async function skillsAdd({ input }) { + const markdown = await (0,node_fs_promises__rspack_import_1.readFile)(await skillFile(input.path), 'utf8'); + const backend = await (0,_shared_js__rspack_import_3/* .openBackendFromInput */.FS)(input); + const skill = resultSchema.parse(await backend.addSkill(markdown)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: skill, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: `Added skill ${skill.name} (${skill.id}) to the shared library` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsAdd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'List the skill library every bot in this Grok Bot shares.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .skillSchema */.b7); +async function skillsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const skills = resultSchema.parse(await backend.skills()); + const lines = skills.map((s)=>`${s.id} ${s.name} [${s.source}]${s.description ? ` ${s.description}` : ''}`); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: skills, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: lines.length > 0 ? lines.join('\n') : 'No skills.' + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/remove.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'Remove a library skill by id or name. Every bot loses it.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + skill: { + description: 'Skill id or name', + type: 'string' + } + }, + required: [ + 'skill' + ], + type: 'object' + }, + positionals: [ + 'skill' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + skill: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .skillSchema */.b7; +async function skillsRemove({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const skill = resultSchema.parse(await backend.removeSkill(input.skill)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: skill, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Removed skill ${skill.name} (${skill.id}) from the shared library` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsRemove) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/thread.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.react-server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_5 = __webpack_require__("./src/core/format.js"); +/* import */ var _core_history_js__rspack_import_1 = __webpack_require__("./src/core/history.js"); +/* import */ var _core_transcript_js__rspack_import_6 = __webpack_require__("./src/core/transcript.js"); +/* import */ var _shared_js__rspack_import_2 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'Read the most recent messages in a Grok Bot bot or group thread.', + inputJsonSchema: { + additionalProperties: false, + properties: { + after: { + description: 'Return entries after this opaque entry id', + type: 'string' + }, + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + full: { + description: 'Show full entry text in human output', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + limit: { + default: 40, + description: 'How many trailing entries to return (1-200)', + type: 'number' + }, + noHistory: { + description: 'Skip local history for this command', + type: 'boolean' + }, + root: { + description: 'Read one rooted thread by message id', + type: 'string' + }, + target: { + type: 'string' + } + }, + required: [ + 'target' + ], + type: 'object' + }, + positionals: [ + 'target' + ] +}; +const inputSchema = _shared_js__rspack_import_2/* .backendFlagsSchema.extend */.lK.extend({ + after: zod__rspack_import_3/* .string */.YjP().min(1).max(1024).optional(), + full: zod__rspack_import_3/* .boolean */.zMY().default(false), + historyDir: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(200).default(40), + noHistory: zod__rspack_import_3/* .boolean */.zMY().default(false), + root: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + target: zod__rspack_import_3/* .string */.YjP().min(1) +}).strict().refine((input)=>input.after === undefined || input.root === undefined, '--after cannot be combined with --root'); +const resultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +async function thread({ input }) { + const backend = await (0,_shared_js__rspack_import_2/* .openBackendFromInput */.FS)(input); + if (input.root !== undefined) { + const rooted = await backend.thread(input.target, input.root); + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(rooted, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread', + rootId: input.root + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: rooted, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(rooted, { + full: input.full + }) + }) + }); + } + const out = await backend.transcript(input.target, input.limit); + if (input.after !== undefined) { + const delta = (0,_core_transcript_js__rspack_import_6/* .transcriptDelta */.N3)(out.transcript, { + after: input.after, + limit: input.limit + }); + const selected = { + ...out, + transcript: { + entries: delta.entries + }, + cursor: delta.cursor, + entryCount: delta.entryCount, + gapReset: delta.gapReset + }; + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(selected, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread' + }); + const text = (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(selected, { + full: input.full + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: selected, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: `${text}\n\ncursor: ${delta.cursor}${delta.gapReset ? ' (gap reset)' : ''}` + }) + }); + } + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(out, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread' + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(out, { + full: input.full + }) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (thread) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/core/codex/routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _codex_bridge_js__rspack_import_0 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _contract_js__rspack_import_1 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _conversation_js__rspack_import_2 = __webpack_require__("./src/core/codex/conversation.js"); + + + + +const id = zod__rspack_import_3/* .string */.YjP().regex(/^[A-Za-z0-9_.:-]{1,128}$/); +const observationFields = { + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + threadId: id, + timeoutMs: zod__rspack_import_3/* .number */.aig().int().min(1).max(600000).optional() +}; +const sendFields = { + ...observationFields, + correlationId: id.optional(), + envelope: zod__rspack_import_3/* .boolean */.zMY().optional(), + hop: zod__rspack_import_3/* .number */.aig().int().min(0).optional(), + replyTo: id.optional(), + expectedTurnId: id.optional(), + whenBusy: zod__rspack_import_3/* ["enum"] */.k5n([ + 'reject', + 'queue', + 'steer' + ]).default('reject'), + wait: zod__rspack_import_3/* .boolean */.zMY().default(false), + maxOutputBytes: zod__rspack_import_3/* .number */.aig().int().min(1).max(4194304).optional() +}; +const sendSchema = zod__rspack_import_3/* .object */.Ikc({ + ...sendFields, + message: zod__rspack_import_3/* .string */.YjP().min(1).max(4194304) +}).strict(); +const waitSchema = zod__rspack_import_3/* .object */.Ikc({ + ...observationFields, + turnId: id, + messageId: id.optional(), + maxOutputBytes: zod__rspack_import_3/* .number */.aig().int().min(1).max(4194304).optional() +}).strict(); +const watchSchema = zod__rspack_import_3/* .object */.Ikc({ + ...observationFields, + maxEvents: zod__rspack_import_3/* .number */.aig().int().min(1).max(500).default(100) +}).strict(); +const threadsSchema = zod__rspack_import_3/* .object */.Ikc({ + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(200).default(20), + cursor: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional() +}).strict(); +const resultSchema = zod__rspack_import_3/* .object */.Ikc({ + exitCode: zod__rspack_import_3/* .number */.aig().int().min(0).max(1), + threadId: zod__rspack_import_3/* .string */.YjP().optional(), + turnId: zod__rspack_import_3/* .string */.YjP().optional(), + messageId: zod__rspack_import_3/* .string */.YjP().optional(), + delivery: zod__rspack_import_3/* ["enum"] */.k5n([ + 'accepted', + 'queued', + 'rejected', + 'unknown' + ]).optional(), + execution: zod__rspack_import_3/* .object */.Ikc({ + state: zod__rspack_import_3/* ["enum"] */.k5n([ + 'completed', + 'failed', + 'interrupted', + 'waiting-for-input', + 'timeout', + 'disconnected', + 'unknown' + ]), + error: zod__rspack_import_3/* .unknown */.L5J().optional() + }).optional(), + reply: zod__rspack_import_3/* .object */.Ikc({ + text: zod__rspack_import_3/* .string */.YjP().max(4194304), + items: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .object */.Ikc({ + id: zod__rspack_import_3/* .string */.YjP(), + type: zod__rspack_import_3/* .literal */.euz('agentMessage'), + phase: zod__rspack_import_3/* ["enum"] */.k5n([ + 'final_answer' + ]).nullable(), + text: zod__rspack_import_3/* .string */.YjP().max(4194304) + })).max(2000), + truncated: zod__rspack_import_3/* .boolean */.zMY() + }).optional(), + interactions: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .unknown */.L5J())).max(500).optional(), + events: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .unknown */.L5J())).max(500).optional(), + reason: zod__rspack_import_3/* .string */.YjP().optional(), + truncated: zod__rspack_import_3/* .boolean */.zMY().optional() +}).passthrough(); +async function sendOperation(input, signal, progress, oneShot = false) { + let envelope; + let receipt; + try { + envelope = (0,_codex_bridge_js__rspack_import_0/* .buildEnvelope */.nq)(input); + if (oneShot && !input.wait && input.whenBusy !== 'steer') { + return await (0,_codex_bridge_js__rspack_import_0/* .sendToCodexThread */.ZS)(input.threadId, input.message, { + envelope, + whenBusy: input.whenBusy, + expectedCwd: input.expectedCwd, + signal + }); + } + await progress?.('Opening Codex conversation'); + const conversation = await (0,_conversation_js__rspack_import_2/* .openCodexConversation */.j)(input.threadId, { + expectedCwd: input.expectedCwd, + signal + }); + try { + receipt = await conversation.send(input.message, { + envelope, + whenBusy: input.whenBusy, + expectedTurnId: input.expectedTurnId + }); + if (!input.wait || receipt.delivery !== 'accepted' || !receipt.turnId) return receipt; + await progress?.(`Accepted message ${receipt.messageId}; observing turn ${receipt.turnId}`); + const result = await conversation.wait({ + turnId: receipt.turnId, + messageId: receipt.messageId, + timeoutMs: input.timeoutMs, + maxOutputBytes: input.maxOutputBytes, + signal + }); + return { + ...receipt, + execution: result.execution, + reply: result.reply, + interactions: result.interactions, + exitCode: result.execution.state === 'completed' ? 0 : 1 + }; + } finally{ + await conversation.close(); + } + } catch (error) { + if (receipt?.delivery === 'accepted') return { + ...receipt, + execution: { + state: 'unknown', + error: (0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error).error + }, + reply: { + text: '', + items: [], + truncated: true + }, + interactions: [], + exitCode: 1 + }; + return { + ...(0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error), + threadId: input.threadId, + ...envelope ? { + messageId: envelope.messageId, + correlationId: envelope.correlationId, + hop: envelope.hop + } : {} + }; + } +} +async function observeOperation(kind, input, signal, progress) { + try { + await progress?.(`Observing Codex thread ${input.threadId}`); + const conversation = await (0,_conversation_js__rspack_import_2/* .openCodexConversation */.j)(input.threadId, { + expectedCwd: input.expectedCwd, + signal + }); + try { + if (kind === 'wait') { + const result = await conversation.wait({ + ...input, + signal + }); + return { + ...result, + exitCode: result.execution.state === 'completed' ? 0 : 1 + }; + } + const result = await conversation.watch({ + ...input, + signal + }); + return { + ...result, + exitCode: [ + 'timeout', + 'event-limit' + ].includes(result.reason) ? 0 : 1 + }; + } finally{ + await conversation.close(); + } + } catch (error) { + return { + ...(0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error), + threadId: input.threadId, + ...'turnId' in input ? { + turnId: input.turnId, + messageId: input.messageId + } : {} + }; + } +} +async function threadsOperation(input) { + try { + return { + ...await listCodexThreads(input), + exitCode: 0 + }; + } catch (error) { + return outcomeFromError(error); + } +} +function resultText(result) { + if (result.execution && typeof result.execution === 'object' && 'state' in result.execution) return `Codex turn ${result.turnId}: ${result.execution.state}`; + if (result.delivery === 'queued') return `Queued ${result.queuedSubmissionId} on busy Codex thread ${result.threadId}; message ${result.messageId}`; + if (result.error) return String(result.error); + if (result.delivery === 'accepted') return `Started turn ${result.turnId} (${result.turnStatus}) on Codex thread ${result.threadId}; message ${result.messageId}`; + if (result.delivery) return `Codex delivery ${result.delivery} on thread ${result.threadId}`; + if (result.reason) return `Codex observation: ${result.reason}`; + if (Array.isArray(result.threads)) return `${result.threads.length} Codex threads`; + return String(result.error ?? 'Codex observation complete'); +} + +__webpack_require__.d(__webpack_exports__, { + D6: () => (resultText), + UP: () => (sendOperation), + gT: () => (observeOperation) +}, { + FD: resultSchema, + R9: watchSchema, + at: sendFields, + jS: waitSchema +}); + + +}, +"./src/core/grok-approval-routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _gateway_js__rspack_import_0 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _grok_approvals_js__rspack_import_1 = __webpack_require__("./src/core/grok-approvals.js"); +/* import */ var _gbot_js__rspack_import_2 = __webpack_require__("./src/gbot.ts"); + + + + +const listSchema = zod__rspack_import_3/* .strictObject */.rej({ + target: zod__rspack_import_3/* .string */.YjP().min(1).max(1024) +}); +const respondSchema = _grok_approvals_js__rspack_import_1/* .grokApprovalResponseSchema */.T5; +const resultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +const listOperation = (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>(0,_gateway_js__rspack_import_0/* .listGrokApprovals */.MI)(await (0,_gateway_js__rspack_import_0/* .connectGateway */.Vq)(), listSchema.parse(input).target)); +const respondOperation = (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>{ + const { target, ...response } = respondSchema.parse(input); + return (0,_gateway_js__rspack_import_0/* .respondGrokApproval */.OR)(await (0,_gateway_js__rspack_import_0/* .connectGateway */.Vq)(), target, response); + }); + +__webpack_require__.d(__webpack_exports__, { +}, { + FD: resultSchema, + cE: listSchema, + gi: listOperation, + lr: respondOperation, + v1: respondSchema +}); + + +}, +"./src/core/relay/routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/40.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _managed_js__rspack_import_0 = __webpack_require__("./src/core/relay/managed.js"); +/* import */ var _gbot_js__rspack_import_1 = __webpack_require__("./src/gbot.ts"); +/* import */ var _codex_bridge_js__rspack_import_2 = __webpack_require__("./src/core/codex-bridge.js"); + + + + + +const id = zod__rspack_import_3/* .string */.YjP().min(1).max(128); +const routeFields = { + codexThreadId: id.optional(), + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional(), + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + requestId: id.optional() +}; +const grokSendSchema = zod__rspack_import_3/* .object */.Ikc({ + target: zod__rspack_import_3/* .string */.YjP().min(1), + message: zod__rspack_import_3/* .string */.YjP().min(1), + replyMode: zod__rspack_import_3/* ["enum"] */.k5n([ + "auto", + "manual" + ]).optional(), + hop: zod__rspack_import_3/* .number */.aig().int().min(0).optional(), + correlationId: id.optional(), + ...routeFields +}).strict(); +const bridgeStartSchema = zod__rspack_import_3/* .object */.Ikc({ + grokTarget: zod__rspack_import_3/* .string */.YjP().min(1), + codexThreadId: id.optional(), + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional(), + busyPolicy: zod__rspack_import_3/* ["enum"] */.k5n([ + "steer", + "reject" + ]).optional(), + requestId: id.optional() +}).strict(); +const bridgeStatusSchema = zod__rspack_import_3/* .object */.Ikc({ + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(100).optional() +}).strict(); +const bridgeStopSchema = zod__rspack_import_3/* .object */.Ikc({ + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + all: zod__rspack_import_3/* .boolean */.zMY().optional(), + worker: zod__rspack_import_3/* .boolean */.zMY().optional() +}).strict().refine((x)=>!!x.bindingId || x.all === true || x.worker === true, "Specify bindingId, all or worker"); +const respondSchema = zod__rspack_import_3/* .object */.Ikc({ + interactionId: zod__rspack_import_3/* .string */.YjP().min(1).max(512), + generation: id, + threadId: id, + turnId: id, + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + exchangeId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + decision: zod__rspack_import_3/* ["enum"] */.k5n([ + "accept", + "decline", + "cancel" + ]).optional(), + answersJson: zod__rspack_import_3/* .string */.YjP().min(2).max(65536).optional() +}).strict().refine((x)=>!!x.bindingId || !!x.exchangeId, "Binding or exchange scope required").refine((x)=>!!x.decision !== !!x.answersJson, "Supply decision or answersJson"); +const answersSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP().min(1).max(128), zod__rspack_import_3/* .object */.Ikc({ + answers: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP().max(8192)).max(20) +}).strict()); +const relayResultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +function nativeCodexThread(context) { + return context.host.state === "available" && (0,_agent_bundle_runtime__rspack_import_4/* .lineageHostFromClient */.bg)(context.host.value.name) === "codex" && context.lineage.state === "available" && context.lineage.source === "native" && context.lineage.value.resolution === "native" ? context.lineage.value.conversation : undefined; +} +function options(context) { + return { + pluginRoot: context?.plugin.state === "available" ? context.plugin.value.root : undefined, + signal: context?.signal + }; +} +function destination(input, context) { + const codexThreadId = input.codexThreadId ?? (context ? nativeCodexThread(context) : undefined); + // Native workspace evidence belongs to the invocation, not the plugin installation directory. + const workspace = context?.workspace; + const expectedCwd = input.expectedCwd ?? (workspace?.state === "available" && workspace.source === "native" ? workspace.value.root : undefined); + return { + codexThreadId, + expectedCwd + }; +} +async function grokSendOperation(input, context) { + const route = destination(input, input.bindingId ? undefined : context); + if (input.replyMode !== "manual" && (input.bindingId || route.codexThreadId)) return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)("sendToGrok", { + grokTarget: input.target, + message: input.message, + hop: input.hop, + correlationId: input.correlationId, + ...route, + ...input.bindingId ? { + bindingId: input.bindingId + } : {}, + ...input.requestId ? { + requestId: input.requestId + } : {} + }, options(context))); + if (input.replyMode === "auto") throw Error("Automatic reply delivery requires a native Codex source, codexThreadId or bindingId"); + const message = input.hop !== undefined || input.correlationId !== undefined ? (0,_codex_bridge_js__rspack_import_2/* .withEnvelopeHeader */.Mr)(input.message, (0,_codex_bridge_js__rspack_import_2/* .buildEnvelope */.nq)(input)) : input.message; + const sent = await (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(async ()=>(0,_gbot_js__rspack_import_1/* .sendPrompt */.LV)(await (0,_gbot_js__rspack_import_1/* .connectGateway */.Vq)(), input.target, message)); + return { + result: sent.result, + target: (0,_gbot_js__rspack_import_1/* .summarizeTarget */.rW)(sent.target), + delivery: sent.delivery === "accepted" ? "accepted" : "unknown", + ...sent.delivery === "accepted" && typeof sent.messageId === "string" ? { + messageId: sent.messageId + } : {}, + replyRoute: { + mode: "manual", + reason: input.replyMode === "manual" ? "requested" : "source-unavailable" + } + }; +} +async function bridgeOperation(method, input, context) { + let routed = method === "startBinding" ? { + ...input, + ...destination(input, context) + } : input; + if (method === "respond") { + const { decision, answersJson, ...scope } = respondSchema.parse(input); + routed = { + ...scope, + result: decision ? { + decision + } : { + answers: answersSchema.parse(JSON.parse(answersJson)) + } + }; + } + if (method === "startBinding" && !routed.codexThreadId) throw Error("Specify codexThreadId when native Codex source identity is unavailable"); + return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)(method, routed, options(context))); +} +function assertManagedSendOptions(input) { + if (input.expectedTurnId !== undefined) throw Error("Managed relay does not support expectedTurnId; omit it to use managed guarded steering, or use a plain Codex send for an explicit turn guard"); + if (input.replyTo !== undefined || input.envelope === true) throw Error("Managed relay does not support legacy replyTo/envelope options; omit them or use a plain send. Use hop/correlationId for explicit managed chains"); +} +async function codexReturnOperation(input, context) { + assertManagedSendOptions(input); + if (input.whenBusy === "queue") throw Error("Managed relay supports steer or reject, not experimental queue"); + return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)("sendToCodex", { + grokTarget: input.replyToGrok, + codexThreadId: input.threadId, + expectedCwd: input.expectedCwd, + bindingId: input.bindingId, + message: input.message, + requestId: input.requestId, + busyPolicy: input.whenBusy, + hop: input.hop, + correlationId: input.correlationId + }, options(context))); +} + +__webpack_require__.d(__webpack_exports__, { + MB: () => (assertManagedSendOptions), + bv: () => (grokSendOperation), + lt: () => (codexReturnOperation), + n1: () => (bridgeOperation) +}, { + Ax: relayResultSchema, + d5: bridgeStopSchema, + np: bridgeStatusSchema, + v1: respondSchema, + xD: bridgeStartSchema, + zK: routeFields +}); + + +}, +"./src/gbot.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_gateway_js__rspack_import_0 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _core_url_policy_js__rspack_import_1 = __webpack_require__("./src/core/url-policy.js"); + + + + + +// Hosts and the CLI print thrown error text (and stack), and a fetch or proxy failure can echo +// a credential. Rewrap with a redacted message; keep `name` and own fields such as `reason`, +// `delivery`, `mode`, and correlation ids so outcome documents still classify the failure. +const withRedactedErrors = async (run)=>{ + try { + return await run(); + } catch (error) { + const wrapped = new Error((0,_core_url_policy_js__rspack_import_1/* .redactSecrets */.fp)(error instanceof Error ? error.message : String(error))); + if (error instanceof Error) Object.assign(wrapped, error, { + name: error.name + }); + throw wrapped; + } +}; +const targetSchema = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP(), + kind: zod__rspack_import_2/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + name: zod__rspack_import_2/* .string */.YjP() +}); +const summarizeTarget = (record)=>({ + id: record.id, + kind: record.isGroup ? 'group' : 'bot', + name: record.name + }); +const entrySchema = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP(), + kind: zod__rspack_import_2/* .string */.YjP(), + role: zod__rspack_import_2/* .string */.YjP().optional(), + text: zod__rspack_import_2/* .string */.YjP(), + truncated: zod__rspack_import_2/* .boolean */.zMY(), + fullLength: zod__rspack_import_2/* .number */.aig().int().min(0), + timestampMs: zod__rspack_import_2/* .number */.aig().optional() +}); +const ENTRY_FULL_MAX = 20000; +const TRANSCRIPT_TOTAL_MAX = 200000; +// Metadata fields are capped too: an uncapped id/kind/role would bypass the total budget. +const ENTRY_META_MAX = 200; +const RECEIPT_CURSOR_MAX = 1024; +const entryFields = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP().default(''), + kind: zod__rspack_import_2/* .string */.YjP().default('message'), + role: zod__rspack_import_2/* .string */.YjP().optional(), + timestampMs: zod__rspack_import_2/* .number */.aig().optional() +}); +const capMeta = (value)=>value.length > ENTRY_META_MAX ? `${value.slice(0, ENTRY_META_MAX)}…` : value; +const threadEntry = (raw)=>{ + const fields = entryFields.safeParse(raw); + const full = entryText(raw); + const truncated = full.length > ENTRY_FULL_MAX; + const text = truncated ? full.slice(0, ENTRY_FULL_MAX) : full; + if (!fields.success) { + return { + id: '', + kind: 'unknown', + text, + truncated, + fullLength: full.length + }; + } + const { id, kind, role, timestampMs } = fields.data; + return { + id: capMeta(id), + kind: capMeta(kind), + ...role === undefined ? {} : { + role: capMeta(role) + }, + text, + truncated, + fullLength: full.length, + ...timestampMs === undefined ? {} : { + timestampMs + } + }; +}; +const metaLength = (entry)=>entry.id.length + entry.kind.length + (entry.role?.length ?? 0); +const transcriptEntries = (transcript)=>{ + const rows = unwrapEntries(transcript); + let remaining = TRANSCRIPT_TOTAL_MAX; + return rows.map((raw)=>{ + const entry = threadEntry(raw); + const allowText = Math.max(0, Math.min(entry.text.length, remaining - metaLength(entry))); + if (allowText < entry.text.length) { + entry.text = allowText <= 0 ? '' : entry.text.slice(0, allowText); + entry.truncated = entry.fullLength > entry.text.length; + } + remaining = Math.max(0, remaining - metaLength(entry) - entry.text.length); + return entry; + }); +}; + +__webpack_require__.d(__webpack_exports__, { + LV: () => (/* reexport safe */ _core_gateway_js__rspack_import_0.LV), + Vq: () => (/* reexport safe */ _core_gateway_js__rspack_import_0.Vq) +}, { + rW: summarizeTarget, + yF: withRedactedErrors +}); + + +}, +"node:async_hooks"(module) { + +module.exports = __rspack_external_node_async_hooks_4d8b1b4a; + + +}, +"node:child_process"(module) { + +module.exports = __rspack_external_node_child_process_cd435d64; + + +}, +"node:crypto"(module) { + +module.exports = __rspack_external_node_crypto_2e7c4b46; + + +}, +"node:fs"(module) { + +module.exports = __rspack_external_node_fs_1b05aee1; + + +}, +"node:fs/promises"(module) { + +module.exports = __rspack_external_node_fs_promises_3b710708; + + +}, +"node:net"(module) { + +module.exports = __rspack_external_node_net_5ed819e1; + + +}, +"node:os"(module) { + +module.exports = __rspack_external_node_os_4f3c9d58; + + +}, +"node:path"(module) { + +module.exports = __rspack_external_node_path_806ed179; + + +}, +"node:readline"(module) { + +module.exports = __rspack_external_node_readline_d8f53bef; + + +}, +"node:string_decoder"(module) { + +module.exports = __rspack_external_node_string_decoder_69b9bd04; + + +}, +"node:url"(module) { + +module.exports = __rspack_external_node_url_3991086a; + + +}, +"node:worker_threads"(module) { + +module.exports = __rspack_external_node_worker_threads_28ca7740; + + +}, +"async_hooks"(module) { +module.exports = __rspack_createRequire_require("async_hooks"); + +}, +"crypto"(module) { +module.exports = __rspack_createRequire_require("crypto"); + +}, +"stream"(module) { +module.exports = __rspack_createRequire_require("stream"); + +}, +"util"(module) { +module.exports = __rspack_createRequire_require("util"); + +}, +"./node_modules/@agent-bundle/runtime/dist/40.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_fs_promises__rspack_import_0 = __webpack_require__("node:fs/promises"); + + +const CODEX_ROLLOUT_HEAD_BYTES = 1048576; +const ROLLOUT_BASENAME = /rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\.jsonl$/iu; +const codexThreadFromRolloutPath = (path)=>{ + if (void 0 === path) return; + const match = ROLLOUT_BASENAME.exec(path); + return match?.[1]?.toLowerCase(); +}; +const record = (value)=>null === value || 'object' != typeof value || Array.isArray(value) ? void 0 : value; +const codex_rollout_text = (value)=>'string' == typeof value && '' !== value.trim() ? value : void 0; +const parseCodexRolloutMeta = (head)=>{ + const newline = head.indexOf('\n'); + const line = (-1 === newline ? head : head.slice(0, newline)).trim(); + if ('' === line) return; + let parsed; + try { + parsed = JSON.parse(line); + } catch { + return; + } + const item = record(parsed); + if (item?.['type'] !== 'session_meta') return; + const payload = record(item['payload']); + const thread = codex_rollout_text(payload?.['id']); + if (void 0 === payload || void 0 === thread) return; + const root = codex_rollout_text(payload['session_id']); + const source = record(payload['source']); + const subagent = record(source?.['subagent']); + if (void 0 === subagent) { + const kind = codex_rollout_text(source?.['subagent']); + return { + ...void 0 === kind ? {} : { + subagentKind: kind + }, + ...void 0 === root ? {} : { + root + }, + thread + }; + } + const [subagentKind] = Object.keys(subagent); + const spawn = record(subagent['thread_spawn']); + const parent = codex_rollout_text(spawn?.['parent_thread_id']) ?? codex_rollout_text(payload['parent_thread_id']); + const rawDepth = spawn?.['depth']; + const depth = 'number' == typeof rawDepth && Number.isInteger(rawDepth) && rawDepth > 0 ? rawDepth : void 0; + const agentPath = codex_rollout_text(spawn?.['agent_path']) ?? codex_rollout_text(payload['agent_path']); + return { + ...void 0 === agentPath ? {} : { + agentPath + }, + ...void 0 === depth ? {} : { + depth + }, + ...void 0 === parent ? {} : { + parent + }, + ...void 0 === root ? {} : { + root + }, + ...void 0 === subagentKind ? {} : { + subagentKind + }, + thread + }; +}; +const readCodexRolloutHead = async (path)=>{ + let handle; + try { + handle = await promises_open(path, 'r'); + const buffer = Buffer.allocUnsafe(CODEX_ROLLOUT_HEAD_BYTES); + let filled = 0; + while(filled < buffer.length){ + const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled); + if (0 === bytesRead) break; + const newline = buffer.subarray(filled, filled + bytesRead).indexOf(0x0a); + if (-1 !== newline) { + filled += newline; + break; + } + filled += bytesRead; + } + return buffer.subarray(0, filled).toString('utf8'); + } catch { + return; + } finally{ + await handle?.close().catch(()=>void 0); + } +}; +const readCodexSpawnLineage = async (path, thread, read = readCodexRolloutHead)=>{ + if (void 0 === path) return; + const head = await read(path); + if (void 0 === head) return; + const meta = parseCodexRolloutMeta(head); + if (void 0 === meta || meta.thread !== thread || void 0 === meta.parent || void 0 === meta.depth) return; + return { + ...meta, + depth: meta.depth, + parent: meta.parent + }; +}; +const nativeString = (native, key)=>{ + const value = native[key]; + return 'string' == typeof value && '' !== value.trim() ? value : void 0; +}; +const lineageHostFromClient = (clientName)=>{ + if (void 0 === clientName) return; + if (clientName.startsWith('claude')) return 'claude'; + if (clientName.startsWith('codex')) return 'codex'; + if (clientName.startsWith('cursor')) return 'cursor'; +}; +const lineageCarrier = (host, native)=>{ + switch(host){ + case 'claude': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'prompt_id'), + root: nativeString(native, 'session_id') + }; + case 'codex': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'turn_id'), + root: nativeString(native, 'session_id') + }; + case 'cursor': + return { + conversation: nativeString(native, 'conversation_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'generation_id'), + root: void 0 + }; + default: + { + const unreachable = host; + throw new Error(`Unhandled lineage host ${String(unreachable)}`); + } + } +}; +const resolveNativeLineage = (host, native)=>{ + const carrier = lineageCarrier(host, native); + if ('cursor' === host || void 0 === carrier.conversation || void 0 === carrier.root) return unavailable('no-shared-runtime'); + if (carrier.conversation !== carrier.root) return unavailable('no-shared-runtime'); + return available({ + conversation: carrier.root, + depth: 0, + ...void 0 === carrier.generation ? {} : { + generation: carrier.generation + }, + resolution: 'native', + root: carrier.root + }, 'native'); +}; +const resolveStandaloneLineage = async (host, native, read)=>{ + const fromPayload = resolveNativeLineage(host, native); + if ('codex' !== host || 'available' === fromPayload.state) return fromPayload; + const carrier = lineageCarrier(host, native); + if (void 0 === carrier.conversation || void 0 === carrier.root) return fromPayload; + const ownRollout = 'SubagentStop' === nativeString(native, 'hook_event_name') ? nativeString(native, "agent_transcript_path") : nativeString(native, "transcript_path"); + const spawn = await readCodexSpawnLineage(ownRollout, carrier.conversation, read); + if (void 0 === spawn) return fromPayload; + const type = nativeString(native, 'agent_type'); + return available({ + conversation: carrier.conversation, + depth: spawn.depth, + ...void 0 === carrier.generation ? {} : { + generation: carrier.generation + }, + parent: spawn.parent, + resolution: "transcript", + root: carrier.root, + subagent: { + id: carrier.conversation, + ...void 0 === type ? {} : { + type + } + } + }, 'derived'); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + bg: lineageHostFromClient +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/49.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_2 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_3 = __webpack_require__("node:path"); +/* import */ var _736_js__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); + + + + + +const PLUGIN_ROOT_ENV_ANCHOR = 'AGENT_BUNDLE_PLUGIN_ROOT'; +const PLUGIN_STATE_ROOT_ENV_ANCHOR = 'AGENT_BUNDLE_STATE_ROOT'; +const PLUGIN_STATE_DIRECTORY = 'state'; +const unexpandedToken = /\$\{[^}]*\}/u; +const defaultWarn = (message)=>{ + process.stderr.write(`${message}\n`); +}; +const safePluginSegment = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/u; +const pluginStateSegment = (root)=>{ + const canonicalRoot = (0,node_fs__rspack_import_1.existsSync)(root) ? (0,node_fs__rspack_import_1.realpathSync)(root) : (0,node_path__rspack_import_3.resolve)(root); + const digest = (0,node_crypto__rspack_import_0.createHash)('sha256').update(canonicalRoot).digest('hex').slice(0, 16); + const name = (0,node_path__rspack_import_3.basename)(canonicalRoot); + return safePluginSegment.test(name) ? `${name}-${digest}` : `plugin-${digest}`; +}; +const userStateHome = (env = process.env, home = (0,node_os__rspack_import_2.homedir)())=>{ + const xdgStateHome = env.XDG_STATE_HOME ?? ''; + return (0,node_path__rspack_import_3.isAbsolute)(xdgStateHome) ? (0,node_path__rspack_import_3.join)(xdgStateHome, 'agent-bundle') : (0,node_path__rspack_import_3.join)(home, '.agent-bundle', PLUGIN_STATE_DIRECTORY); +}; +const userDataStateRoot = (root, env, home)=>(0,node_path__rspack_import_3.join)(userStateHome(env, home), pluginStateSegment(root)); +const resolvePluginRoot = (options)=>{ + const env = options.env ?? process.env; + const declared = env[PLUGIN_ROOT_ENV_ANCHOR] ?? ''; + let root; + let source; + if ('' === declared.trim()) { + root = (0,node_path__rspack_import_3.resolve)(options.fallback); + source = 'derived'; + } else if (unexpandedToken.test(declared)) { + (options.warn ?? defaultWarn)(`[agent-bundle] ${PLUGIN_ROOT_ENV_ANCHOR} is the unexpanded token ${JSON.stringify(declared)}; anchoring the plugin on ${(0,node_path__rspack_import_3.resolve)(options.fallback)} instead.`); + root = (0,node_path__rspack_import_3.resolve)(options.fallback); + source = 'derived'; + } else { + root = (0,node_path__rspack_import_3.resolve)(declared); + source = 'native'; + } + const derivedStateRoot = 'user-data' === options.stateAnchor ? userDataStateRoot(root, env, options.home) : (0,node_path__rspack_import_3.join)(root, PLUGIN_STATE_DIRECTORY); + const declaredStateRoot = env[PLUGIN_STATE_ROOT_ENV_ANCHOR] ?? ''; + let stateRoot; + let stateSource; + if ('' === declaredStateRoot.trim()) { + stateRoot = derivedStateRoot; + stateSource = 'derived'; + } else if (unexpandedToken.test(declaredStateRoot)) { + (options.warn ?? defaultWarn)(`[agent-bundle] ${PLUGIN_STATE_ROOT_ENV_ANCHOR} is the unexpanded token ${JSON.stringify(declaredStateRoot)}; anchoring state on ${derivedStateRoot} instead.`); + stateRoot = derivedStateRoot; + stateSource = 'derived'; + } else { + stateRoot = (0,node_path__rspack_import_3.resolve)(declaredStateRoot); + stateSource = 'native'; + } + return Object.freeze({ + identity: (0,_736_js__rspack_import_4/* .available */.qC)({ + root, + stateRoot + }, source), + root, + source, + stateRoot, + stateSource + }); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + E7: resolvePluginRoot +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/506.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var react__rspack_import_0 = __webpack_require__("./node_modules/react/react.react-server.js"); + +const AgentResult = ({ children, metadata, value })=>(0,react__rspack_import_0.createElement)('agent-result', { + metadata, + value + }, children); +const AgentMarkdown = ({ children })=>(0,react__rspack_import_0.createElement)('agent-markdown', null, children); +const AgentText = ({ children })=>(0,react__rspack_import_0.createElement)('agent-text', null, children); +const AgentContext = ({ children })=>(0,react__rspack_import_0.createElement)('agent-context', null, children); +const AgentJson = ({ value })=>(0,react__rspack_import_0.createElement)('agent-json', { + value + }); +const AgentProgress = ({ completed, message, total })=>(0,react__rspack_import_0.createElement)('agent-progress', { + completed, + message, + total + }); +const AgentImage = ({ data, mimeType })=>(0,react__rspack_import_0.createElement)('agent-image', { + data, + mimeType + }); +const AgentAudio = ({ data, mimeType })=>(0,react__rspack_import_0.createElement)('agent-audio', { + data, + mimeType + }); +const AgentResource = ({ mimeType, name, uri })=>(0,react__rspack_import_0.createElement)('agent-resource', { + mimeType, + name, + uri + }); +const AgentError = ({ children, code })=>(0,react__rspack_import_0.createElement)('agent-error', { + code + }, children); +const Agent = Object.freeze({ + Audio: AgentAudio, + Context: AgentContext, + Error: AgentError, + Image: AgentImage, + Json: AgentJson, + Markdown: AgentMarkdown, + Progress: AgentProgress, + Resource: AgentResource, + Result: AgentResult, + Text: AgentText +}); +const Result = ({ children })=>createElement('agent-hook-result', null, children); +const AdditionalContext = ({ children })=>createElement('agent-hook-additional-context', null, children); +const Hook = (/* unused pure expression or super */ null && ({ + AdditionalContext: AdditionalContext, + Result: Result +})); +const McpResult = ({ _meta, children, isError, structuredContent })=>createElement('mcp-result', { + _meta, + isError, + structuredContent + }, children); +const McpText = ({ children })=>createElement('mcp-text', null, children); +const McpImage = ({ data, mimeType })=>createElement('mcp-image', { + data, + mimeType + }); +const McpAudio = ({ data, mimeType })=>createElement('mcp-audio', { + data, + mimeType + }); +const McpResourceLink = ({ mimeType, name, uri })=>createElement('mcp-resource-link', { + mimeType, + name, + uri + }); +const McpEmbeddedResource = ({ blob, children, mimeType, text, uri })=>createElement('mcp-embedded-resource', { + blob, + mimeType, + text, + uri + }, children); +const Mcp = (/* unused pure expression or super */ null && ({ + Audio: McpAudio, + EmbeddedResource: McpEmbeddedResource, + Image: McpImage, + ResourceLink: McpResourceLink, + Result: McpResult, + Text: McpText +})); + + +__webpack_require__.d(__webpack_exports__, { +}, { + g6: Agent +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/707.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +const EMPTY_FLIGHT_MANIFEST = Object.freeze({ + clientManifest: Object.freeze({}), + moduleLoading: null, + serverConsumerModuleMap: null, + serverManifest: Object.freeze({}) +}); +const ensureAgentFlightManifest = ()=>{ + const scope = globalThis; + if (void 0 !== scope.__rspack_rsc_manifest__) return; + scope.__rspack_rsc_manifest__ = EMPTY_FLIGHT_MANIFEST; +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + n: ensureAgentFlightManifest +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/736.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_async_hooks__rspack_import_0 = __webpack_require__("node:async_hooks"); + +const AGENT_REQUEST_STORE_VERSION = 6; +const STORE_SYMBOL = Symbol.for('@agent-bundle/runtime/request-store'); +class AgentRequestError extends Error { + code; + constructor(code, message){ + super(message); + this.code = code; + this.name = 'AgentRequestError'; + } +} +const freezeValue = (value)=>{ + if (Array.isArray(value)) return Object.freeze(value.map((item)=>freezeValue(item))); + if (null !== value && 'object' == typeof value && Object.getPrototypeOf(value) === Object.prototype) { + const copy = {}; + for (const [key, nested] of Object.entries(value))copy[key] = freezeValue(nested); + return Object.freeze(copy); + } + return value; +}; +const available = (value, source)=>Object.freeze({ + source, + state: 'available', + value: freezeValue(value) + }); +const unavailable = (reason = 'not-provided')=>Object.freeze({ + reason, + state: 'unavailable' + }); +const snapshotObserved = (observed)=>'available' === observed.state ? available(observed.value, observed.source) : unavailable(observed.reason); +const silentProgress = Object.freeze({ + report: async ()=>void 0 +}); +const emptyCapabilities = ()=>Object.freeze({ + command: unavailable(), + filesystem: unavailable(), + network: unavailable(), + projectRoot: unavailable() + }); +const snapshotCapabilities = (capabilities)=>Object.freeze({ + command: snapshotObserved(capabilities.command), + filesystem: snapshotObserved(capabilities.filesystem), + network: snapshotObserved(capabilities.network), + projectRoot: snapshotObserved(capabilities.projectRoot) + }); +const optionalText = (value)=>{ + if (void 0 === value) return; + if ('' === value.trim()) throw new AgentRequestError('invalid-invocation', 'Agent invocation fields must be non-empty when present'); + return value; +}; +const invocationFrom = (input)=>Object.freeze({ + id: optionalText(input.id) ?? crypto.randomUUID(), + kind: input.kind, + startedAt: optionalText(input.startedAt) ?? new Date().toISOString(), + ...void 0 === input.artifactEpoch ? {} : { + artifactEpoch: optionalText(input.artifactEpoch) + }, + ...void 0 === input.hostContractRevision ? {} : { + hostContractRevision: optionalText(input.hostContractRevision) + }, + ...void 0 === input.operationId ? {} : { + operationId: optionalText(input.operationId) + }, + ...void 0 === input.protocolRevision ? {} : { + protocolRevision: optionalText(input.protocolRevision) + }, + ...void 0 === input.sourceRevision ? {} : { + sourceRevision: optionalText(input.sourceRevision) + }, + ...void 0 === input.surface ? {} : { + surface: optionalText(input.surface) + } + }); +class Lease { + values; + closed = false; + handle; + constructor(values){ + this.values = values; + this.handle = createHandle(this); + } +} +const realm = globalThis; +const getStore = ()=>{ + const existing = realm[STORE_SYMBOL]; + if (void 0 !== existing) { + if (existing.version !== AGENT_REQUEST_STORE_VERSION) throw new AgentRequestError('store-version-conflict', `Incompatible @agent-bundle/runtime request store version: found ${String(existing.version)}, expected ${String(AGENT_REQUEST_STORE_VERSION)}`); + return existing; + } + const created = { + storage: new node_async_hooks__rspack_import_0.AsyncLocalStorage(), + version: AGENT_REQUEST_STORE_VERSION + }; + realm[STORE_SYMBOL] = created; + return created; +}; +const agent_request_open = (lease)=>{ + if (lease.closed) throw new AgentRequestError('request-closed', 'agent() used after the request completed'); + return lease.values; +}; +const createHandle = (lease)=>Object.freeze({ + get invocation () { + return agent_request_open(lease).invocation; + }, + get host () { + return agent_request_open(lease).host; + }, + get session () { + return agent_request_open(lease).session; + }, + get actor () { + return agent_request_open(lease).actor; + }, + get workspace () { + return agent_request_open(lease).workspace; + }, + get plugin () { + return agent_request_open(lease).plugin; + }, + get lineage () { + return agent_request_open(lease).lineage; + }, + get terminal () { + return agent_request_open(lease).terminal; + }, + get capabilities () { + return agent_request_open(lease).capabilities; + }, + get progress () { + return agent_request_open(lease).progress; + }, + get signal () { + return agent_request_open(lease).signal; + }, + get services () { + return agent_request_open(lease).services; + }, + get process () { + return agent_request_open(lease).process; + }, + async provider (key) { + const values = agent_request_open(lease); + values.signal.throwIfAborted(); + const value = await values.provider(key); + agent_request_open(lease).signal.throwIfAborted(); + return value; + }, + get state () { + return agent_request_open(lease).state; + }, + get notices () { + return agent_request_open(lease).notices; + } + }); +const currentLease = ()=>{ + const lease = getStore().storage.getStore(); + if (void 0 === lease) throw new AgentRequestError('outside-invocation', 'agent() used outside a real invocation'); + return lease; +}; +const currentAgentRequest = ()=>{ + const lease = getStore().storage.getStore(); + return void 0 === lease || lease.closed ? void 0 : lease.handle; +}; +const agent = async ()=>{ + const lease = currentLease(); + agent_request_open(lease); + return lease.handle; +}; +const useAgent = ()=>{ + const lease = currentLease(); + agent_request_open(lease); + return lease.handle; +}; +const runAgentRequest = async (init, operation)=>{ + const actor = snapshotObserved(init.actor ?? unavailable()); + const host = snapshotObserved(init.host ?? unavailable()); + const invocation = invocationFrom(init.invocation); + const lineage = snapshotObserved(init.lineage ?? unavailable()); + const plugin = snapshotObserved(init.plugin ?? unavailable()); + const session = snapshotObserved(init.session ?? unavailable()); + const signal = init.signal ?? new AbortController().signal; + const terminal = snapshotObserved(init.terminal ?? unavailable()); + const workspace = snapshotObserved(init.workspace ?? unavailable()); + const noticeLease = void 0 === init.noticeLedger ? void 0 : await init.noticeLedger.openRequest({ + invocation, + principal: Object.freeze({ + actor, + host, + lineage, + session, + workspace + }), + signal + }); + try { + const providers = 'function' == typeof init.providers ? await resolveProvidersDetached(init.providers, providerRequest({ + host, + lineage, + notices: noticeLease?.handle, + plugin, + session, + signal, + state: init.state, + workspace + })) : init.providers; + const providerPromises = new Map(); + const request = providerRequest({ + host, + lineage, + notices: noticeLease?.handle, + plugin, + session, + signal, + state: init.state, + workspace + }); + const values = Object.freeze({ + provider: (key)=>{ + let pending = providerPromises.get(key); + if (void 0 === pending) { + pending = getStore().storage.exit(async ()=>{ + if (void 0 !== providers && Object.hasOwn(providers, key)) return providers[key]; + if (void 0 === init.resolveProvider) throw new TypeError(`Unknown provider ${JSON.stringify(key)}.`); + return init.resolveProvider(key, request); + }); + providerPromises.set(key, pending); + } + return pending; + }, + actor, + capabilities: snapshotCapabilities(init.capabilities ?? emptyCapabilities()), + host, + invocation, + lineage, + notices: noticeLease?.handle, + plugin, + progress: init.progress ?? silentProgress, + process: void 0 === init.process ? void 0 : Object.freeze({ + ...init.process + }), + services: Object.freeze({ + ...init.services ?? {} + }), + session, + signal, + state: init.state, + terminal, + workspace + }); + const lease = new Lease(values); + try { + return await getStore().storage.run(lease, operation); + } finally{ + lease.closed = true; + } + } finally{ + noticeLease?.close(); + } +}; +const resolveProvidersDetached = (resolver, request)=>getStore().storage.exit(async ()=>resolver(request)); +const providerRequest = ({ notices, state, ...axes })=>Object.freeze({ + ...axes, + ...void 0 === notices ? {} : { + notices: Object.freeze({ + inbox: ()=>notices.inbox(), + published: ()=>notices.published() + }) + }, + ...void 0 === state ? {} : { + state: Object.freeze({ + lifetime: state.lifetime, + read: (options)=>state.read(options) + }) + } + }); + + +__webpack_require__.d(__webpack_exports__, { +}, { + MA: agent, + hU: unavailable, + iC: runAgentRequest, + qC: available +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/flight/server.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var react_server_dom_rspack_server_node__rspack_import_0 = __webpack_require__("./node_modules/react-server-dom-rspack/server.node.js"); +/* import */ var _707_js__rspack_import_1 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/707.js"); + + +const abortError = ()=>new DOMException('Agent render was aborted', 'AbortError'); +const renderAgentFlight = (model, options = {})=>{ + if (options.signal?.aborted) throw abortError(); + (0,_707_js__rspack_import_1/* .ensureAgentFlightManifest */.n)(); + const flight = (0,react_server_dom_rspack_server_node__rspack_import_0/* .renderToReadableStream */.WK)(model, { + ...void 0 === options.onError ? {} : { + onError: options.onError + } + }); + if (void 0 === options.signal) return flight; + return flight.pipeThrough(new TransformStream(), { + signal: options.signal + }); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + y: renderAgentFlight +}); + + +}, +"./node_modules/zod/v4/classic/errors.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_index_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/errors.js"); +/* import */ var _core_index_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _core_util_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const initializer = (inst, issues) => { + _core_index_js__rspack_import_0/* .$ZodError.init */.a$.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => _core_index_js__rspack_import_0/* .formatError */.Wk(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => _core_index_js__rspack_import_0/* .flattenError */.JM(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, _core_util_js__rspack_import_1/* .jsonStringifyReplacer */.k8, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, _core_util_js__rspack_import_1/* .jsonStringifyReplacer */.k8, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", initializer))); +const ZodRealError = /*@__PURE__*/ _core_index_js__rspack_import_2/* .$constructor */.xI("ZodError", initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + +__webpack_require__.d(__webpack_exports__, { +}, { + g: ZodRealError +}); + + +}, +"./node_modules/zod/v4/classic/parse.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_index_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/parse.js"); +/* import */ var _errors_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/classic/errors.js"); + + +const parse = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._parse */.Tj(_errors_js__rspack_import_1/* .ZodRealError */.g); +const parseAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._parseAsync */.Rb(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeParse = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeParse */.Od(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeParseAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeParseAsync */.wG(_errors_js__rspack_import_1/* .ZodRealError */.g); + +// Codec functions +const encode = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._encode */.Mv(_errors_js__rspack_import_1/* .ZodRealError */.g); +const decode = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._decode */.e2(_errors_js__rspack_import_1/* .ZodRealError */.g); +const encodeAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._encodeAsync */.GW(_errors_js__rspack_import_1/* .ZodRealError */.g); +const decodeAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._decodeAsync */.or(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeEncode = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeEncode */.rh(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeDecode = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeDecode */.VS(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeEncodeAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeEncodeAsync */.v_(_errors_js__rspack_import_1/* .ZodRealError */.g); +const safeDecodeAsync = /* @__PURE__ */ _core_index_js__rspack_import_0/* ._safeDecodeAsync */.R3(_errors_js__rspack_import_1/* .ZodRealError */.g); + +__webpack_require__.d(__webpack_exports__, { +}, { + D4: decode, + EJ: parseAsync, + EM: safeEncodeAsync, + Re: decodeAsync, + X$: encodeAsync, + bp: safeParseAsync, + ex: safeDecode, + lF: encode, + qg: parse, + wy: safeEncode, + xL: safeParse, + yR: safeDecodeAsync +}); + + +}, +"./node_modules/zod/v4/classic/schemas.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_index_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _core_index_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/memoizer.js"); +/* import */ var _core_index_js__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/core/schemas.js"); +/* import */ var _core_index_js__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/core/util.js"); +/* import */ var _core_index_js__rspack_import_6 = __webpack_require__("./node_modules/zod/v4/core/registries.js"); +/* import */ var _checks_js__rspack_import_5 = __webpack_require__("./node_modules/zod/v4/core/api.js"); +/* import */ var _core_json_schema_processors_js__rspack_import_10 = __webpack_require__("./node_modules/zod/v4/core/json-schema-processors.js"); +/* import */ var _core_to_json_schema_js__rspack_import_7 = __webpack_require__("./node_modules/zod/v4/core/to-json-schema.js"); +/* import */ var _locales_en_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/locales/en.js"); +/* import */ var _parse_js__rspack_import_8 = __webpack_require__("./node_modules/zod/v4/classic/parse.js"); +/* import */ var _parse_js__rspack_import_9 = __webpack_require__("./node_modules/zod/v4/core/parse.js"); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!_core_index_js__rspack_import_0/* .globalConfig.localeError */.cr.localeError) + _core_index_js__rspack_import_0/* .config */.$W((0,_locales_en_js__rspack_import_1/* ["default"] */.A)()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!_core_index_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer) + _core_index_js__rspack_import_0/* .config */.$W({ memoizer: _core_index_js__rspack_import_2/* .memoizer */.x3() }); +} +const ZodType = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodType", (inst, def) => { + _ensureDefaultLocale(); + _core_index_js__rspack_import_3/* .$ZodType.init */.W4.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return _core_index_js__rspack_import_4/* .clone */.o8(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_checks_js__rspack_import_5/* ._overwrite */.bS(fn)); + }, + optional() { + return optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return array(this); + }, + or(arg) { + return union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return _default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return _catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + _core_index_js__rspack_import_6/* .globalRegistry.add */.fd.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return _core_index_js__rspack_import_6/* .globalRegistry.get */.fd.get(this); + const cl = this.clone(); + _core_index_js__rspack_import_6/* .globalRegistry.add */.fd.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return _core_index_js__rspack_import_4/* .hide */.jD(this, "~standard", { + ..._core_index_js__rspack_import_3/* .standardProps */.YK(this), + jsonSchema: { + input: (0,_core_to_json_schema_js__rspack_import_7/* .createStandardJSONSchemaMethod */.uE)(this, "input"), + output: (0,_core_to_json_schema_js__rspack_import_7/* .createStandardJSONSchemaMethod */.uE)(this, "output"), + }, + }); + }, + set "~standard"(value) { + _core_index_js__rspack_import_4/* .own */.qh(this, "~standard", value); + }, + parse: function _parse(data, params) { + return _parse_js__rspack_import_8/* .parse */.qg(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await _parse_js__rspack_import_8/* .parseAsync */.EJ(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return _parse_js__rspack_import_8/* .safeParse */.xL(this, data, params); + }, + async safeParseAsync(data, params) { + return _parse_js__rspack_import_8/* .safeParseAsync */.bp(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + _core_index_js__rspack_import_4/* .own */.qh(this, "spa", value); + }, + validate(data, params) { + return _parse_js__rspack_import_9/* .validate */.tf(this, data, params); + }, + validateAsync(data, params) { + return _parse_js__rspack_import_9/* .validateAsync */.F0(this, data, params); + }, + encode: function _encode(data, params) { + return _parse_js__rspack_import_8/* .encode */.lF(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return _parse_js__rspack_import_8/* .decode */.D4(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await _parse_js__rspack_import_8/* .encodeAsync */.X$(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await _parse_js__rspack_import_8/* .decodeAsync */.Re(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return _parse_js__rspack_import_8/* .safeEncode */.wy(this, data, params); + }, + safeDecode(data, params) { + return _parse_js__rspack_import_8/* .safeDecode */.ex(this, data, params); + }, + async safeEncodeAsync(data, params) { + return _parse_js__rspack_import_8/* .safeEncodeAsync */.EM(this, data, params); + }, + async safeDecodeAsync(data, params) { + return _parse_js__rspack_import_8/* .safeDecodeAsync */.yR(this, data, params); + }, + toJSONSchema(params) { + return (0,_core_to_json_schema_js__rspack_import_7/* .createToJSONSchemaMethod */.OA)(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return _core_index_js__rspack_import_6/* .globalRegistry */.fd.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("_ZodString", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodString.init */.$v.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .stringProcessor */.SW(inst, ctx, json, params); +}, +/*@__PURE__*/ _core_index_js__rspack_import_4/* .derived */.un({ + format: (inst) => _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst).format ?? null, + minLength: (inst) => _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst).minimum ?? null, + maxLength: (inst) => _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst).maximum ?? null, +}, { + regex(...args) { + return this.check(_checks_js__rspack_import_5/* ._regex */.Fk(...args)); + }, + includes(...args) { + return this.check(_checks_js__rspack_import_5/* ._includes */.dR(...args)); + }, + startsWith(...args) { + return this.check(_checks_js__rspack_import_5/* ._startsWith */.$S(...args)); + }, + endsWith(...args) { + return this.check(_checks_js__rspack_import_5/* ._endsWith */.ER(...args)); + }, + min(...args) { + return this.check(_checks_js__rspack_import_5/* ._minLength */.m9(...args)); + }, + max(...args) { + return this.check(_checks_js__rspack_import_5/* ._maxLength */.Eb(...args)); + }, + length(...args) { + return this.check(_checks_js__rspack_import_5/* ._length */.YA(...args)); + }, + nonempty(...args) { + return this.check(_checks_js__rspack_import_5/* ._minLength */.m9(1, ...args)); + }, + lowercase(params) { + return this.check(_checks_js__rspack_import_5/* ._lowercase */.hH(params)); + }, + uppercase(params) { + return this.check(_checks_js__rspack_import_5/* ._uppercase */.qF(params)); + }, + trim() { + return this.check(_checks_js__rspack_import_5/* ._trim */.WN()); + }, + normalize(...args) { + return this.check(_checks_js__rspack_import_5/* ._normalize */.lo(...args)); + }, + toLowerCase() { + return this.check(_checks_js__rspack_import_5/* ._toLowerCase */.Il()); + }, + toUpperCase() { + return this.check(_checks_js__rspack_import_5/* ._toUpperCase */.xY()); + }, + slugify() { + return this.check(_checks_js__rspack_import_5/* ._slugify */.TL()); + }, +})); +const ZodString = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodString", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodString.init */.$v.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_checks_js__rspack_import_5/* ._email */.Mu(ZodEmail, params)); + }, + url(params) { + return this.check(_checks_js__rspack_import_5/* ._url */.Fn(ZodURL, params)); + }, + jwt(params) { + return this.check(_checks_js__rspack_import_5/* ._jwt */.rk(ZodJWT, params)); + }, + emoji(params) { + return this.check(_checks_js__rspack_import_5/* ._emoji */.aC(ZodEmoji, params)); + }, + guid(params) { + return this.check(_checks_js__rspack_import_5/* ._guid */.tB(ZodGUID, params)); + }, + uuid(params) { + return this.check(_checks_js__rspack_import_5/* ._uuid */.Be(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_checks_js__rspack_import_5/* ._uuidv4 */.nA(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_checks_js__rspack_import_5/* ._uuidv6 */.pY(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_checks_js__rspack_import_5/* ._uuidv7 */.wA(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_checks_js__rspack_import_5/* ._nanoid */.Dl(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_checks_js__rspack_import_5/* ._cuid */.fs(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_checks_js__rspack_import_5/* ._cuid2 */.Bj(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_checks_js__rspack_import_5/* ._ulid */.Ct(ZodULID, params)); + }, + base64(params) { + return this.check(_checks_js__rspack_import_5/* ._base64 */.rt(ZodBase64, params)); + }, + base64url(params) { + return this.check(_checks_js__rspack_import_5/* ._base64url */.cU(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_checks_js__rspack_import_5/* ._xid */.Pw(ZodXID, params)); + }, + ksuid(params) { + return this.check(_checks_js__rspack_import_5/* ._ksuid */._z(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_checks_js__rspack_import_5/* ._ipv4 */.Ny(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_checks_js__rspack_import_5/* ._ipv6 */.$O(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_checks_js__rspack_import_5/* ._cidrv4 */.Uy(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_checks_js__rspack_import_5/* ._cidrv6 */.gP(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_checks_js__rspack_import_5/* ._e164 */.KB(ZodE164, params)); + }, + datetime(params) { + return this.check(_checks_js__rspack_import_5/* ._isoDateTime */.G1(ZodISODateTime, params)); + }, + date(params) { + return this.check(_checks_js__rspack_import_5/* ._isoDate */.db(ZodISODate, params)); + }, + time(params) { + return this.check(_checks_js__rspack_import_5/* ._isoTime */.Kn(ZodISOTime, params)); + }, + duration(params) { + return this.check(_checks_js__rspack_import_5/* ._isoDuration */.f2(ZodISODuration, params)); + }, +}); +function string(params) { + return _checks_js__rspack_import_5/* ._string */.Rl(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodStringFormat", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodStringFormat.init */.EY.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodISODateTime", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodISODateTime.init */.Ko.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodISODate", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodISODate.init */.v1.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISOTime = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodISOTime", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodISOTime.init */.Ax.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODuration = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodISODuration", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodISODuration.init */.$N.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodEmail.init */.qG.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function email(params) { + return core._email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodGUID.init */.Zc.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodUUID.init */.Zn.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodURL.init */.VY.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function url(params) { + return core._url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: regexes.httpProtocol, + hostname: regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodEmoji.init */.cG.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodNanoID.init */.Py.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodCUID.init */.bl.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodCUID2.init */.Zu.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodULID.init */.g5.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodXID.init */.TF.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodKSUID.init */.GY.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodIPv4.init */.Lc.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodIPv6.init */.Zy.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCIDRv4", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodCIDRv4.init */.CI.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCIDRv6", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodCIDRv6.init */.Cn.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodBase64.init */.Dq.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodBase64URL.init */.CQ.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodE164.init */.Oy.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodIBAN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodIBAN", (inst, def) => { + core.$ZodIBAN.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function iban(params) { + return core._iban(ZodIBAN, params); +} +const ZodJWT = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + _core_index_js__rspack_import_3/* .$ZodJWT.init */.h8.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", regexes.hostname, _params); +} +function hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", regexes.hex, _params); +} +function currencyCode(_params) { + return core._stringFormat(ZodCustomStringFormat, "currency_code", regexes.currencyCode, _params); +} +function hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNumber", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNumber.init */.vz.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .numberProcessor */.Wg(inst, ctx, json, params); + inst.isFinite = true; +}, +/*@__PURE__*/ _core_index_js__rspack_import_4/* .derived */.un({ + minValue: (inst) => { + const { minimum, exclusiveMinimum } = _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst); + return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY); + }, + maxValue: (inst) => { + const { maximum, exclusiveMaximum } = _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst); + return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY); + }, + isInt: (inst) => { + const { isInt, multipleOf } = _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst); + return !!isInt || !!multipleOf?.some(Number.isSafeInteger); + }, + format: (inst) => _core_json_schema_processors_js__rspack_import_10/* .aggregateChecks */.Fs(inst).format ?? null, +}, { + gt(value, params) { + return this.check(_checks_js__rspack_import_5/* ._gt */.Tx(value, params)); + }, + gte(value, params) { + return this.check(_checks_js__rspack_import_5/* ._gte */.qm(value, params)); + }, + min(value, params) { + return this.check(_checks_js__rspack_import_5/* ._gte */.qm(value, params)); + }, + lt(value, params) { + return this.check(_checks_js__rspack_import_5/* ._lt */.Au(value, params)); + }, + lte(value, params) { + return this.check(_checks_js__rspack_import_5/* ._lte */.Zm(value, params)); + }, + max(value, params) { + return this.check(_checks_js__rspack_import_5/* ._lte */.Zm(value, params)); + }, + int(params) { + return this.check(int(params)); + }, + safe(params) { + return this.check(int(params)); + }, + positive(params) { + return this.check(_checks_js__rspack_import_5/* ._gt */.Tx(0, params)); + }, + nonnegative(params) { + return this.check(_checks_js__rspack_import_5/* ._gte */.qm(0, params)); + }, + negative(params) { + return this.check(_checks_js__rspack_import_5/* ._lt */.Au(0, params)); + }, + nonpositive(params) { + return this.check(_checks_js__rspack_import_5/* ._lte */.Zm(0, params)); + }, + multipleOf(value, params) { + return this.check(_checks_js__rspack_import_5/* ._multipleOf */.Hi(value, params)); + }, + step(value, params) { + return this.check(_checks_js__rspack_import_5/* ._multipleOf */.Hi(value, params)); + }, + finite() { + return this; + }, +})); +function number(params) { + return _checks_js__rspack_import_5/* ._number */.F7(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNumberFormat", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNumberFormat.init */.I.init(inst, def); + ZodNumber.init(inst, def); +}); +function int(params) { + return _checks_js__rspack_import_5/* ._int */.LK(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodBoolean", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodBoolean.init */.sF.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .booleanProcessor */.dO(inst, ctx, json, params); +}); +function boolean(params) { + return _checks_js__rspack_import_5/* ._boolean */._L(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); +}, +/*@__PURE__*/ util.derived({ + minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null, + maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null, + format: (inst) => processors.aggregateChecks(inst).format ?? null, +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +})))); +function bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function _undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNull", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNull.init */.x8.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .nullProcessor */.In(inst, ctx, json, params); +}); +function _null(params) { + return _checks_js__rspack_import_5/* ._null */.jw(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodAny", (inst, def) => { + core.$ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params); +}))); +function any() { + return core._any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodUnknown", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodUnknown.init */.GP.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .unknownProcessor */.NV(inst, ctx, json, params); +}); +function unknown() { + return _checks_js__rspack_import_5/* ._unknown */.em(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNever", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNever.init */.Um.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .neverProcessor */.RH(inst, ctx, json, params); +}); +function never(params) { + return _checks_js__rspack_import_5/* ._never */.G8(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function _void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); +}, +/*@__PURE__*/ util.derived({ + minDate: (inst) => { + const { minimum } = processors.aggregateChecks(inst); + return minimum ? new Date(minimum) : null; + }, + maxDate: (inst) => { + const { maximum } = processors.aggregateChecks(inst); + return maximum ? new Date(maximum) : null; + }, +}, {})))); +function date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + _core_index_js__rspack_import_3/* .$ZodArray.init */.$p.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .arrayProcessor */.cY(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_checks_js__rspack_import_5/* ._minLength */.m9(n, params)); + }, + nonempty(params) { + return this.check(_checks_js__rspack_import_5/* ._minLength */.m9(1, params)); + }, + max(n, params) { + return this.check(_checks_js__rspack_import_5/* ._maxLength */.Eb(n, params)); + }, + length(n, params) { + return this.check(_checks_js__rspack_import_5/* ._length */.YA(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function array(element, params) { + return _checks_js__rspack_import_5/* ._array */.dZ(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return _enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + _core_index_js__rspack_import_3/* .$ZodObjectJIT.init */.w.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .objectProcessor */.Ec(inst, ctx, json, params); + _core_index_js__rspack_import_4/* .installLazyProp */.X(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return _enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(this._zod.def, { catchall: catchall })); + }, + passthrough() { + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(this._zod.def, { catchall: unknown() })); + }, + loose() { + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(this._zod.def, { catchall: unknown() })); + }, + strict() { + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(this._zod.def, { catchall: never() })); + }, + strip() { + return this.clone(_core_index_js__rspack_import_4/* .mergeDefs */.zM(this._zod.def, { catchall: undefined })); + }, + extend(incoming) { + return _core_index_js__rspack_import_4/* .extend */.X$(this, incoming); + }, + safeExtend(incoming) { + return _core_index_js__rspack_import_4/* .safeExtend */.W0(this, incoming); + }, + merge(other) { + return _core_index_js__rspack_import_4/* .merge */.h1(this, other); + }, + pick(mask) { + return _core_index_js__rspack_import_4/* .pick */.Up(this, mask); + }, + omit(mask) { + return _core_index_js__rspack_import_4/* .omit */.cJ(this, mask); + }, + partial(...args) { + return _core_index_js__rspack_import_4/* .partial */.OH(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return _core_index_js__rspack_import_4/* .partial */.OH(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return _core_index_js__rspack_import_4/* .required */.mw(ZodNonOptional, this, args[0]); + }, +}); +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...util.normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodUnion", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodUnion.init */.cu.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .unionProcessor */.iC(inst, ctx, json, params); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodDiscriminatedUnion.init(inst, def); +}))); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodIntersection", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodIntersection.init */.LJ.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .intersectionProcessor */.i_(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + _core_index_js__rspack_import_3/* .$ZodRecord.init */.h.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .recordProcessor */.GC(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: string(), + valueType: keyType, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodEnum", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodEnum.init */.VO.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .enumProcessor */.C0(inst, ctx, json, params); + inst.enum = def.entries; + // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out + inst.options = [...inst._zod.values]; + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + entries: newEntries, + }); + }; +}); +function _enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodLiteral", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodLiteral.init */.nu.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .literalProcessor */.Yv(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + _core_index_js__rspack_import_3/* .$ZodTransform.init */.Wc.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .transformProcessor */.xi(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new _core_index_js__rspack_import_0/* .$ZodEncodeError */.cV(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(_core_index_js__rspack_import_4/* .issue */.sn(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(_core_index_js__rspack_import_4/* .issue */.sn(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodOptional", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodOptional.init */.ig.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .optionalProcessor */.$k(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodExactOptional", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodExactOptional.init */.RL.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .optionalProcessor */.$k(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNullable", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNullable.init */.qc.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .nullableProcessor */.yq(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function nullish(innerType) { + return optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodDefault", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodDefault.init */.rv.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .defaultProcessor */.mh(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : _core_index_js__rspack_import_4/* .shallowClone */.yG(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodPrefault", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodPrefault.init */.VF.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .prefaultProcessor */.A(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : _core_index_js__rspack_import_4/* .shallowClone */.yG(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodNonOptional", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodNonOptional.init */.N$.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .nonoptionalProcessor */.cR(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ..._core_index_js__rspack_import_4/* .normalizeParams */.A2(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCatch", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodCatch.init */.t$.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .catchProcessor */.Q9(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : _core_index_js__rspack_import_4/* .constantCatch */.SS(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodPipe", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodPipe.init */._m.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .pipeProcessor */.fs(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodPreprocess.init(inst, def); +}))); +const ZodReadonly = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodReadonly", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodReadonly.init */.Sb.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .readonlyProcessor */.$X(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodLazy", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodLazy.init */.kU.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .lazyProcessor */.Tr(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ _core_index_js__rspack_import_0/* .$constructor */.xI("ZodCustom", (inst, def) => { + _core_index_js__rspack_import_3/* .$ZodCustom.init */.b0.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => _core_json_schema_processors_js__rspack_import_10/* .customProcessor */.A6(inst, ctx, json, params); +}); +// custom checks +function check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _checks_js__rspack_import_5/* ._refine */.fU(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _checks_js__rspack_import_5/* ._superRefine */.MB(fn, params); +} +// Re-export describe and meta from core +const describe = _checks_js__rspack_import_5/* .describe */.q0; +const meta = _checks_js__rspack_import_5/* .meta */.mI; +const ZodInstanceOf = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodInstanceOf", (inst, def) => { + ZodCustom.init(inst, def); +}, { + properties(shape, params) { + // asserts in place, so the narrowed output type is truthful without a wrapper + return this.check(core._properties(shape, params)); + }, +}))); +function _instanceof(cls, params = {}) { + const inst = new ZodInstanceOf({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function json(params) { + const jsonSchema = lazy(() => { + return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + +__webpack_require__.d(__webpack_exports__, { + Ikc: () => (object), + KCZ: () => (union), + L5J: () => (unknown), + Pq9: () => (json), + YOg: () => (array), + YjP: () => (string), + aig: () => (number), + euz: () => (literal), + g1P: () => (record), + k5n: () => (_enum), + rej: () => (strictObject), + zMY: () => (boolean) +}); + + +}, +"./node_modules/zod/v4/core/api.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _checks_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/checks.js"); +/* import */ var _registries_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/registries.js"); +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + + + +function snapshotChecks(def) { + if (def.checks) + def.checks = [...def.checks]; + return def; +} +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class(snapshotChecks({ type: "string", ..._util_js__rspack_import_0/* .normalizeParams */.A2(params) })); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class(snapshotChecks({ type: "string", coerce: true, ...util.normalizeParams(params) })); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _iban(Class, params) { + return new Class({ + type: "string", + format: "iban", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class(snapshotChecks({ type: "number", checks: [], ..._util_js__rspack_import_0/* .normalizeParams */.A2(params) })); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class(snapshotChecks({ type: "number", coerce: true, checks: [], ...util.normalizeParams(params) })); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _null(Class, params) { + return new Class({ + type: "null", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckLessThan */.sm({ + check: "less_than", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckLessThan */.sm({ + check: "less_than", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckGreaterThan */.J_({ + check: "greater_than", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckGreaterThan */.J_({ + check: "greater_than", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckMultipleOf */.Jk({ + check: "multiple_of", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new _checks_js__rspack_import_1/* .$ZodCheckMaxLength */.Yk({ + check: "max_length", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckMinLength */.Kk({ + check: "min_length", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckLengthEquals */.RM({ + check: "length_equals", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckRegex */.DG({ + check: "string_format", + format: "regex", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new _checks_js__rspack_import_1/* .$ZodCheckLowerCase */.NI({ + check: "string_format", + format: "lowercase", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new _checks_js__rspack_import_1/* .$ZodCheckUpperCase */.kH({ + check: "string_format", + format: "uppercase", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckIncludes */.Tt({ + check: "string_format", + format: "includes", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckStartsWith */.J({ + check: "string_format", + format: "starts_with", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new _checks_js__rspack_import_1/* .$ZodCheckEndsWith */.E6({ + check: "string_format", + format: "ends_with", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape, params) { + return new checks.$ZodCheckProperties({ + check: "properties", + shape, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new _checks_js__rspack_import_1/* .$ZodCheckOverwrite */.v$({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => _util_js__rspack_import_0/* .slugify */.Yv(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ..._util_js__rspack_import_0/* .normalizeParams */.A2(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(_util_js__rspack_import_0/* .issue */.sn(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(_util_js__rspack_import_0/* .issue */.sn(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new _checks_js__rspack_import_1/* .$ZodCheck */.QP({ + check: "custom", + ..._util_js__rspack_import_0/* .normalizeParams */.A2(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new _checks_js__rspack_import_1/* .$ZodCheck */.QP({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = _registries_js__rspack_import_2/* .globalRegistry.get */.fd.get(inst) ?? {}; + _registries_js__rspack_import_2/* .globalRegistry.add */.fd.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new _checks_js__rspack_import_1/* .$ZodCheck */.QP({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = _registries_js__rspack_import_2/* .globalRegistry.get */.fd.get(inst) ?? {}; + _registries_js__rspack_import_2/* .globalRegistry.add */.fd.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + +__webpack_require__.d(__webpack_exports__, { + $O: () => (_ipv6), + $S: () => (_startsWith), + Au: () => (_lt), + Be: () => (_uuid), + Bj: () => (_cuid2), + Ct: () => (_ulid), + Dl: () => (_nanoid), + ER: () => (_endsWith), + Eb: () => (_maxLength), + F7: () => (_number), + Fk: () => (_regex), + Fn: () => (_url), + G1: () => (_isoDateTime), + G8: () => (_never), + Hi: () => (_multipleOf), + Il: () => (_toLowerCase), + KB: () => (_e164), + Kn: () => (_isoTime), + LK: () => (_int), + MB: () => (_superRefine), + Mu: () => (_email), + Ny: () => (_ipv4), + Pw: () => (_xid), + Rl: () => (_string), + TL: () => (_slugify), + Tx: () => (_gt), + Uy: () => (_cidrv4), + WN: () => (_trim), + YA: () => (_length), + Zm: () => (_lte), + _L: () => (_boolean), + _z: () => (_ksuid), + aC: () => (_emoji), + bS: () => (_overwrite), + cU: () => (_base64url), + dR: () => (_includes), + dZ: () => (_array), + db: () => (_isoDate), + em: () => (_unknown), + f2: () => (_isoDuration), + fU: () => (_refine), + fs: () => (_cuid), + gP: () => (_cidrv6), + hH: () => (_lowercase), + jw: () => (_null), + lo: () => (_normalize), + m9: () => (_minLength), + mI: () => (meta), + nA: () => (_uuidv4), + pY: () => (_uuidv6), + q0: () => (describe), + qF: () => (_uppercase), + qm: () => (_gte), + rk: () => (_jwt), + rt: () => (_base64), + tB: () => (_guid), + wA: () => (_uuidv7), + xY: () => (_toUpperCase) +}); + + +}, +"./node_modules/zod/v4/core/checks.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _regexes_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/regexes.js"); +/* import */ var _util_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/util.js"); +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !_util_js__rspack_import_1/* .nullish */.cl(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : _util_js__rspack_import_1/* .floatSafeRemainder */.LG(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = _util_js__rspack_import_1/* .NUMBER_FORMAT_RANGES */.zH[def.format]; + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? _util_js__rspack_import_1/* .codePointLength */.O7(input) : units; + if (length <= def.maximum) + return; + const origin = _util_js__rspack_import_1/* .getLengthableOrigin */.Rc(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? _util_js__rspack_import_1/* .codePointLength */.O7(input) + : units; + if (length >= def.minimum) + return; + const origin = _util_js__rspack_import_1/* .getLengthableOrigin */.Rc(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? _util_js__rspack_import_1/* .codePointLength */.O7(input) + : units; + if (length === def.length) + return; + const origin = _util_js__rspack_import_1/* .getLengthableOrigin */.Rc(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_2/* .lowercase */.AC); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_2/* .uppercase */.Zv); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = _util_js__rspack_import_1/* .escapeRegex */.sD(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${_util_js__rspack_import_1/* .escapeRegex */.sD(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${_util_js__rspack_import_1/* .escapeRegex */.sD(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckProperties = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperties", (inst, def) => { + $ZodCheck.init(inst, def); + util.hide(inst, Symbol.iterator, function* () { + yield inst; + }); + // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema + let entries; + inst._zod.check = (payload) => { + // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length + if (payload.value == null) { + payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst }); + return undefined; + } + entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]])); + const input = payload.value; + let proms; + for (const [key, schema] of entries) { + const result = schema._zod.run({ value: input[key], issues: [] }, {}); + if (result instanceof Promise) { + proms ?? (proms = []); + proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key))); + } + else { + handleCheckPropertyResult(result, payload, key); + } + } + if (proms) + return Promise.all(proms).then(() => undefined); + return undefined; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +__webpack_require__.d(__webpack_exports__, { +}, { + DG: $ZodCheckRegex, + E6: $ZodCheckEndsWith, + J: $ZodCheckStartsWith, + J_: $ZodCheckGreaterThan, + Jk: $ZodCheckMultipleOf, + KH: $ZodCheckNumberFormat, + Kk: $ZodCheckMinLength, + NI: $ZodCheckLowerCase, + QP: $ZodCheck, + RM: $ZodCheckLengthEquals, + Tt: $ZodCheckIncludes, + Yk: $ZodCheckMaxLength, + kH: $ZodCheckUpperCase, + ql: $ZodCheckStringFormat, + sm: $ZodCheckLessThan, + v$: $ZodCheckOverwrite +}); + + +}, +"./node_modules/zod/v4/core/core.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.d(__webpack_exports__, { + $W: () => (config), + GT: () => ($ZodAsyncError), + cV: () => ($ZodEncodeError), + cr: () => (globalConfig), + xI: () => ($constructor) +}); +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); +var _a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ (/* unused pure expression or super */ null && (Object.freeze({ + status: "aborted", +}))); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + else if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + (0,_util_js__rspack_import_0/* .members */.ol)(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + + +}, +"./node_modules/zod/v4/core/doc.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it + indented(fn) { + this.indent += 1; + try { + fn(this); + } + finally { + this.indent -= 1; + } + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + +__webpack_require__.d(__webpack_exports__, { + J: () => (Doc) +}); + + +}, +"./node_modules/zod/v4/core/errors.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, _util_js__rspack_import_0/* .jsonStringifyReplacer */.k8, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const initializer = (inst, def) => { + inst.name = "$ZodError"; + // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slot; a retained `value` pins the last error's issues. + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = (0,_core_js__rspack_import_1/* .$constructor */.xI)("$ZodError", initializer); +const $ZodRealError = (0,_core_js__rspack_import_1/* .$constructor */.xI)("$ZodError", initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + +__webpack_require__.d(__webpack_exports__, { + JM: () => (flattenError), + Wk: () => (formatError) +}, { + Kd: $ZodRealError, + a$: $ZodError +}); + + +}, +"./node_modules/zod/v4/core/json-schema-processors.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _regexes_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/regexes.js"); +/* import */ var _schemas_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/schemas.js"); +/* import */ var _to_json_schema_js__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/core/to-json-schema.js"); +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + + + +const narrowMin = (agg, key, value) => { + if (agg[key] === undefined || value > agg[key]) + agg[key] = value; +}; +const narrowMax = (agg, key, value) => { + if (agg[key] === undefined || value < agg[key]) + agg[key] = value; +}; +const narrowBoth = (agg, value) => { + narrowMin(agg, "minimum", value); + narrowMax(agg, "maximum", value); +}; +const addDivisor = (agg, value) => { + agg.multipleOf ?? (agg.multipleOf = []); + if (!agg.multipleOf.includes(value)) + agg.multipleOf.push(value); +}; +const addPattern = (agg, pattern) => { + agg.patterns ?? (agg.patterns = new Set()); + agg.patterns.add(pattern); +}; +const intersectMime = (agg, mime) => { + agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime]; +}; +// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one +const setFormat = (agg, format) => { + agg.format = format; + if (format.includes("int")) + agg.isInt = true; +}; +const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum); +const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum); +const formatContributor = (ranges) => (agg, def) => { + setFormat(agg, def.format); + const [minimum, maximum] = ranges[def.format]; + narrowMin(agg, "minimum", minimum); + narrowMax(agg, "maximum", maximum); +}; +const contributors = { + greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value), + less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value), + multiple_of: (agg, def) => addDivisor(agg, def.value), + number_format: formatContributor(_util_js__rspack_import_0/* .NUMBER_FORMAT_RANGES */.zH), + bigint_format: formatContributor(_util_js__rspack_import_0/* .BIGINT_FORMAT_RANGES */.NR), + min_length: minContributor, + max_length: maxContributor, + length_equals: (agg, def) => narrowBoth(agg, def.length), + min_size: minContributor, + max_size: maxContributor, + size_equals: (agg, def) => narrowBoth(agg, def.size), + string_format: (agg, def) => { + setFormat(agg, def.format); + if (def.pattern) + addPattern(agg, def.pattern); + if (def.format === "base64" || def.format === "base64url") + agg.contentEncoding = def.format; + if (def.local || def.precision === -1) + agg.laxFormat = true; + }, + mime_type: (agg, def) => intersectMime(agg, def.mime), +}; +function aggregateChecks(schema) { + const agg = {}; + const def = schema._zod.def; + // a format schema is its own first check, same rule as $ZodType init + const list = schema._zod.traits.has("$ZodCheck") + ? [schema, ...(def.checks ?? [])] + : (def.checks ?? []); + for (const ch of list) + contributors[ch._zod.def.check]?.(agg, ch._zod.def); + // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other + const bag = schema._zod.bag; + if (bag.minimum !== undefined) + narrowMin(agg, "minimum", bag.minimum); + if (bag.exclusiveMinimum !== undefined) + narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum); + if (bag.maximum !== undefined) + narrowMax(agg, "maximum", bag.maximum); + if (bag.exclusiveMaximum !== undefined) + narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum); + if (bag.multipleOf !== undefined) + addDivisor(agg, bag.multipleOf); + if (bag.format !== undefined) { + agg.format ?? (agg.format = bag.format); + if (bag.format.includes("int")) + agg.isInt = true; + } + if (bag.mime) + intersectMime(agg, bag.mime); + for (const pattern of bag.patterns ?? []) + addPattern(agg, pattern); + return agg; +} +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes +const exactPatterns = new Map([ + [_schemas_js__rspack_import_1/* .base64Charset */.cq, _regexes_js__rspack_import_2/* .base64 */.K3], + [_schemas_js__rspack_import_1/* .base64urlCharset */.xE, _regexes_js__rspack_import_2/* .base64url */.r0], +]); +const exactPattern = (p) => exactPatterns.get(p) ?? p; +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema); + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns].map(exactPattern); + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema); + json.type = isInt ? "integer" : "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (multipleOf) { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + const divisors = new Set(); + for (const divisor of multipleOf) { + if (Number.isFinite(divisor) && divisor !== 0) + divisors.add(Math.abs(divisor)); + else + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`); + } + // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns + const [first, ...rest] = divisors; + if (first !== undefined) + json.multipleOf = first; + if (rest.length) + json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))]; + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = (0,_util_js__rspack_import_0/* .getEnumValues */.w5)(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if ((0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if ((0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + _json.type = "string"; + _json.format = "binary"; + _json.contentEncoding = "binary"; + const { minimum, maximum, mime } = aggregateChecks(schema); + if (minimum !== undefined) + _json.minLength = minimum; + if (maximum !== undefined) + _json.maxLength = maximum; + if (!mime) + return; + // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}` + if (mime.length === 0) + _json.not = {}; + else if (mime.length === 1) + _json.contentMediaType = mime[0]; + // only contentMediaType differs, so the shared props stay at the root + else + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = aggregateChecks(schema); + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + (0,_util_js__rspack_import_0/* .assignProp */.Vy)(json.properties, key, (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const requiredKeys = []; + for (const key of Object.keys(shape)) { + const field = def.shape[key]; + if (ctx.io === "input" ? inputOptin(field) === undefined : field._zod.optout === undefined) { + requiredKeys.push(key); + } + } + if (requiredKeys.length > 0) { + json.required = requiredKeys; + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => processSchema(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? processSchema(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = aggregateChecks(schema); + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? _regexes_js__rspack_import_2/* .number */.ai : _regexes_js__rspack_import_2/* .integer */.nd).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const patterns = aggregateChecks(keyType).patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + (0,_util_js__rspack_import_0/* .assignProp */.Vy)(json.patternProperties, exactPattern(pattern).source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + (0,_to_json_schema_js__rspack_import_3/* .handleUnrepresentable */._S)(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + processSchema(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + (0,_to_json_schema_js__rspack_import_3/* .processSchema */.Lp)(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = (/* unused pure expression or super */ null && ({ + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +})); +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + processSchema(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + processSchema(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + +__webpack_require__.d(__webpack_exports__, { + Fs: () => (aggregateChecks) +}, { + $X: readonlyProcessor, + $k: optionalProcessor, + A: prefaultProcessor, + A6: customProcessor, + C0: enumProcessor, + Ec: objectProcessor, + GC: recordProcessor, + In: nullProcessor, + NV: unknownProcessor, + Q9: catchProcessor, + RH: neverProcessor, + SW: stringProcessor, + Tr: lazyProcessor, + Wg: numberProcessor, + Yv: literalProcessor, + cR: nonoptionalProcessor, + cY: arrayProcessor, + dO: booleanProcessor, + fs: pipeProcessor, + iC: unionProcessor, + i_: intersectionProcessor, + mh: defaultProcessor, + xi: transformProcessor, + yq: nullableProcessor +}); + + +}, +"./node_modules/zod/v4/core/memoizer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// a value a cycle can close through +function isRef(value) { + return value !== null && typeof value === "object"; +} +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */ +const NONE = 0; +const ASSUMED = 1; +const PROVEN = 2; +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack, resolve) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached ? PROVEN : NONE; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return PROVEN; + stack.add(inst); + let result = NONE; + const check = (child) => { + if (result !== PROVEN && child?._zod) { + const answer = isRecursive(child, stack, resolve); + if (answer > result) + result = answer; + } + }; + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + const shape = (sh, spread) => { + let answer = NONE; + for (const key of Reflect.ownKeys(sh)) { + const desc = Object.getOwnPropertyDescriptor(sh, key); + // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all + if (spread && !desc.enumerable) + continue; + // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle + const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE; + if (child > answer) + answer = child; + } + return answer; + }; + const merge = (answer) => { + if (answer > result) + result = answer; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + const raw = _util_js__rspack_import_0/* .rawShape */.MO(def); + // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree + merge(raw ? shape(raw, true) : ASSUMED); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly + case "lazy": { + const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined); + // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there + merge(inner ? isRecursive(inner, stack, false) : ASSUMED); + break; + } + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + return settle(inst, result); +} +/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */ +function settle(inst, answer) { + if (answer !== ASSUMED) + recursive.set(inst, answer === PROVEN); + return answer; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive + return isRecursive(inst, new Set(), true) !== NONE; +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new WeakMap(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const open = []; +const memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + let rechecked = false; + // a recursive schema is re-entered many times per parse and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + const walked = isRecursive(inst, new Set(), false); + if (walked === NONE) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + // this parse resolves the deferred edges on its own path, so ask once more before latching + if (walked === PROVEN || rechecked) + isRecursiveInst = true; + else + rechecked = true; + } + const input = payload.value; + if (!isRef(input)) + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new WeakMap(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new WeakSet()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = open.length > depth ? open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && isRef(value) && backEdges.has(value); +} + +__webpack_require__.d(__webpack_exports__, { + x3: () => (memoizer) +}); + + +}, +"./node_modules/zod/v4/core/parse.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _errors_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/errors.js"); +/* import */ var _util_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const _parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => _util_js__rspack_import_1/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W()))); + _util_js__rspack_import_1/* .captureStackTrace */.gx(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const parse = /* @__PURE__*/ _parse(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => _util_js__rspack_import_1/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W()))); + _util_js__rspack_import_1/* .captureStackTrace */.gx(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const parseAsync = /* @__PURE__*/ _parseAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + } + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle +function failure(Err, issues, ctx) { + let error; + return { + success: false, + get error() { + if (!error) { + error = new Err(issues.map((iss) => _util_js__rspack_import_1/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W()))); + // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result + issues = undefined; + ctx = undefined; + } + return error; + }, + set error(e) { + error = e; + // a replacement makes the getter's branch unreachable, so the captures have to go here too + issues = undefined; + ctx = undefined; + }, + }; +} +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid"); +const COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback"); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined) { + if (validator(value) !== COMPILE_INVALID) + return true; + // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer + if (validator.definite === true && _ctx === undefined) + return false; + } + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx + ? { ..._ctx, async: false, abortEarly: true } + : { async: false, abortEarly: true }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx + ? { ..._ctx, async: true, abortEarly: true } + : { async: true, abortEarly: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const _encode = (_Err) => { + const parse = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ _encode(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _decode = (_Err) => { + const parse = _parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ _decode(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _encodeAsync = (_Err) => { + const parseAsync = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ _encodeAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _decodeAsync = (_Err) => { + const parseAsync = _parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ _decodeAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(_errors_js__rspack_import_2/* .$ZodRealError */.Kd); + +__webpack_require__.d(__webpack_exports__, { +}, { + F0: validateAsync, + GW: _encodeAsync, + Mv: _encode, + Od: _safeParse, + R3: _safeDecodeAsync, + Rb: _parseAsync, + Tj: _parse, + VS: _safeDecode, + e2: _decode, + or: _decodeAsync, + rh: _safeEncode, + tf: validate, + v_: _safeEncodeAsync, + wG: _safeParseAsync +}); + + +}, +"./node_modules/zod/v4/core/regexes.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base. +const _emoji = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts +const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/; +// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters +const iban = /^[A-Z]{2}(?!00|01|99)\d{2}[A-Z0-9]{11,30}$/; +const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function anchor(source) { + return new RegExp(`^${source}$`); +} +const date = /*@__PURE__*/ anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own +const anyString = /^[\s\S]{0,}$/; +const string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +__webpack_require__.d(__webpack_exports__, { + D2: () => (nanoidOfLength), + Zg: () => (emoji), + kB: () => (time), + w$: () => (datetime) +}, { + AC: lowercase, + Ak: nanoid, + F: httpProtocol, + Gl: cuid2, + K3: base64, + Os: guid, + Rp: email, + Z0: ulid, + Zv: uppercase, + ai: number, + ch: _null, + fO: ksuid, + gF: cuid, + gp: anyString, + hQ: e164, + kM: xid, + l7: cidrv6, + nd: integer, + p0: duration, + p6: date, + r0: base64url, + uR: uuid, + uX: ipv4, + ug: ipv6, + zM: boolean, + zr: cidrv4 +}); + + +}, +"./node_modules/zod/v4/core/registries.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +var _a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registry() { + return new $ZodRegistry(); +} +(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + +__webpack_require__.d(__webpack_exports__, { +}, { + fd: globalRegistry +}); + + +}, +"./node_modules/zod/v4/core/schemas.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _checks_js__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/core/checks.js"); +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/core.js"); +/* import */ var _doc_js__rspack_import_5 = __webpack_require__("./node_modules/zod/v4/core/doc.js"); +/* import */ var _regexes_js__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/core/regexes.js"); +/* import */ var _util_js__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/core/util.js"); +/* import */ var _versions_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/versions.js"); + + + + + + + +const $ZodType = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = _versions_js__rspack_import_1/* .version */.r; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = _util_js__rspack_import_2/* .aborted */.QH(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (_util_js__rspack_import_2/* .explicitlyAborted */.rL(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + _util_js__rspack_import_2/* .attachSchema */.d3(payload.issues, currLen, inst); + if (!isAborted) + isAborted = _util_js__rspack_import_2/* .aborted */.QH(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + _util_js__rspack_import_2/* .attachSchema */.d3(payload.issues, currLen, inst); + if (!isAborted) + isAborted = _util_js__rspack_import_2/* .aborted */.QH(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (_util_js__rspack_import_2/* .aborted */.QH(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return _util_js__rspack_import_2/* .hide */.jD(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + _util_js__rspack_import_2/* .own */.qh(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through +const toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => _util_js__rspack_import_2/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W())) } : { value: r.value }; +async function validateAsync(inst, value) { + const ctx = { async: true }; + return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx); +} +function standardProps(inst) { + return { + validate: (value) => { + const ctx = { async: false }; + try { + const r = inst._zod.run({ value, issues: [] }, ctx); + if (!(r instanceof Promise)) + return toStandardResult(r, ctx); + } + catch (_) { } + // async function so a synchronously throwing check rejects instead of escaping validate + return validateAsync(inst, value); + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + // a format's own pattern, else unbounded; a template literal derives the check-aware form itself + inst._zod.pattern = def.pattern ?? _regexes_js__rspack_import_3/* .anyString */.gp; + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodStringFormat", (inst, def) => { + // check initialization must come first + _checks_js__rspack_import_4/* .$ZodCheckStringFormat.init */.ql.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .guid */.Os); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .uuid */.uR(v)); + } + else + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .uuid */.uR()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .email */.Rp); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL parser rejected the input. */ +const URL_UNPARSEABLE = 2; +function canParseURL(input) { + try { + if (typeof URL !== "undefined" && typeof URL.canParse === "function") + return URL.canParse(input); + new URL(input); + return true; + } + catch { + return false; + } +} +function validateURL(trimmed, def) { + if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) { + return canParseURL(trimmed) || URL_UNPARSEABLE; + } + return parseURLObject(trimmed, def); +} +/** Parses a URL while preserving the non-normalizing HTTP guard. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === _regexes_js__rspack_import_3/* .httpProtocol.source */.F.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + if (typeof URL !== "undefined") { + const URLStatic = URL; + if (typeof URLStatic.parse === "function") + return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE; + } + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = validateURL(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === true) { + payload.value = stripTabAndNewline(trimmed); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .emoji */.Zg()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? _regexes_js__rspack_import_3/* .nanoid */.Ak : _regexes_js__rspack_import_3/* .nanoidOfLength */.D2(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .cuid */.gF); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .cuid2 */.Gl); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .ulid */.Z0); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .xid */.kM); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .ksuid */.fO); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .datetime */.w$(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODate = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .date */.p6); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .time */.kB(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .duration */.p0); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .ipv4 */.uX); + $ZodStringFormat.init(inst, def); +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + return canParseURL(`http://[${value}]`); +} +const $ZodIPv6 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .ipv6 */.ug); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCIDRv4 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .cidrv4 */.zr); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .cidrv6 */.l7); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding +const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/; +const $ZodBase64 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64Charset); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64URL ////////////////////////////// +// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string +const base64urlCharset = /^[A-Za-z0-9_-]*$/; +function isValidBase64URL(data) { + if (!base64urlCharset.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64urlCharset); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = _regexes_js__rspack_import_3/* .e164 */.hQ); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = digits.charCodeAt(--length) - 48; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodIBAN ////////////////////////////// +// iso 7064 mod 97-10 checksum without BigInt +function isIso7064Mod97(iban) { + let remainder = 0; + const len = iban.length; + for (let i = 4; i < len; i++) { + const code = iban.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + for (let i = 0; i < 4; i++) { + const code = iban.charCodeAt(i); + remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97; + } + return remainder === 1; +} +function isValidIBAN(input) { + if (!regexes.iban.test(input)) + return false; + return isIso7064Mod97(input); +} +const $ZodIBAN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIBAN", (inst, def) => { + // shape only — checksum is not expressible as a pattern + def.pattern ?? (def.pattern = regexes.iban); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidIBAN(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "iban", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _regexes_js__rspack_import_3/* .number */.ai; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNumberFormat", (inst, def) => { + _checks_js__rspack_import_4/* .$ZodCheckNumberFormat.init */.KH.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _regexes_js__rspack_import_3/* .boolean */.zM; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _regexes_js__rspack_import_3/* ["null"] */.ch; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}))); +const $ZodUnknown = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = _core_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + const abortEarly = ctx?.abortEarly; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional + if (abortEarly && result.issues.length !== 0 && _util_js__rspack_import_2/* .aborted */.QH(result)) + break; + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent || (optin === "defaulted" && !isOptionalOut)) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = _util_js__rspack_import_2/* .optionalKeys */.NM(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + // starts at 0, not the current length: the shape phase already ran and may have aborted + let seen = 0; + for (const key in input) { + if (abortEarly && payload.issues.length !== seen) { + if (_util_js__rspack_import_2/* .aborted */.QH(payload, seen)) + break; + seen = payload.issues.length; + } + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +const $ZodObject = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it + const sh = desc?.get ? desc.get.raw : (def.shape ?? {}); + if (sh) { + // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas. + const get = () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { value: newSh }); + get.raw = newSh; + return newSh; + }; + get.raw = sh; + Object.defineProperty(def, "shape", { get }); + } + const _normalized = _util_js__rspack_import_2/* .cached */.PO(() => normalizeDef(def)); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + _util_js__rspack_import_2/* .assignProp */.Vy(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = _util_js__rspack_import_2/* .isObject */.Gv; + const catchall = def.catchall; + let value; + const memo = _core_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const key of value.allKeys) { + if (abortEarly && payload.issues.length !== seen) { + if (_util_js__rspack_import_2/* .aborted */.QH(payload, seen)) + break; + seen = payload.issues.length; + } + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = _util_js__rspack_import_2/* .cached */.PO(() => normalizeDef(def)); + const memo = _core_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new _doc_js__rspack_import_5/* .Doc */.J(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input + const prefixStr = (id, k) => ` + let ${id}_ab = false; + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + if (iss.continue !== true) ${id}_ab = true; + } + if (${id}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : _util_js__rspack_import_2/* .esc */.UQ(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + `); + if (optin === "defaulted") { + doc.write(`newResult[${k}] = ${id}.value;`); + } + else { + doc.write(` + if (${id}.value !== undefined || ${isPresent}) { + newResult[${k}] = ${id}.value; + } + `); + } + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = _util_js__rspack_import_2/* .isObject */.Gv; + const jit = !_core_js__rspack_import_0/* .globalConfig.jitless */.cr.jitless; + const allowsEval = _util_js__rspack_import_2/* .allowsEval */.hI; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !_util_js__rspack_import_2/* .aborted */.QH(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => _util_js__rspack_import_2/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => _util_js__rspack_import_2/* .cleanRegex */.p6(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = discriminatorMap(internals.def); + internals.bag.optionsMap = map; + } + const option = map.get(value); + if (option === null) + throw new Error(`Ambiguous discriminator value "${String(value)}"`); + return option; +} +function discriminatorMap(def) { + const map = new Map(); + for (const option of def.options) { + const values = option._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const value of values) { + if (map.has(value)) { + if (value !== undefined) + throw new Error(`Duplicate discriminator value "${String(value)}"`); + // keep the collision marked so a later member cannot reclaim it + map.set(value, null); + } + else { + map.set(value, option); + } + } + } + return map; +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +(/* unused pure expression or super */ null && (core.$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + util.defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + let undefinedCount = 0; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + if (pv[zod.def.discriminator]?.has(undefined)) + undefinedCount++; + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + util.assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + if (!zod.def.unionFallback && undefinedCount > 1) + propValues[zod.def.discriminator]?.delete(undefined); + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map. + def.options.forEach((option, i) => { + const propShape = util.rawShape(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util.cached(() => discriminatorMap(def)); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const value = input?.[def.discriminator]; + const opt = disc.value.get(value); + // forward metadata cannot choose an encoder for an absent tag + if (opt && (value !== undefined || ctx.direction !== "backward")) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}))); +const $ZodIntersection = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (_util_js__rspack_import_2/* .isPlainObject */.Qd(a) && _util_js__rspack_import_2/* .isPlainObject */.Qd(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + if (_util_js__rspack_import_2/* .aborted */.QH(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + // only tracked when there is a rest loop to skip + const abortEarly = def.rest ? ctx?.abortEarly : undefined; + let itemAborted = false; + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + if (abortEarly && !itemAborted && r.issues.length) + itemAborted = util.aborted(r); + } + } + // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues + if (def.rest && !itemAborted) { + let i = items.length - 1; + const rest = input.slice(items.length); + let seen = payload.issues.length; + for (const el of rest) { + if (abortEarly && payload.issues.length !== seen) { + if (util.aborted(payload, seen)) + break; + seen = payload.issues.length; + } + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = _core_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!_util_js__rspack_import_2/* .isPlainObject */.Qd(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => _util_js__rspack_import_2/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && _regexes_js__rspack_import_3/* .number.test */.ai.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => _util_js__rspack_import_2/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(..._util_js__rspack_import_2/* .prefixIssues */.lQ(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const [key, value] of input) { + if (abortEarly && payload.issues.length !== seen) { + if (util.aborted(payload, seen)) + break; + seen = payload.issues.length; + } + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + const abortEarly = ctx?.abortEarly; + let seen = payload.issues.length; + for (const item of input) { + if (abortEarly && payload.issues.length !== seen) { + if (util.aborted(payload, seen)) + break; + seen = payload.issues.length; + } + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = _util_js__rspack_import_2/* .getEnumValues */.w5(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => { + const patternValues = _util_js__rspack_import_2/* .getEnumValues */.w5(zod.def.entries).filter((k) => _util_js__rspack_import_2/* .propertyKeyTypes.has */.qQ.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + return new RegExp(patternValues.length ? `^(${patternValues.map((o) => _util_js__rspack_import_2/* .escapeRegex */.sD(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + }); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => { + const vals = zod.def.values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + return new RegExp(vals.length + ? `^(${vals + .map((o) => typeof o === "string" ? _util_js__rspack_import_2/* .escapeRegex */.sD(o) : o ? _util_js__rspack_import_2/* .escapeRegex */.sD(o.toString()) : String(o)) + .join("|")})$` + : "^[^\\s\\S]$"); + }); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + _core_js__rspack_import_0/* .globalConfig.memoizer */.cr.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new _core_js__rspack_import_0/* .$ZodEncodeError */.cV(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new _core_js__rspack_import_0/* .$ZodAsyncError */.GT(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${_util_js__rspack_import_2/* .cleanRegex */.p6(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.innerType._zod.values); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.innerType._zod.optin); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.def.innerType._zod.optout); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${_util_js__rspack_import_2/* .cleanRegex */.p6(pattern.source)}|null)$`) : undefined; + }); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => _util_js__rspack_import_2/* .finalizeIssue */.iR(iss, ctx, _core_js__rspack_import_0/* .config */.$W())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.def.innerType._zod.optout); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.in._zod.values); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.in._zod.optin); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.def.out._zod.optout); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}))); +const $ZodReadonly = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "values", (zod) => zod.def.innerType._zod.values); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it +function leafPattern(schema) { + const def = schema._zod.def; + let pattern = def.pattern; + let isInt = !!def.format?.includes("int"); + let minimum; + let maximum; + for (const ch of def.checks ?? []) { + const d = ch._zod.def; + if (d.pattern) + pattern = d.pattern; + isInt || (isInt = !!d.format?.includes("int")); + const lo = d.minimum ?? d.length; + const hi = d.maximum ?? d.length; + if (lo !== undefined && (minimum === undefined || lo > minimum)) + minimum = lo; + if (hi !== undefined && (maximum === undefined || hi < maximum)) + maximum = hi; + } + if (pattern) + return pattern.source; + // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier + if (minimum !== undefined && maximum !== undefined && minimum > maximum) + return "(?!)"; + if (minimum !== undefined || maximum !== undefined) + return regexes.string({ minimum, maximum }).source; + const own = schema._zod.pattern; + return (isInt && own === regexes.number ? regexes.integer : own)?.source; +} +// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern +function partPattern(schema) { + const def = schema._zod.def; + const own = schema._zod.pattern?.source; + // lazy resolves its inner on the internals, not the def + const inner = def.innerType ?? schema._zod.innerType; + if (inner) { + const before = inner._zod.pattern?.source; + const after = partPattern(inner); + if (own && before && after && after !== before) { + return own.replace(util.cleanRegex(before), () => util.cleanRegex(after)); + } + return own; + } + if (def.options) { + const sources = def.options.map(partPattern); + if (sources.every(Boolean)) + return `^(${sources.map((s) => util.cleanRegex(s)).join("|")})$`; + } + return leafPattern(schema); +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + const source = partPattern(part); + if (!source) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + regexParts.push(util.cleanRegex(source)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + _util_js__rspack_import_2/* .defineLazy */.gJ(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + _util_js__rspack_import_2/* .defineLazyInternal */.v5(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ _core_js__rspack_import_0/* .$constructor */.xI("$ZodCustom", (inst, def) => { + _checks_js__rspack_import_4/* .$ZodCheck.init */.QP.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(_util_js__rspack_import_2/* .issue */.sn(_iss)); + } +} + +__webpack_require__.d(__webpack_exports__, { + YK: () => (standardProps) +}, { + $N: $ZodISODuration, + $p: $ZodArray, + $v: $ZodString, + Ax: $ZodISOTime, + CI: $ZodCIDRv4, + CQ: $ZodBase64URL, + Cn: $ZodCIDRv6, + Dq: $ZodBase64, + EY: $ZodStringFormat, + GP: $ZodUnknown, + GY: $ZodKSUID, + I: $ZodNumberFormat, + Ko: $ZodISODateTime, + LJ: $ZodIntersection, + Lc: $ZodIPv4, + N$: $ZodNonOptional, + Oy: $ZodE164, + Py: $ZodNanoID, + RL: $ZodExactOptional, + Sb: $ZodReadonly, + TF: $ZodXID, + Um: $ZodNever, + VF: $ZodPrefault, + VO: $ZodEnum, + VY: $ZodURL, + W4: $ZodType, + Wc: $ZodTransform, + Zc: $ZodGUID, + Zn: $ZodUUID, + Zu: $ZodCUID2, + Zy: $ZodIPv6, + _m: $ZodPipe, + b0: $ZodCustom, + bl: $ZodCUID, + cG: $ZodEmoji, + cq: base64Charset, + cu: $ZodUnion, + g5: $ZodULID, + h: $ZodRecord, + h8: $ZodJWT, + ig: $ZodOptional, + kU: $ZodLazy, + nu: $ZodLiteral, + qG: $ZodEmail, + qc: $ZodNullable, + rv: $ZodDefault, + sF: $ZodBoolean, + t$: $ZodCatch, + v1: $ZodISODate, + vz: $ZodNumber, + w: $ZodObjectJIT, + x8: $ZodNull, + xE: base64urlCharset +}); + + +}, +"./node_modules/zod/v4/core/to-json-schema.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _registries_js__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/core/registries.js"); +/* import */ var _util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + (0,_util_js__rspack_import_0/* .assignProp */.Vy)(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? _registries_js__rspack_import_1/* .globalRegistry */.fd, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397) +function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + processSchema(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */ + +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + (0,_util_js__rspack_import_0/* .assignProp */.Vy)(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + (0,_util_js__rspack_import_0/* .assignProp */.Vy)(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + processSchema(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + processSchema(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +__webpack_require__.d(__webpack_exports__, { + Lp: () => (processSchema), + _S: () => (handleUnrepresentable) +}, { + OA: createToJSONSchemaMethod, + uE: createStandardJSONSchemaMethod +}); + + +}, +"./node_modules/zod/v4/core/util.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.d(__webpack_exports__, { + A2: () => (normalizeParams), + B7: () => (stringifyPrimitive), + GW: () => (parsedType), + Gv: () => (isObject), + LG: () => (floatSafeRemainder), + MO: () => (rawShape), + NM: () => (optionalKeys), + NR: () => (BIGINT_FORMAT_RANGES), + O7: () => (codePointLength), + OH: () => (partial), + PO: () => (cached), + QH: () => (aborted), + Qd: () => (isPlainObject), + Rc: () => (getLengthableOrigin), + SS: () => (constantCatch), + UQ: () => (esc), + Up: () => (pick), + Vy: () => (assignProp), + W0: () => (safeExtend), + X: () => (installLazyProp), + X$: () => (extend), + Yv: () => (slugify), + cJ: () => (omit), + cl: () => (nullish), + d3: () => (attachSchema), + gJ: () => (defineLazy), + gx: () => (captureStackTrace), + h1: () => (merge), + hI: () => (allowsEval), + iR: () => (finalizeIssue), + jD: () => (hide), + jw: () => (joinValues), + k8: () => (jsonStringifyReplacer), + lQ: () => (prefixIssues), + mw: () => (required), + o8: () => (clone), + ol: () => (members), + p6: () => (cleanRegex), + qQ: () => (propertyKeyTypes), + qh: () => (own), + rL: () => (explicitlyAborted), + sD: () => (escapeRegex), + sn: () => (issue), + un: () => (derived), + v5: () => (defineLazyInternal), + w5: () => (getEnumValues), + yG: () => (shallowClone), + zH: () => (NUMBER_FORMAT_RANGES), + zM: () => (mergeDefs) +}); +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/core.js"); + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here) +class Cached { + constructor(getter) { + this._getter = getter; + this._value = undefined; + } + get value() { + const getter = this._getter; + if (getter !== undefined) { + this._value = getter(); + this._getter = undefined; + } + return this._value; + } +} +function cached(getter) { + return new Cached(getter); +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +/** + * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. + * + * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none. + */ +function rawShape(def) { + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + return desc?.get ? desc.get.raw : desc?.value; +} +// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it. +function sourceShape(schema) { + return rawShape(schema._zod.def) ?? schema._zod.def.shape; +} +// a key whose value is not settled yet, self-caching so every read after the first gets the same one +function deferProp(target, key, getter) { + Object.defineProperty(target, key, { + get() { + const value = getter(); + assignProp(this, key, value); + return value; + }, + enumerable: true, + configurable: true, + }); +} +// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name. +function putProp(target, key, value) { + if (key in target) + assignProp(target, key, value); + else + target[key] = value; +} +/** + * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`. + * + * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema. + */ +function mirrorShape(target, source, keys, wrap) { + const raw = sourceShape(source); + for (const key of keys) { + const desc = Object.getOwnPropertyDescriptor(raw, key); + if (!desc.enumerable) + continue; + if (desc.get) { + deferProp(target, key, () => { + const value = source._zod.def.shape[key]; + return wrap ? wrap(value, key) : value; + }); + } + else + putProp(target, key, wrap ? wrap(desc.value, key) : desc.value); + } +} +// same, for a plain shape a caller passed rather than a schema's +function mirrorProps(target, source) { + for (const key of Reflect.ownKeys(source)) { + const desc = Object.getOwnPropertyDescriptor(source, key); + if (!desc.enumerable) + continue; + if (desc.get) + deferProp(target, key, () => source[key]); + else + putProp(target, key, desc.value); + } +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const allowsEval = /* @__PURE__*/ cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (_core_js__rspack_import_0/* .globalConfig.jitless */.cr.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const newShape = {}; + mirrorShape(newShape, schema, maskedKeys(schema, mask)); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +// the mask keys that select something, checked against the source's shape without resolving it +function maskedKeys(schema, mask) { + const raw = sourceShape(schema); + const keys = []; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (mask[key]) + keys.push(key); + } + return keys; +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const omitted = new Set(maskedKeys(schema, mask)); + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key))); + return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] })); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = sourceShape(schema); + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +// the source's keys, then the caller's overlaid on top +function extended(schema, shape) { + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema))); + mirrorProps(newShape, shape); + return newShape; +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) })); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const newShape = {}; + mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a))); + mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b))); + const def = mergeDefs(a._zod.def, { + shape: newShape, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && + ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: "optional", innerType: value })))); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] })); +} +function required(Class, schema, mask) { + const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined; + const newShape = {}; + mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => + // overwrite with non-optional + selected && !selected.has(key) ? value : new Class({ type: "nonoptional", innerType: value })); + return clone(schema, mergeDefs(schema._zod.def, { shape: newShape })); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter + const full = {}; + for (const k of Object.keys(iss)) { + if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") + continue; + full[k] = iss[k]; + } + full.path ?? (full.path = []); + full.message = message; + if (ctx?.reportInput) { + full.input = iss.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return own(inst, key, value, false); +} +/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */ +function derived(computes, table) { + for (const key in computes) { + const compute = computes[key]; + // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written + Object.defineProperty(table, key, { + configurable: true, + enumerable: true, + get() { + return own(this, key, compute(this)); + }, + set(value) { + own(this, key, value); + }, + }); + } + return table; +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : own(this, key, fn.bind(this)); + }, + set(value) { + own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + + +}, +"./node_modules/zod/v4/core/versions.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +const version = { + major: 4, + minor: 6, + patch: 5, +}; + +__webpack_require__.d(__webpack_exports__, { +}, { + r: version +}); + + +}, +"./node_modules/zod/v4/locales/en.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _core_util_js__rspack_import_0 = __webpack_require__("./node_modules/zod/v4/core/util.js"); + +const error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + currency_code: "currency code", + credit_card: "credit card number", + iban: "IBAN", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = _core_util_js__rspack_import_0/* .parsedType */.GW(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${_core_util_js__rspack_import_0/* .stringifyPrimitive */.B7(issue.values[0])}`; + return `Invalid option: expected one of ${_core_util_js__rspack_import_0/* .joinValues */.jw(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${_core_util_js__rspack_import_0/* .joinValues */.jw(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function __rspack_default_export() { + return { + localeError: error(), + }; +} + +__webpack_require__.d(__webpack_exports__, { + A: () => (/* export default binding */ __rspack_default_export) +}); + + +}, +"./src/core/app-session.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_child_process__rspack_import_1 = __webpack_require__("node:child_process"); +/* import */ var node_fs__rspack_import_2 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_3 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_4 = __webpack_require__("node:path"); + + + + + +// Chromium OSCrypt: "v10" = fixed password (macOS: the Keychain password; Linux: "peanuts"), +// "v11" = Linux Secret Service password. macOS stretches with 1003 PBKDF2 rounds, Linux with 1. +// Windows v10 uses AES-256-GCM with a DPAPI-wrapped key from Local State (not PBKDF2). +const SAFE_STORAGE_PREFIX_V10 = "v10"; +const SAFE_STORAGE_PREFIX_V11 = "v11"; +const SAFE_STORAGE_PREFIX_V10_BUF = Buffer.from(SAFE_STORAGE_PREFIX_V10); +const LINUX_BASIC_TEXT_PASSWORD = "peanuts"; +const SUPPORTED_PLATFORMS = new Set([ + "darwin", + "linux", + "win32" +]); +class GrokBotGatewaySessionError extends Error { + constructor(code, message){ + super(message); + this.name = "GrokBotGatewaySessionError"; + this.code = code; + } +} +function encryptedPayload(wrapped) { + if (wrapped.version != null && wrapped.version !== 1 && wrapped.version !== 2) { + throw new GrokBotGatewaySessionError("UNSUPPORTED_VERSION", `Unsupported Grok Bot gateway descriptor version ${wrapped.version}.`); + } + let encrypted; + if (wrapped.version === 2) { + const entries = Object.values(wrapped.entries ?? {}); + if (entries.length === 0) { + throw new GrokBotGatewaySessionError("EMPTY_ENTRIES", "Grok Bot gateway descriptor has no saved gateway entries."); + } + if (entries.length > 1) { + throw new GrokBotGatewaySessionError("AMBIGUOUS_ENTRIES", "Grok Bot gateway descriptor has multiple saved gateway entries and no active entry selection."); + } + encrypted = entries[0]?.encrypted; + } else { + encrypted = wrapped.encrypted; + } + if (typeof encrypted !== "string" || !encrypted) { + throw new GrokBotGatewaySessionError("MISSING_ENCRYPTED_PAYLOAD", "Grok Bot gateway descriptor is missing an encrypted payload."); + } + return encrypted; +} +function safeStorageKey(password, platform) { + const iterations = platform === "linux" ? 1 : 1003; + return node_crypto__rspack_import_0["default"].pbkdf2Sync(password, "saltysalt", iterations, 16, "sha1"); +} +function decryptSafeStorageString(encryptedBase64, password, platform = "darwin") { + const encrypted = Buffer.from(encryptedBase64, "base64"); + const prefix = encrypted.subarray(0, 3).toString("latin1"); + const linuxBasicText = platform === "linux" && prefix === SAFE_STORAGE_PREFIX_V10; + const keyring = prefix === SAFE_STORAGE_PREFIX_V10 || platform === "linux" && prefix === SAFE_STORAGE_PREFIX_V11; + if (!keyring) { + throw new Error("Unsupported Grok Bot Safe Storage format."); + } + const key = safeStorageKey(linuxBasicText ? LINUX_BASIC_TEXT_PASSWORD : password, platform); + const decipher = node_crypto__rspack_import_0["default"].createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 32)); + return Buffer.concat([ + decipher.update(encrypted.subarray(3)), + decipher.final() + ]).toString("utf8"); +} +// Windows Chromium Safe Storage: "v10" + 12-byte nonce + AES-256-GCM ciphertext + 16-byte tag. +function decryptWindowsSafeStorageString(encryptedBase64, key) { + const encrypted = Buffer.from(encryptedBase64, "base64"); + if (!encrypted.subarray(0, 3).equals(SAFE_STORAGE_PREFIX_V10_BUF)) { + throw new Error("Unsupported Grok Bot Safe Storage format."); + } + const decipher = node_crypto__rspack_import_0["default"].createDecipheriv("aes-256-gcm", key, encrypted.subarray(3, 15)); + decipher.setAuthTag(encrypted.subarray(-16)); + return Buffer.concat([ + decipher.update(encrypted.subarray(15, -16)), + decipher.final() + ]).toString("utf8"); +} +function grokBotAppDataPath(home, platform, env = {}) { + if (platform === "win32") { + const appData = env.APPDATA || (0,node_path__rspack_import_4.join)(home, "AppData/Roaming"); + return (0,node_path__rspack_import_4.join)(appData, "Grok Bot"); + } + if (platform === "linux") { + const configHome = env.XDG_CONFIG_HOME || (0,node_path__rspack_import_4.join)(home, ".config"); + return (0,node_path__rspack_import_4.join)(configHome, "Grok Bot"); + } + return (0,node_path__rspack_import_4.join)(home, "Library/Application Support/Grok Bot"); +} +function grokBotGatewayDescriptorPath(home = (0,node_os__rspack_import_3.homedir)(), platform = process.platform, env = process.env) { + return (0,node_path__rspack_import_4.join)(grokBotAppDataPath(home, platform, env), "gateway-descriptor.json"); +} +function sessionEnv({ env = process.env, appData } = {}) { + // Windows tests pass appData directly; empty string clears APPDATA to exercise the home fallback. + if (appData !== undefined) return { + ...env, + APPDATA: appData + }; + return env; +} +function hasGrokBotGatewaySession({ platform = process.platform, home = (0,node_os__rspack_import_3.homedir)(), env = process.env, appData } = {}) { + return SUPPORTED_PLATFORMS.has(platform) && (0,node_fs__rspack_import_2.existsSync)(grokBotGatewayDescriptorPath(home, platform, sessionEnv({ + env, + appData + }))); +} +function readKeychainPassword(platform = process.platform) { + if (platform === "linux") { + return (0,node_child_process__rspack_import_1.execFileSync)("secret-tool", [ + "lookup", + "xdg:schema", + "chrome_libsecret_os_crypt_password_v2", + "application", + "Grok Bot" + ], { + encoding: "utf8" + }).trimEnd(); + } + return (0,node_child_process__rspack_import_1.execFileSync)("/usr/bin/security", [ + "find-generic-password", + "-w", + "-s", + "Grok Bot Safe Storage" + ], { + encoding: "utf8" + }).trimEnd(); +} +function unprotectWithDpapi(blob) { + const script = "Add-Type -AssemblyName System.Security; " + "$blob = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); " + "[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Unprotect($blob, $null, 'CurrentUser'))"; + const out = (0,node_child_process__rspack_import_1.execFileSync)((0,node_path__rspack_import_4.join)(process.env.SystemRoot ?? "C:\\Windows", "System32/WindowsPowerShell/v1.0/powershell.exe"), [ + "-NoProfile", + "-NonInteractive", + "-Command", + script + ], { + input: blob.toString("base64"), + encoding: "utf8" + }); + return Buffer.from(out.trim(), "base64"); +} +function readWindowsSafeStorageKey(home, env, unprotectData) { + const path = (0,node_path__rspack_import_4.join)(grokBotAppDataPath(home, "win32", env), "Local State"); + const encryptedKey = (0,node_fs__rspack_import_2.existsSync)(path) ? JSON.parse((0,node_fs__rspack_import_2.readFileSync)(path, "utf8")).os_crypt?.encrypted_key : null; + const blob = Buffer.from(typeof encryptedKey === "string" ? encryptedKey : "", "base64"); + if (blob.subarray(0, 5).toString("latin1") !== "DPAPI") { + throw new GrokBotGatewaySessionError("MISSING_SAFE_STORAGE_KEY", "Grok Bot Local State has no Safe Storage key."); + } + return unprotectData(blob.subarray(5)); +} +function loadGrokBotGatewaySession({ platform = process.platform, home = (0,node_os__rspack_import_3.homedir)(), env = process.env, appData, getKeychainPassword = readKeychainPassword, unprotectData = unprotectWithDpapi } = {}) { + if (!SUPPORTED_PLATFORMS.has(platform)) return null; + const effectiveEnv = sessionEnv({ + env, + appData + }); + const path = grokBotGatewayDescriptorPath(home, platform, effectiveEnv); + if (!(0,node_fs__rspack_import_2.existsSync)(path)) return null; + const wrapped = JSON.parse((0,node_fs__rspack_import_2.readFileSync)(path, "utf8")); + const encrypted = encryptedPayload(wrapped); + let clear; + if (platform === "win32") { + clear = decryptWindowsSafeStorageString(encrypted, readWindowsSafeStorageKey(home, effectiveEnv, unprotectData)); + } else { + const prefix = Buffer.from(encrypted, "base64").subarray(0, 3).toString("latin1"); + // Linux v10 is the keyring-less basic_text backend; no secret store to ask. + const needsKeychain = !(platform === "linux" && prefix === SAFE_STORAGE_PREFIX_V10); + clear = decryptSafeStorageString(encrypted, needsKeychain ? getKeychainPassword(platform) : LINUX_BASIC_TEXT_PASSWORD, platform); + } + const descriptor = JSON.parse(clear); + if (!descriptor.baseUrl || !descriptor.token) { + throw new GrokBotGatewaySessionError("INCOMPLETE_DESCRIPTOR", "Decrypted Grok Bot gateway descriptor is incomplete."); + } + return { + gatewayUrl: String(descriptor.baseUrl).replace(/\/$/, ""), + gatewayToken: String(descriptor.token), + headers: descriptor.headers ?? {} + }; +} +function inspectGrokBotGatewaySession(options = {}) { + if (!hasGrokBotGatewaySession(options)) { + return { + present: false, + usable: false + }; + } + try { + loadGrokBotGatewaySession(options); + return { + present: true, + usable: true + }; + } catch (error) { + return { + present: true, + usable: false, + code: error instanceof GrokBotGatewaySessionError ? error.code : "UNUSABLE_SESSION", + error: error instanceof Error ? error.message : String(error) + }; + } +} + +__webpack_require__.d(__webpack_exports__, { + Z2: () => (loadGrokBotGatewaySession), + ZN: () => (hasGrokBotGatewaySession), + dQ: () => (grokBotGatewayDescriptorPath), + hd: () => (inspectGrokBotGatewaySession) +}); + + +}, +"./src/core/codex-bridge.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var node_net__rspack_import_2 = __webpack_require__("node:net"); +/* import */ var node_os__rspack_import_3 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_4 = __webpack_require__("node:path"); +/* import */ var node_child_process__rspack_import_5 = __webpack_require__("node:child_process"); +/* import */ var _package_json__rspack_import_6 = __webpack_require__("./package.json"); +/* import */ var _codex_contract_js__rspack_import_7 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _desktop_shim_js__rspack_import_8 = __webpack_require__("./src/core/desktop-shim.js"); + + + + + + + + + +// Method and param names below come from `codex app-server generate-json-schema` +// of this Codex release. Newer daemons usually keep them; `gbot codex status` +// reports the running daemon's version next to this one. +const PINNED_CODEX_VERSION = "0.154.0"; +const UPSTREAM_DESKTOP_ISSUES = [ + "https://github.com/openai/codex/issues/41014", + "https://github.com/openai/codex/issues/41112" +]; +const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; +// Transport budgets: fail fast instead of buffering unbounded attacker-controlled bytes. +// ponytail: raise these only with streaming/pagination support; the app-server sends small JSON-RPC frames. +const WS_MAX_HEADER_BYTES = 16 * 1024; +const WS_MAX_MESSAGE_BYTES = 4 * 1024 * 1024; +const WS_MAX_BUFFER_BYTES = 8 * 1024 * 1024; +const WS_MAX_WRITE_BYTES = 8 * 1024 * 1024; +const CODEX_MAX_REQUESTS = 128; +const CODEX_MAX_LISTENERS = 128; +const textDecoder = new TextDecoder("utf-8", { + fatal: true +}); +function codexSocketPath(env = process.env) { + // Explicit socket wins so status/send/queue agree with a shim-installed or + // operator-exported CODEX_APP_SERVER_SOCK; otherwise derive from CODEX_HOME. + if (env.CODEX_APP_SERVER_SOCK) return env.CODEX_APP_SERVER_SOCK; + const home = env.CODEX_HOME || (0,node_path__rspack_import_4.join)((0,node_os__rspack_import_3.homedir)(), ".codex"); + return (0,node_path__rspack_import_4.join)(home, "app-server-control", "app-server-control.sock"); +} +/** `socket` | `absent` | `permission-denied` | `not-a-socket`; permission failures are not absence. */ function socketState(path) { + try { + return (0,node_fs__rspack_import_1.statSync)(path).isSocket() ? "socket" : "not-a-socket"; + } catch (err) { + return err && (err.code === "EACCES" || err.code === "EPERM") ? "permission-denied" : "absent"; + } +} +/** Strip ANSI/OSC sequences and C0/C1 controls (tab and newline stay) from server-supplied text. */ function stripTerminalControls(text) { + return String(text).replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, "").replace(/\u001b./g, "").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g, ""); +} +/** Single-line fields (ids, names, paths, cursors, header tokens): no line breaks or tabs survive. */ function singleLine(text) { + return stripTerminalControls(text).replace(/[\t\n\r\u2028\u2029]+/g, " "); +} +function unreachableMessage(path, desktopAttached = "unknown") { + if (desktopAttached === "private-stdio") { + return [ + "ChatGPT Desktop is running its private stdio app-server, which external clients cannot reach", + "(" + UPSTREAM_DESKTOP_ISSUES.join(", ") + ").", + "No Codex app-server control socket at " + path + ": start a managed standalone daemon with `codex app-server daemon start`.", + "gbot codex targets daemon-managed threads only." + ].join("\n"); + } + return [ + "No Codex app-server control socket at " + path + ".", + "Either no daemon is running (start one with `codex app-server daemon start`),", + "or ChatGPT Desktop is running a private stdio app-server that external clients cannot reach", + "(" + UPSTREAM_DESKTOP_ISSUES.join(", ") + ").", + "gbot codex targets daemon-managed threads only." + ].join("\n"); +} +function windowsUnsupportedMessage() { + return [ + "gbot codex does not support native Windows yet.", + "Codex's control socket is AF_UNIX; this CLI's Node client only dials Unix domain sockets.", + "Use WSL, Linux, or macOS (or a future stdio proxy path)." + ].join("\n"); +} +function encodeFrame(opcode, payload, mask) { + const len = payload.length; + const head = Buffer.alloc(len < 126 ? 2 : len < 65536 ? 4 : 10); + head[0] = 0x80 | opcode; + if (len < 126) head[1] = len; + else if (len < 65536) { + head[1] = 126; + head.writeUInt16BE(len, 2); + } else { + head[1] = 127; + head.writeBigUInt64BE(BigInt(len), 2); + } + if (!mask) return Buffer.concat([ + head, + payload + ]); + head[1] |= 0x80; + const body = Buffer.from(payload); + for(let i = 0; i < body.length; i++)body[i] ^= mask[i & 3]; + return Buffer.concat([ + head, + mask, + body + ]); +} +function decodeFrame(buf) { + if (buf.length < 2) return null; + const fin = (buf[0] & 0x80) !== 0; + const opcode = buf[0] & 0x0f; + const masked = (buf[1] & 0x80) !== 0; + let len = buf[1] & 0x7f; + let offset = 2; + if (len === 126) { + if (buf.length < 4) return null; + len = buf.readUInt16BE(2); + offset = 4; + } else if (len === 127) { + if (buf.length < 10) return null; + len = Number(buf.readBigUInt64BE(2)); + offset = 10; + } + const mask = masked ? buf.subarray(offset, offset + 4) : null; + if (masked) offset += 4; + if (buf.length < offset + len) return null; + const payload = Buffer.from(buf.subarray(offset, offset + len)); + if (mask) for(let i = 0; i < payload.length; i++)payload[i] ^= mask[i & 3]; + return { + fin, + opcode, + masked, + payload, + rest: buf.subarray(offset + len) + }; +} +/** Claimed frame length without consuming; null when the length prefix is incomplete. */ function peekFrameLength(buf) { + if (buf.length < 2) return null; + const marker = buf[1] & 0x7f; + if (marker < 126) return marker; + if (marker === 126) { + if (buf.length < 4) return null; + return buf.readUInt16BE(2); + } + if (buf.length < 10) return null; + const big = buf.readBigUInt64BE(2); + return big > BigInt(Number.MAX_SAFE_INTEGER) ? Infinity : Number(big); +} +function validateUpgradeHead(head, key) { + const lines = head.split("\r\n"); + if (!/^HTTP\/1\.1 101/.test(lines[0])) return false; + const headers = new Map(); + for (const line of lines.slice(1)){ + const i = line.indexOf(":"); + if (i === -1) return false; + headers.set(line.slice(0, i).trim().toLowerCase(), line.slice(i + 1).trim()); + } + return headers.get("sec-websocket-accept") === websocketAccept(key) && (headers.get("upgrade") || "").toLowerCase() === "websocket" && (headers.get("connection") || "").toLowerCase().includes("upgrade"); +} +function upgradeRequest(key) { + return "GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: " + key + "\r\nSec-WebSocket-Version: 13\r\n\r\n"; +} +function websocketAccept(key) { + return (0,node_crypto__rspack_import_0.createHash)("sha1").update(key + WS_GUID).digest("base64"); +} +class CodexRpcError extends Error { + constructor(method, error){ + super("Codex app-server rejected " + method + ": " + (error && error.message ? error.message : JSON.stringify(error))); + this.name = "CodexRpcError"; + this.method = method; + this.rpc = error; + } +} +class CodexSendError extends Error { + constructor(message, { correlationId, delivery, hop, messageId, reason, refused, threadId, turnId } = {}){ + super(message); + this.name = "CodexSendError"; + this.delivery = delivery; + if (correlationId !== undefined) this.correlationId = correlationId; + if (hop !== undefined) this.hop = hop; + if (messageId !== undefined) this.messageId = messageId; + if (reason !== undefined) this.reason = reason; + if (refused !== undefined) this.refused = refused; + if (threadId !== undefined) this.threadId = threadId; + if (turnId !== undefined) this.turnId = turnId; + } +} +function attachEnvelope(error, envelope) { + if (!error || typeof error !== "object") return; + for (const key of [ + "messageId", + "correlationId", + "hop" + ]){ + if (envelope?.[key] !== undefined) error[key] = envelope[key]; + } +} +/** The route to the app-server is unavailable; `mode` is a stable machine-readable state. */ class CodexRouteError extends Error { + constructor(message, mode){ + super(message); + this.name = "CodexRouteError"; + this.mode = mode; + this.delivery = "rejected"; + this.reason = mode; + } +} +/** The app-server answered with a shape this pinned schema does not describe. */ class CodexProtocolError extends Error { + constructor(method, detail){ + super("Codex app-server returned an unexpected " + method + " response: " + detail + ". gbot is pinned to app-server schema " + PINNED_CODEX_VERSION + "; run `gbot codex status --json` to compare versions."); + this.name = "CodexProtocolError"; + this.method = method; + this.mode = "bad-response"; + this.reason = "bad-response"; + } +} +function isObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} +/** Failures before the WebSocket upgrade completes: the socket is present but unusable. */ function connectError(err, path) { + const code = err && err.cause && err.cause.code ? err.cause.code : err && err.code; + const message = err && err.message ? err.message : String(err); + if (code === "EACCES" || code === "EPERM" || /\bEACCES\b|\bEPERM\b/.test(message)) { + return new CodexRouteError("Codex app-server control socket at " + path + " refused the connection for this user (" + code + "). " + "gbot runs as the user who owns CODEX_HOME; check the socket's owner and mode.", "permission-denied"); + } + if (/refused the WebSocket upgrade|violated the WebSocket protocol|handshake headers exceed/.test(message)) { + return new CodexRouteError(message, "handshake-failed"); + } + return new CodexRouteError(message + " (socket present at " + path + ", but no app-server completed the connection).", "connect-failed"); +} +/** Failures while initializing an upgraded connection: reachable transport, unusable session. */ function handshakeError(err) { + if (err instanceof CodexProtocolError) return err; + const message = err && err.message ? err.message : String(err); + return new CodexRouteError("Codex app-server accepted the connection but initialize failed: " + message, "handshake-failed"); +} +/** Failures after a session exists: the request may or may not have been processed. */ function transportError(err) { + if (err instanceof CodexRpcError || err instanceof CodexProtocolError || err instanceof CodexSendError || err instanceof CodexRouteError) return err; + if (err && typeof err === "object" && err.reason === undefined) err.reason = "transport"; + return err; +} +/** + * Open a JSON-RPC session to the app-server over its Unix socket (WebSocket framing). + * Server requests are observed without answering by default. Legacy one-shot + * callers arm ownership-scoped refusals; persistent sessions respond explicitly. + */ function connectCodexAppServer(path, { timeoutMs = 15000, signal, onNotification, onServerRequest, onClose } = {}) { + return new Promise((resolve, reject)=>{ + if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) { + throw new RangeError("timeoutMs must be an integer 1-2147483647"); + } + for (const listener of [ + onNotification, + onServerRequest, + onClose + ]){ + if (listener !== undefined && typeof listener !== "function") throw new TypeError("Event listener must be a function"); + } + if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal"); + if (signal?.aborted) throw new Error("Codex connection aborted", { + cause: signal.reason + }); + const socket = (0,node_net__rspack_import_2.createConnection)({ + path + }); + const key = (0,node_crypto__rspack_import_0.randomBytes)(16).toString("base64"); + const pending = new Map(); + const refused = []; + const serverRequests = new Map(); + const listeners = { + notification: new Set(onNotification ? [ + onNotification + ] : []), + serverRequest: new Set(onServerRequest ? [ + onServerRequest + ] : []), + close: new Set(onClose ? [ + onClose + ] : []) + }; + let closeError; + let writeTimer; + let nextId = 1; + let buf = Buffer.alloc(0); + let upgraded = false; + let closed = false; + let fragOpcode = null; + let fragParts = []; + let fragBytes = 0; + // Absolute handshake deadline: socket timeouts reset on any bytes, so trickled + // headers must not extend this. Per-request timers stay absolute after upgrade. + const handshakeTimer = setTimeout(()=>failAll(new Error("Timed out connecting to Codex app-server at " + path)), timeoutMs); + if (typeof handshakeTimer.unref === "function") handshakeTimer.unref(); + const failAll = (err)=>{ + if (closed) return; + closed = true; + closeError = err; + clearTimeout(handshakeTimer); + clearTimeout(writeTimer); + signal?.removeEventListener("abort", abort); + if (err && err.delivery == null) err.delivery = pending.size ? "unknown" : "rejected"; + for (const { reject: rej } of pending.values())rej(err); + pending.clear(); + serverRequests.clear(); + client.deferred.length = 0; + buf = Buffer.alloc(0); + fragParts = []; + fragBytes = 0; + const closeListeners = [ + ...listeners.close + ]; + for (const group of Object.values(listeners))group.clear(); + try { + socket.destroy(); + } catch {} + reject(err); + for (const listener of closeListeners)invoke(listener, err, true); + }; + // Observers execute synchronously to preserve order, but failures never escape + // the socket callback. Rejected async callbacks use the same cleanup path. + const invoke = (listener, message, closing = false)=>{ + const failed = (cause)=>{ + if (!closing) failAll(new Error("Codex event listener failed", { + cause + })); + }; + try { + const result = listener(message); + if (result && typeof result.then === "function") Promise.resolve(result).catch(failed); + } catch (err) { + failed(err); + } + }; + const dispatch = (kind, message)=>{ + for (const listener of [ + ...listeners[kind] + ]){ + if (closed) break; + if (listeners[kind].has(listener)) invoke(listener, message); + } + }; + const subscribe = (kind, listener)=>{ + if (typeof listener !== "function") throw new TypeError("Event listener must be a function"); + if (closed) { + if (kind === "close") invoke(listener, closeError, true); + return ()=>{}; + } + const group = listeners[kind]; + if (!group.has(listener) && group.size >= CODEX_MAX_LISTENERS) { + const err = new Error("Codex listener limit exceeds " + CODEX_MAX_LISTENERS); + failAll(err); + throw err; + } + group.add(listener); + return ()=>group.delete(listener); + }; + const abort = ()=>failAll(new Error("Codex connection aborted", { + cause: signal.reason + })); + const failProtocol = (detail)=>failAll(new Error("Codex app-server violated the WebSocket protocol: " + detail)); + const write = (opcode, payload)=>{ + if (closed) throw closeError; + const encodedBytes = payload.length + (payload.length < 126 ? 6 : payload.length < 65536 ? 8 : 14); + if (socket.destroyed || encodedBytes + socket.writableLength > WS_MAX_WRITE_BYTES) { + const err = new Error(socket.destroyed ? "Codex socket closed" : "Codex outbound write budget exceeds " + WS_MAX_WRITE_BYTES + " bytes"); + failAll(err); + throw err; + } + try { + if (!socket.write(encodeFrame(opcode, payload, (0,node_crypto__rspack_import_0.randomBytes)(4))) && !writeTimer) { + // One absolute deadline for the whole backpressured interval: more + // writes must not keep an unread socket alive indefinitely. + writeTimer = setTimeout(()=>failAll(new Error("Codex outbound write did not drain within " + timeoutMs + "ms")), timeoutMs); + writeTimer.unref(); + } + } catch (err) { + failAll(err); + throw err; + } + }; + const sendJson = (obj)=>write(0x1, Buffer.from(JSON.stringify(obj))); + const respondToRequest = (id, payload)=>{ + if (closed) throw closeError; + if (!serverRequests.has(id)) throw new Error("Unknown or resolved server request: " + id); + // Consume ownership before JSON.stringify can invoke caller-owned getters + // or toJSON hooks. A failed serialization closes rather than restoring it. + serverRequests.delete(id); + client.deferred = client.deferred.filter((entry)=>entry.id !== id); + try { + sendJson({ + jsonrpc: "2.0", + id, + ...payload + }); + } catch (cause) { + if (closed) throw closeError; + const err = new Error("Codex server response serialization failed", { + cause + }); + failAll(err); + throw err; + } + }; + const client = { + refused, + get closed () { + return closed; + }, + onNotification: (listener)=>subscribe("notification", listener), + onServerRequest: (listener)=>subscribe("serverRequest", listener), + onClose: (listener)=>subscribe("close", listener), + respond: (id, result)=>respondToRequest(id, { + result + }), + rejectRequest: (id, error)=>respondToRequest(id, { + error + }), + // Server-initiated requests are only *answered* once our own turn/start + // is in flight, and then only when they name our own thread/turn: + // anything earlier — or naming another thread or Desktop turn — belongs + // to another client and must never be rejected on their behalf. Early + // and foreign requests are still recorded; the connection closes right + // after, so a pending request simply dies with it instead of denying + // someone's approval. + answerServerRequests: false, + expectedThreadId: null, + expectedTurnId: null, + // Approvals that name a turn while our own turn id is still unknown + // (arriving before — or in the same socket batch as — the turn/start + // acknowledgment) wait here instead of being classified foreign: once + // the acknowledgment supplies the turn id, matching ones are answered + // and the rest stay silent. + deferred: [], + // Adopt the acknowledged turn id, answering deferred requests that + // prove to be ours. Runs inside the connection closure so it can send. + _adoptTurn (turnId) { + client.expectedTurnId = turnId; + for (const entry of client.deferred.splice(0)){ + const params = entry.params && typeof entry.params === "object" && !Array.isArray(entry.params) ? entry.params : null; + const threadId = params ? params.threadId ?? params.thread_id : null; + const namedTurnId = params ? params.turnId ?? params.turn_id ?? (params.turn && params.turn.id) : null; + if (threadId === client.expectedThreadId && namedTurnId === turnId && serverRequests.get(entry.id) === entry) { + client.rejectRequest(entry.id, { + code: -32601, + message: "gbot codex does not answer " + entry.method + "; configure approval_policy on the daemon" + }); + entry.answered = true; + } + } + }, + request (method, params) { + return new Promise((res, rej)=>{ + if (closed) return rej(closeError); + if (pending.size >= CODEX_MAX_REQUESTS) { + const err = new Error("Codex pending request limit exceeds " + CODEX_MAX_REQUESTS); + failAll(err); + return rej(err); + } + const id = nextId++; + const timer = setTimeout(()=>{ + pending.delete(id); + rej(new Error("Codex app-server did not answer " + method + " within " + timeoutMs + "ms")); + }, timeoutMs); + pending.set(id, { + method, + resolve: (v)=>{ + clearTimeout(timer); + res(v); + }, + reject: (e)=>{ + clearTimeout(timer); + rej(e); + } + }); + try { + sendJson({ + jsonrpc: "2.0", + id, + method, + params + }); + } catch (err) { + const entry = pending.get(id); + pending.delete(id); + entry?.reject(err); + } + }); + }, + notify (method, params) { + sendJson({ + jsonrpc: "2.0", + method, + params + }); + }, + close () { + if (closed) return; + // Best effort protocol close; cleanup never depends on the peer reading it. + try { + if (upgraded) write(0x8, Buffer.from([ + 0x03, + 0xe8 + ])); + } catch {} + failAll(new Error("Codex client closed")); + } + }; + signal?.addEventListener("abort", abort, { + once: true + }); + const onMessage = (msg)=>{ + if (msg.id != null && msg.method) { + if (serverRequests.has(msg.id)) return failProtocol("duplicate pending server request id"); + if (serverRequests.size >= CODEX_MAX_REQUESTS || refused.length >= CODEX_MAX_REQUESTS || client.deferred.length >= CODEX_MAX_REQUESTS) { + return failAll(new Error("Codex remembered server request limit exceeds " + CODEX_MAX_REQUESTS)); + } + const entry = { + id: msg.id, + method: msg.method, + params: msg.params, + answered: false + }; + serverRequests.set(msg.id, entry); + dispatch("serverRequest", msg); + if (closed) return; + let answered = client.answerServerRequests; + let defer = false; + // Approval ownership: only answer requests for the turn gbot itself + // started. A request naming another thread — or naming a turn that is + // not ours — is recorded foreign-silent, never rejected. A request + // naming a turn while our turn id is still unknown is deferred, not + // classified: the turn/start acknowledgment decides it. + if (answered) { + const params = msg.params && typeof msg.params === "object" && !Array.isArray(msg.params) ? msg.params : null; + if (params) { + const threadId = params.threadId ?? params.thread_id; + const turnId = params.turnId ?? params.turn_id ?? (params.turn && params.turn.id); + if (threadId !== client.expectedThreadId || turnId == null) answered = false; + else if (client.expectedTurnId == null) { + answered = false; + defer = true; + } else if (turnId !== client.expectedTurnId) answered = false; + } else answered = false; + } + answered = answered && serverRequests.has(msg.id); + defer = defer && serverRequests.has(msg.id); + entry.answered = answered; + refused.push(entry); + if (defer) { + client.deferred.push(entry); + return; + } + if (!answered) return; + client.rejectRequest(msg.id, { + code: -32601, + message: "gbot codex does not answer " + msg.method + "; configure approval_policy on the daemon" + }); + return; + } + if (msg.id == null && msg.method) { + if (msg.method === "serverRequest/resolved") { + const id = msg.params?.requestId; + serverRequests.delete(id); + client.deferred = client.deferred.filter((entry)=>entry.id !== id); + } + dispatch("notification", msg); + return; + } + if (msg.id == null || !pending.has(msg.id)) return; + const entry = pending.get(msg.id); + pending.delete(msg.id); + if (msg.error) entry.reject(new CodexRpcError(entry.method, msg.error)); + else entry.resolve(msg.result); + }; + const onText = (payload)=>{ + let text; + try { + text = textDecoder.decode(payload); + } catch { + failAll(new Error("Codex app-server sent a non-UTF-8 text message")); + return; + } + let msg; + try { + msg = JSON.parse(text); + } catch (err) { + failAll(new Error("Codex app-server sent an unreadable message: " + err.message)); + return; + } + if (!msg || typeof msg !== "object" || Array.isArray(msg)) { + failAll(new Error("Codex app-server sent a malformed message")); + return; + } + try { + onMessage(msg); + } catch (err) { + failAll(err); + } + }; + socket.on("drain", ()=>{ + clearTimeout(writeTimer); + writeTimer = undefined; + }); + socket.once("error", (err)=>failAll(new Error("Could not connect to Codex app-server at " + path + ": " + err.message))); + socket.once("close", ()=>failAll(new Error("Codex app-server closed the connection"))); + socket.once("connect", ()=>socket.write(upgradeRequest(key))); + socket.on("data", (chunk)=>{ + if (closed) return; + buf = Buffer.concat([ + buf, + chunk + ]); + if (!upgraded) { + const end = buf.indexOf("\r\n\r\n"); + if (end === -1) { + if (buf.length > WS_MAX_HEADER_BYTES) failAll(new Error("Codex app-server handshake headers exceed " + WS_MAX_HEADER_BYTES + " bytes")); + return; + } + // Terminated headers hit the cap too; size is checked before any decoding. + if (end > WS_MAX_HEADER_BYTES) return failAll(new Error("Codex app-server handshake headers exceed " + WS_MAX_HEADER_BYTES + " bytes")); + const head = buf.subarray(0, end).toString(); + buf = buf.subarray(end + 4); + if (!validateUpgradeHead(head, key)) return failAll(new Error("Codex app-server refused the WebSocket upgrade: " + head.split("\r\n")[0])); + upgraded = true; + clearTimeout(handshakeTimer); + resolve(client); + } + while(!closed){ + const frame = decodeFrame(buf); + if (!frame) { + const claimed = peekFrameLength(buf); + if (claimed != null && claimed > WS_MAX_MESSAGE_BYTES) { + failAll(new Error("Codex app-server frame exceeds " + WS_MAX_MESSAGE_BYTES + " bytes")); + } else if (buf.length > WS_MAX_BUFFER_BYTES) { + failAll(new Error("Codex app-server buffer exceeds " + WS_MAX_BUFFER_BYTES + " bytes")); + } + return; + } + buf = frame.rest; + if (frame.payload.length > WS_MAX_MESSAGE_BYTES) return failAll(new Error("Codex app-server frame exceeds " + WS_MAX_MESSAGE_BYTES + " bytes")); + if (frame.masked) return failProtocol("server frames must not be masked"); + if (frame.opcode >= 0x8) { + if (!frame.fin || frame.payload.length > 125) return failProtocol("bad control frame"); + if (frame.opcode === 0x9) { + try { + write(0xa, frame.payload); + } catch { + return; + } + } else if (frame.opcode === 0x8) { + try { + write(0x8, frame.payload); + } catch { + return; + } + failAll(new Error("Codex app-server closed the connection")); + } + continue; // pong and other control frames carry nothing for us + } + if (frame.opcode === 0x0) { + if (fragOpcode == null) return failProtocol("continuation with nothing to continue"); + fragParts.push(frame.payload); + fragBytes += frame.payload.length; + if (fragBytes > WS_MAX_MESSAGE_BYTES) return failAll(new Error("Codex app-server message exceeds " + WS_MAX_MESSAGE_BYTES + " bytes")); + if (!frame.fin) continue; + const whole = Buffer.concat(fragParts, fragBytes); + const opcode = fragOpcode; + fragOpcode = null; + fragParts = []; + fragBytes = 0; + // ponytail: binary frames are unused by the app-server; only text is delivered. + if (opcode === 0x1) onText(whole); + continue; + } + if (frame.opcode === 0x1 || frame.opcode === 0x2) { + if (fragOpcode != null) return failProtocol("new message before finishing fragments"); + if (!frame.fin) { + fragOpcode = frame.opcode; + fragParts = [ + frame.payload + ]; + fragBytes = frame.payload.length; + continue; + } + // ponytail: binary frames are unused by the app-server; only text is delivered. + if (frame.opcode === 0x1) onText(frame.payload); + continue; + } + return failProtocol("unknown opcode " + frame.opcode); + } + }); + }); +} +function appServerVersion(initResult) { + const ua = initResult && typeof initResult.userAgent === "string" ? initResult.userAgent : ""; + const m = /^[^/\s]+\/(\S+)/.exec(ua); + return m ? m[1] : null; +} +/** Throws CodexRouteError when the operator's socket cannot be used; the path comes only from CODEX_HOME. */ function assertRoute(path) { + if (process.platform === "win32") throw new CodexRouteError(windowsUnsupportedMessage(), "windows-unsupported"); + const state = socketState(path); + if (state === "socket") return; + if (state === "permission-denied") { + throw new CodexRouteError("Codex app-server control socket at " + path + " exists but this user may not access it. " + "gbot runs as the user who owns CODEX_HOME; check the socket's owner and mode.", "permission-denied"); + } + if (state === "not-a-socket") { + throw new CodexRouteError(path + " exists but is not a Unix socket; remove the stale file and restart the daemon.", "not-a-socket"); + } + throw new CodexRouteError(unreachableMessage(path), "socket-absent"); +} +async function openCodexSession(env = process.env, { experimental = false, ...options } = {}) { + const path = codexSocketPath(env); + assertRoute(path); + let client; + try { + client = await connectCodexAppServer(path, options); + } catch (err) { + throw connectError(err, path); + } + let init; + try { + init = await client.request("initialize", { + clientInfo: { + name: "gbot", + version: _package_json__rspack_import_6/* .version */.rE + }, + ...experimental ? { + capabilities: { + experimentalApi: true + } + } : {} + }); + } catch (err) { + client.close(); + throw handshakeError(err); + } + if (!isObject(init)) { + client.close(); + throw new CodexProtocolError("initialize", "result is not an object"); + } + try { + client.notify("initialized"); + } catch (err) { + client.close(); + throw handshakeError(err); + } + return { + client, + path, + init + }; +} +const openSession = openCodexSession; +const CODEX_VERSION_PROBE_TIMEOUT_MS = 3000; +/** Bounded `codex --version` probe: `{ version, probe }` where probe is ok | missing | timeout | error. */ function probeLocalCodexVersion(timeoutMs = CODEX_VERSION_PROBE_TIMEOUT_MS) { + const out = (0,node_child_process__rspack_import_5.spawnSync)("codex", [ + "--version" + ], { + encoding: "utf8", + timeout: timeoutMs + }); + if (out.error) { + if (out.error.code === "ENOENT") return { + version: null, + probe: "missing" + }; + if (out.error.code === "ETIMEDOUT") return { + version: null, + probe: "timeout" + }; + return { + version: null, + probe: "error" + }; + } + const m = out.status === 0 ? /(\d+\.\d+\.\d+\S*)/.exec(out.stdout) : null; + return m ? { + version: m[1], + probe: "ok" + } : { + version: null, + probe: "error" + }; +} +/** Bounded `ps` snapshot for Desktop detection: process names only, never pipes or sockets. */ const DESKTOP_PROCESS_LIST_TIMEOUT_MS = 3000; +function listDesktopProcesses(timeoutMs = DESKTOP_PROCESS_LIST_TIMEOUT_MS) { + if (process.platform === "win32") return ""; + try { + const out = (0,node_child_process__rspack_import_5.spawnSync)("ps", [ + "-eo", + "args" + ], { + encoding: "utf8", + timeout: timeoutMs + }); + if (out.error || out.status !== 0 || typeof out.stdout !== "string") return ""; + return out.stdout; + } catch { + return ""; + } +} +/** + * Pure Desktop private-stdio detector. Returns `"private-stdio"` when the process list + * shows Desktop's bundled `.../ChatGPT.app/.../Resources/codex` running `app-server` + * (the `codex_app` override corroborates, the Resources path alone suffices); `"unknown"` + * otherwise. Never `"detached"`: absence of a match means "not observed", not "not running". + * Windows stays `"unknown"` (unsupported route, unchanged). + * + * @param {{ platform?: string, listProcesses?: string | string[] | null }} [opts] + */ function detectDesktopPrivateAppServer({ platform = process.platform, listProcesses = "" } = {}) { + if (platform === "win32") return "unknown"; + const lines = Array.isArray(listProcesses) ? listProcesses : String(listProcesses ?? "").split(/\r?\n/); + for (const line of lines){ + if (!/app-server/.test(line)) continue; + // Desktop's bundled binary only (Mac/Windows separators, optional .exe). + // Do NOT match probe shells whose cmdline merely mentions ChatGPT.app + + // app-server + codex-app-tools — that false-positives MATCH2 / Scout noise. + if (/ChatGPT\.app[\\/].*Resources[\\/]codex(\.exe)?(["'\s]|$)/.test(line)) return "private-stdio"; + } + return "unknown"; +} +/** + * Status contract: `reachable` is endpoint reachability only. `schema.compatibility` is + * `exact` when the daemon reports the pinned version, otherwise `unverified` (methods + * usually survive upgrades) or `unknown`. `desktopShimConfigured` records an installed + * wrapper selected by Desktop-facing CODEX_CLI_PATH (the GUI domain on Darwin). + * Configuration does not prove a running Desktop inherited it or connected. + * `desktopAttached` is `"private-stdio"` when a Desktop-bundled app-server process + * is visible, otherwise `"unknown"`. Managed attachment is not observable here. + * + * @param {NodeJS.ProcessEnv} [env] + * @param {{ listProcesses?: string | string[], shim?: { installed?: boolean, wrapperPointsAtShim?: boolean } | null }} [opts] + * injected process list and shim state for tests; defaults to a live `ps` snapshot and + * `desktopShimStatus`. Never reads pipes or connects to Desktop. + */ async function codexStatus(env = process.env, { listProcesses, shim } = {}) { + const path = codexSocketPath(env); + const cli = probeLocalCodexVersion(); + let desktopShimConfigured = Boolean(shim && shim.installed && shim.wrapperPointsAtShim); + if (shim === undefined) { + try { + const live = (0,_desktop_shim_js__rspack_import_8/* .desktopShimStatus */.em)({ + env + }); + desktopShimConfigured = Boolean(live.installed && live.wrapperPointsAtShim); + } catch { + desktopShimConfigured = false; + } + } + const desktopAttached = detectDesktopPrivateAppServer({ + platform: process.platform, + listProcesses: listProcesses ?? listDesktopProcesses() + }); + const base = { + socketPath: path, + socketState: socketState(path), + pinnedVersion: PINNED_CODEX_VERSION, + cliVersion: cli.version, + cliVersionProbe: cli.probe, + desktopAttached, + desktopShimConfigured + }; + let session; + try { + session = await openSession(env); + } catch (err) { + if (err instanceof CodexRouteError) { + // Name the private-stdio case explicitly: Desktop is up but unreachable, so the + // operator needs a managed standalone daemon, not a Desktop reconnect. + const message = err.mode === "socket-absent" ? unreachableMessage(path, desktopAttached) : err.message; + return (0,_codex_contract_js__rspack_import_7/* .withStatusExitCode */.AQ)({ + ...base, + reachable: false, + mode: err.mode, + message + }); + } + // The endpoint answered; what it said does not match the pinned schema. + if (err instanceof CodexProtocolError) return (0,_codex_contract_js__rspack_import_7/* .withStatusExitCode */.AQ)({ + ...base, + reachable: true, + mode: err.mode, + message: err.message + }); + throw err; + } + session.client.close(); + const daemonVersion = appServerVersion(session.init); + return (0,_codex_contract_js__rspack_import_7/* .withStatusExitCode */.AQ)({ + ...base, + reachable: true, + mode: "daemon", + daemonVersion, + codexHome: typeof session.init.codexHome === "string" ? session.init.codexHome : null, + schema: { + pinned: PINNED_CODEX_VERSION, + daemon: daemonVersion, + compatibility: daemonVersion == null ? "unknown" : daemonVersion === PINNED_CODEX_VERSION ? "exact" : "unverified" + }, + versionMismatch: Boolean(base.cliVersion && daemonVersion && base.cliVersion !== daemonVersion) + }); +} +const THREAD_STATUSES = new Set([ + "notLoaded", + "idle", + "active", + "systemError" +]); +function lineField(value) { + return value == null ? null : singleLine(value); +} +/** Server text fields are sanitized; structured values (Codex's `source: { custom }`) pass through untouched. */ function sourceField(value) { + if (value == null) return null; + return typeof value === "string" ? singleLine(value) : value; +} +function summarizeThread(t) { + if (!isObject(t) || typeof t.id !== "string" || !t.id) throw new CodexProtocolError("thread/list", "entry without a string `id`"); + const type = isObject(t.status) && typeof t.status.type === "string" ? t.status.type : "unknown"; + return { + id: singleLine(t.id), + status: THREAD_STATUSES.has(type) ? type : "unknown", + activeFlags: isObject(t.status) && Array.isArray(t.status.activeFlags) ? t.status.activeFlags.map((f)=>singleLine(f)) : [], + name: lineField(t.name), + preview: typeof t.preview === "string" ? stripTerminalControls(t.preview) : "", + cwd: lineField(t.cwd), + source: sourceField(t.source), + updatedAt: typeof t.updatedAt === "number" ? t.updatedAt : null + }; +} +const THREAD_LIST_MAX_LIMIT = 200; +/** + * @param {{ limit?: number, cursor?: string, env?: NodeJS.ProcessEnv }} [opts] + */ async function listCodexThreads({ limit = 20, cursor, env = process.env } = {}) { + if (!Number.isInteger(limit) || limit < 1 || limit > THREAD_LIST_MAX_LIMIT) { + throw new RangeError("--limit must be an integer 1-" + THREAD_LIST_MAX_LIMIT); + } + if (cursor !== undefined && (typeof cursor !== "string" || !cursor)) throw new RangeError("--cursor must be a non-empty string"); + const { client } = await openSession(env); + try { + // The default listing rescans every rollout file to repair metadata (26 s on a busy machine); + // the state DB already holds what we print. + const params = { + limit, + useStateDbOnly: true, + ...cursor !== undefined ? { + cursor + } : {} + }; + let out; + try { + out = await client.request("thread/list", params); + } catch (err) { + throw transportError(err); + } + if (!isObject(out) || !Array.isArray(out.data)) throw new CodexProtocolError("thread/list", "missing `data` array"); + if (out.nextCursor != null && typeof out.nextCursor !== "string") throw new CodexProtocolError("thread/list", "`nextCursor` is not a string"); + const threads = out.data.map(summarizeThread); + return { + threads, + nextCursor: out.nextCursor ?? null, + limit + }; + } finally{ + client.close(); + } +} +function explainSendError(err, threadId) { + if (!(err instanceof CodexRpcError)) return err; + const msg = String(err.rpc && err.rpc.message || ""); + if (/no rollout found|thread not found/i.test(msg)) { + return new Error("Unknown Codex thread " + threadId + ". Run `gbot codex list-threads` to see reachable threads."); + } + if (/active writer/i.test(msg)) { + return new Error("Codex thread " + threadId + " is open in another client (VS Code, TUI, or Desktop), which owns its turns. Close it there first."); + } + return err; +} +const DEFAULT_MAX_HOPS = 4; +const ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/; +/** + * Delivery envelope: `messageId` names this send, `correlationId` names the conversation it + * belongs to, `replyTo` names the message it answers, `hop` counts agent-to-agent forwards. + * `maxHops` (GROK_BOT_MAX_HOPS) bounds relays: a reply must carry hop = incoming hop + 1, and a + * send at or past the bound is refused, so two agents cannot ack each other forever. + * The textual header is caller-authored provenance for the reader, not authentication. + * @param {{ correlationId?: string, replyTo?: string, hop?: number, envelope?: boolean, env?: NodeJS.ProcessEnv }} [opts] + */ function buildEnvelope({ correlationId, replyTo, hop, envelope = false, env = process.env } = {}) { + const maxHops = Number.parseInt(env.GROK_BOT_MAX_HOPS ?? "", 10); + const bound = Number.isInteger(maxHops) && maxHops >= 0 ? maxHops : DEFAULT_MAX_HOPS; + for (const [name, value] of [ + [ + "--correlation-id", + correlationId + ], + [ + "--reply-to", + replyTo + ] + ]){ + if (value !== undefined && !ID_PATTERN.test(value)) throw new RangeError(name + " must be 1-128 characters of [A-Za-z0-9_.:-]"); + } + const hopCount = hop === undefined ? 0 : hop; + if (!Number.isInteger(hopCount) || hopCount < 0) throw new RangeError("--hop must be a non-negative integer"); + if (replyTo !== undefined && correlationId === undefined) { + throw new RangeError("--reply-to needs the original --correlation-id so the reply stays in its conversation"); + } + const messageId = (0,node_crypto__rspack_import_0.randomUUID)(); + const out = { + messageId, + correlationId: correlationId ?? messageId, + hop: hopCount, + maxHops: bound, + header: envelope || replyTo !== undefined || hop !== undefined || correlationId !== undefined + }; + if (replyTo !== undefined) out.replyTo = replyTo; + if (hopCount >= bound) { + throw new CodexSendError("Refusing to send: hop " + hopCount + " reaches the relay bound " + bound + " (GROK_BOT_MAX_HOPS). " + "This message is an agent-to-agent relay that has already been forwarded too many times.", { + delivery: "rejected", + reason: "hop-limit", + ...out + }); + } + return out; +} +/** One-line header a receiving agent can read to reply with `--reply-to` and `--hop N+1`. */ const identityToken = (value)=>String(value ?? "").replace(/[^A-Za-z0-9_.:-]/g, "").slice(0, 64) || "unknown"; +function envelopeHeader(envelope, env = process.env) { + const from = identityToken(env.USER || env.USERNAME) + "@" + hostnameSafe(); + const parts = [ + "msg=" + envelope.messageId, + "corr=" + envelope.correlationId + ]; + if (envelope.replyTo) parts.push("reply-to=" + envelope.replyTo); + parts.push("hop=" + envelope.hop, "from=" + from); + return "[gbot " + parts.join(" ") + "]"; +} +function hostnameSafe() { + try { + return identityToken((0,node_os__rspack_import_3.hostname)()); + } catch { + return "unknown"; + } +} +function withEnvelopeHeader(text, envelope, env = process.env) { + return envelope.header ? envelopeHeader(envelope, env) + "\n" + text : text; +} +/** Operator-controlled destinations: GROK_BOT_CODEX_THREADS="id,id" restricts `codex send`. */ function assertThreadAllowed(threadId, env = process.env) { + const raw = env.GROK_BOT_CODEX_THREADS; + if (raw == null || raw.trim() === "") return; + const allowed = raw.split(",").map((s)=>s.trim()).filter(Boolean); + if (!allowed.includes(threadId)) { + throw new CodexSendError("Codex thread " + threadId + " is not in GROK_BOT_CODEX_THREADS; the operator allows only: " + allowed.join(", "), { + delivery: "rejected", + reason: "route-not-allowed", + threadId + }); + } +} +/** + * Busy destinations. In app-server 0.154.0 `turn/start` on a thread with an active turn steers + * that turn instead of queueing (TurnStartParams.turnTrigger: "Ignored when this request steers + * an already-active turn"). gbot never steers or interrupts human work: an `active` thread is + * refused with a `busy` receipt, or, with `whenBusy: "queue"`, handed to the daemon's own queue + * through the experimental `thread/queue/add`. See docs/codex-busy-threads.md. + */ function threadState(resumed, threadId) { + const status = resumed.thread.status; + const type = isObject(status) && typeof status.type === "string" ? status.type : "unknown"; + if (type === "idle" || type === "notLoaded") return { + type, + busy: false + }; + if (type === "active") { + const flags = Array.isArray(status.activeFlags) ? status.activeFlags.map((f)=>singleLine(f)) : []; + return { + type, + busy: true, + flags + }; + } + if (type === "systemError") { + throw new CodexSendError("Codex thread " + threadId + " is in systemError state; open it in a Codex client first.", { + delivery: "rejected", + reason: "thread-error", + threadId + }); + } + throw new CodexSendError("Codex thread " + threadId + " reports status " + JSON.stringify(type) + ", which this gbot (pinned to app-server " + PINNED_CODEX_VERSION + ") does not know; not sending.", { + delivery: "rejected", + reason: "unknown-status", + threadId + }); +} +function experimentalEnabled(env = process.env) { + return /^(1|true|on)$/i.test(env.GROK_BOT_CODEX_EXPERIMENTAL || ""); +} +function requireExperimental(env, what) { + if (experimentalEnabled(env)) return; + throw new CodexSendError(what + " uses Codex's experimental app-server API (thread/queue/*), which is off by default. " + "Set GROK_BOT_CODEX_EXPERIMENTAL=1 to opt in; method names are pinned to Codex " + PINNED_CODEX_VERSION + ".", { + delivery: "rejected", + reason: "experimental-disabled" + }); +} +function unsupportedOrRpc(err, method, threadId, envelope, turnId) { + const guarded = method === "turn/steer"; + if (err instanceof CodexRpcError && err.rpc && err.rpc.code === -32601) { + return new CodexSendError("Codex app-server does not offer " + method + " (daemon predates it, or experimentalApi was not granted). " + (guarded ? "Upgrade Codex before retrying guarded steering." : "Upgrade Codex or send without --when-busy queue."), { + delivery: "rejected", + reason: "unsupported", + threadId, + turnId, + ...envelope + }); + } + if (err instanceof CodexRpcError) return new CodexSendError(err.message, { + delivery: "rejected", + reason: "rejected", + threadId, + turnId, + ...envelope + }); + return new CodexSendError("Lost the Codex " + method + " response for thread " + threadId + ": " + (err && err.message || err) + (guarded ? ". Delivery is unknown; check thread " + threadId + " turn " + turnId + " before resending." : ". Delivery is unknown; list the queue before resending."), { + delivery: err && err.delivery || "unknown", + reason: "transport", + threadId, + turnId, + ...envelope + }); +} +/** Read the daemon's queue for one thread (experimental `thread/queue/list`). */ async function listCodexQueue(threadId, { env = process.env, limit = 50, cursor } = {}) { + requireExperimental(env, "gbot codex queue"); + const { client } = await openSession(env, { + experimental: true + }); + try { + let out; + try { + out = await client.request("thread/queue/list", { + threadId, + limit, + ...cursor !== undefined ? { + cursor + } : {} + }); + } catch (err) { + throw unsupportedOrRpc(err, "thread/queue/list", threadId); + } + if (!isObject(out) || !Array.isArray(out.data)) throw new CodexProtocolError("thread/queue/list", "missing `data` array"); + return { + threadId, + queued: out.data.map((q)=>({ + id: isObject(q) && typeof q.id === "string" ? singleLine(q.id) : null, + clientUserMessageId: isObject(q) && typeof q.clientUserMessageId === "string" ? singleLine(q.clientUserMessageId) : null, + text: isObject(q) && Array.isArray(q.input) ? q.input.map((part)=>isObject(part) && typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n") : "" + })), + nextCursor: typeof out.nextCursor === "string" ? out.nextCursor : null + }; + } finally{ + client.close(); + } +} +/** + * @param {string} threadId + * @param {string} text + * @param {{ env?: NodeJS.ProcessEnv, envelope?: object, whenBusy?: "reject"|"queue"|"steer", session?: object, expectedTurnId?: string, expectedCwd?: string, signal?: AbortSignal }} [opts] + */ async function sendToCodexThread(threadId, text, { env = process.env, envelope = buildEnvelope({ + env +}), whenBusy = "reject", session, expectedTurnId, expectedCwd, signal } = {}) { + try { + const receipt = await sendToCodexThreadInner(threadId, text, { + env, + envelope, + whenBusy, + session, + expectedTurnId, + expectedCwd, + signal + }); + return (0,_codex_contract_js__rspack_import_7/* .outcomeFromReceipt */.Dz)(receipt); + } catch (err) { + // Every receipt names the message, including refusals that never reached the daemon. + if (err && typeof err === "object") { + attachEnvelope(err, envelope); + if (err.threadId === undefined) err.threadId = threadId; + } + return (0,_codex_contract_js__rspack_import_7/* .outcomeFromError */.DG)(err); + } +} +async function sendToCodexThreadInner(threadId, text, { env, envelope, whenBusy, session, expectedTurnId, expectedCwd, signal }) { + if (![ + "reject", + "queue", + ...session ? [ + "steer" + ] : [] + ].includes(whenBusy)) throw new RangeError("--when-busy must be reject, queue, or persistent steer"); + if (whenBusy === "steer" && (typeof expectedTurnId !== "string" || !ID_PATTERN.test(expectedTurnId))) throw new RangeError("steer requires expectedTurnId"); + if (typeof threadId !== "string" || !ID_PATTERN.test(threadId)) throw new RangeError("Invalid threadId"); + if (typeof text !== "string" || !text.trim() || Buffer.byteLength(text) > WS_MAX_MESSAGE_BYTES) throw new RangeError("Message must contain text within 4 MiB"); + if (!envelope || typeof envelope.messageId !== "string" || !ID_PATTERN.test(envelope.messageId)) throw new RangeError("Invalid envelope messageId"); + const validated = buildEnvelope({ + correlationId: envelope.correlationId, + replyTo: envelope.replyTo, + hop: envelope.hop, + env + }); + envelope = { + ...validated, + messageId: envelope.messageId, + header: Boolean(envelope.header) + }; + assertThreadAllowed(threadId, env); + if (whenBusy === "queue") requireExperimental(env, "--when-busy queue"); + if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal"); + const assertNotCancelled = ()=>{ + if (signal?.aborted) throw new CodexSendError("Codex submission cancelled before delivery", { + delivery: "rejected", + reason: "cancelled", + threadId, + turnId: whenBusy === "steer" ? expectedTurnId : undefined, + ...envelope + }); + }; + assertNotCancelled(); + const body = withEnvelopeHeader(text, envelope, env); + const { client } = session ?? await openSession(env, { + experimental: whenBusy === "queue", + signal + }); + try { + let resumed; + try { + resumed = await client.request("thread/resume", { + threadId, + excludeTurns: true + }); + } catch (err) { + assertNotCancelled(); + if (err instanceof CodexSendError) throw err; + throw new CodexSendError(explainSendError(err, threadId).message, { + delivery: err instanceof CodexRpcError ? "rejected" : err && err.delivery || "unknown", + reason: err instanceof CodexRpcError ? /no rollout found|thread not found/i.test(String(err.rpc && err.rpc.message)) ? "unknown-thread" : /active writer/i.test(String(err.rpc && err.rpc.message)) ? "external-owner" : "rejected" : "transport", + threadId, + ...envelope + }); + } + // A shared session stays connected when this conversation is cancelled. + // Recheck after the last awaited preflight, before any submission request. + assertNotCancelled(); + if (!isObject(resumed) || !isObject(resumed.thread) || typeof resumed.thread.id !== "string") { + throw new CodexProtocolError("thread/resume", "missing `thread.id`"); + } + if (resumed.thread.id !== threadId) throw new CodexSendError("thread/resume returned a different thread ID", { + delivery: "rejected", + reason: "bad-response", + threadId, + ...envelope + }); + if (expectedCwd !== undefined && (0,node_fs__rspack_import_1.realpathSync)(resumed.cwd ?? resumed.thread.cwd) !== (0,node_fs__rspack_import_1.realpathSync)(expectedCwd)) throw new CodexSendError("Codex thread cwd does not match expectedCwd", { + delivery: "rejected", + reason: "cwd-mismatch", + threadId, + ...envelope + }); + const state = threadState(resumed, threadId); + const receiptBase = { + threadId: resumed.thread.id, + threadStatus: state.type, + model: resumed.model, + cwd: resumed.cwd, + approvalPolicy: resumed.approvalPolicy, + messageId: envelope.messageId, + correlationId: envelope.correlationId, + ...envelope.replyTo ? { + replyTo: envelope.replyTo + } : {}, + hop: envelope.hop, + maxHops: envelope.maxHops + }; + if (state.busy && whenBusy === "reject") { + const flags = state.flags.length ? " (" + state.flags.join(", ") + ")" : ""; + throw new CodexSendError("Codex thread " + threadId + " has an active turn" + flags + "; sending now would steer that turn. " + "Wait for it to go idle (`gbot codex list-threads`) and resend, or pass --when-busy queue.", { + delivery: "rejected", + reason: "busy", + threadId, + ...envelope + }); + } + if (whenBusy === "steer") { + let steered; + try { + steered = await client.request("turn/steer", { + threadId, + expectedTurnId, + clientUserMessageId: envelope.messageId, + input: [ + { + type: "text", + text: body + } + ] + }); + } catch (err) { + throw unsupportedOrRpc(err, "turn/steer", threadId, envelope, expectedTurnId); + } + if (typeof steered?.turnId !== "string" || steered.turnId !== expectedTurnId) { + throw new CodexSendError("Malformed turn/steer acknowledgment", { + delivery: "unknown", + reason: "bad-response", + threadId, + turnId: expectedTurnId, + ...envelope + }); + } + return { + delivery: "accepted", + ...receiptBase, + turnId: steered.turnId + }; + } + if (state.busy) { + let queued; + try { + queued = await client.request("thread/queue/add", { + threadId, + clientUserMessageId: envelope.messageId, + input: [ + { + type: "text", + text: body + } + ] + }); + } catch (err) { + throw unsupportedOrRpc(err, "thread/queue/add", threadId, envelope); + } + const submission = isObject(queued) && isObject(queued.queuedSubmission) && typeof queued.queuedSubmission.id === "string" ? queued.queuedSubmission : null; + if (!submission) { + throw new CodexSendError("Codex app-server sent a malformed thread/queue/add acknowledgment for thread " + threadId + ". Delivery is unknown; list the queue before resending.", { + delivery: "unknown", + reason: "bad-response", + threadId, + ...envelope + }); + } + return { + delivery: "queued", + ...receiptBase, + queuedSubmissionId: submission.id, + activeFlags: state.flags + }; + } + // ponytail: idle-at-resume then turn/start is a small race with a human starting a turn first; + // the daemon exposes no compare-and-start request. Upgrade path: thread/queue/add + thread/queue/start once stable. + // Scope refusals to this turn: server requests from earlier calls belong to another context. + const seenRefused = client.refused.length; + // Arm refusal replies only now that our own turn/start is in flight, scoped + // to our own thread/turn: anything recorded earlier (resume, busy reject, + // queue) — or naming another thread or Desktop turn — stays unanswered so + // gbot never rejects another client's approval. Requests naming a turn + // that arrives before the acknowledgment supplies our turn id wait in + // client.deferred and are adopted only on a match. Requests missing + // thread or turn IDs remain unanswered because ownership is unknown. + if (!session) { + client.expectedThreadId = threadId; + client.expectedTurnId = null; + client.answerServerRequests = true; + } + let turn; + try { + turn = await client.request("turn/start", { + threadId, + input: [ + { + type: "text", + text: body + } + ], + clientUserMessageId: envelope.messageId, + turnTrigger: "gbot" + }); + } catch (err) { + if (err instanceof CodexSendError) throw err; + const delivery = err instanceof CodexRpcError ? "rejected" : err && err.delivery || "unknown"; + const detail = err instanceof CodexRpcError ? err.message : "Lost the Codex turn/start response for thread " + threadId + ": " + (err && err.message || err) + ". Delivery is unknown; check the thread before resending."; + // No blind retry: the receipt carries messageId so the caller can look for it before resending. + throw new CodexSendError(detail, { + delivery, + reason: delivery === "rejected" ? "rejected" : "transport", + threadId, + ...envelope + }); + } + const turnId = turn && turn.turn && typeof turn.turn.id === "string" && turn.turn.id ? turn.turn.id : null; + if (!turnId) { + throw new CodexSendError("Codex app-server sent a malformed turn/start acknowledgment for thread " + threadId + ". Delivery is unknown; check the thread before resending.", { + delivery: "unknown", + reason: "bad-response", + threadId, + ...envelope + }); + } + if (!session) client._adoptTurn(turnId); + const freshRefused = client.refused.slice(seenRefused).filter((r)=>{ + if (!r.answered) return false; + const params = r.params && typeof r.params === "object" && !Array.isArray(r.params) ? r.params : null; + if (!params) return true; + const refusedThreadId = params.threadId ?? params.thread_id; + const refusedTurnId = params.turnId ?? params.turn_id ?? (params.turn && params.turn.id); + if (refusedThreadId != null && refusedThreadId !== threadId) return false; + if (refusedTurnId != null && refusedTurnId !== turnId) return false; + return true; + }); + if (freshRefused.length) { + const methods = freshRefused.map((r)=>r.method).join(", "); + throw new CodexSendError("Turn " + turnId + " started on thread " + threadId + " but Codex asked for " + methods + ", which gbot refused. " + "Answer it in a Codex client, or set `approval_policy = \"never\"` in the daemon's config.toml for unattended sends.", { + delivery: "accepted", + reason: "approval-refused", + threadId, + turnId, + refused: freshRefused.map((r)=>r.method), + ...envelope + }); + } + return { + delivery: "accepted", + ...receiptBase, + turnId, + turnStatus: turn.turn.status + }; + } finally{ + if (!session) client.close(); + } +} + +__webpack_require__.d(__webpack_exports__, { + $3: () => (assertThreadAllowed), + Bt: () => (listCodexQueue), + MU: () => (codexStatus), + Mr: () => (withEnvelopeHeader), + X$: () => (listCodexThreads), + ZS: () => (sendToCodexThread), + e0: () => (experimentalEnabled), + eC: () => (openCodexSession), + nq: () => (buildEnvelope), + pF: () => (singleLine), + ql: () => (codexSocketPath) +}); + + +}, +"./src/core/codex/contract.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _url_policy_js__rspack_import_0 = __webpack_require__("./src/core/url-policy.js"); +/** + * #46 Codex contract documents and exit-code derivation. + * The bridge and the CLI routes flatten through these helpers so reason/delivery + * spelling stays one owner. No process I/O here. + */ +/** @typedef {'accepted' | 'queued' | 'rejected' | 'unknown'} CodexDelivery */ /** + * @typedef {{ + * delivery: CodexDelivery, + * exitCode: 0 | 1, + * error?: string, + * reason?: string, + * mode?: string, + * threadId?: string, + * turnId?: string, + * turnStatus?: string, + * queuedSubmissionId?: string, + * refused?: string[], + * messageId?: string, + * correlationId?: string, + * hop?: number, + * replyTo?: string, + * threadStatus?: string, + * model?: string, + * cwd?: string, + * approvalPolicy?: string, + * maxHops?: number, + * }} CodexSendOutcome + */ /** + * Exit 0 iff the daemon is usable. + * @param {{ reachable: boolean, mode: string }} status + * @returns {0 | 1} + */ function statusExitCode(status) { + return status.reachable && status.mode === "daemon" ? 0 : 1; +} +/** + * Attach derived exitCode to a status document (never mutates input). + * @param {Record} status + */ function withStatusExitCode(status) { + return { + ...status, + exitCode: statusExitCode(/** @type {{ reachable: boolean, mode: string }} */ status) + }; +} +/** + * @param {{ + * delivery: CodexDelivery, + * reason?: string, + * error?: string, + * }} outcome + * @returns {0 | 1} + */ function sendExitCode(outcome) { + if (outcome.error !== undefined) return 1; + if (outcome.delivery === "accepted" && outcome.reason === "approval-refused") return 1; + if (outcome.delivery === "rejected" || outcome.delivery === "unknown") return 1; + return 0; +} +/** + * Flatten a thrown error into the #46 send/failure document (plus exitCode). + * + * @param {unknown} error + * @param {{ isUsage?: (err: unknown) => boolean }} [opts] + * @returns {CodexSendOutcome & { error: string, exitCode: 1 }} + */ function outcomeFromError(error, opts = {}) { + const isUsage = opts.isUsage ?? ((err)=>err instanceof RangeError || Boolean(err && typeof err === "object" && err.name === "StoreError")); + const message = (0,_url_policy_js__rspack_import_0/* .redactSecrets */.fp)(error instanceof Error ? error.message : String(error)); + /** @type {Record} */ const out = { + error: message + }; + if (error && typeof error === "object") { + for (const key of [ + "delivery", + "reason", + "mode", + "threadId", + "turnId", + "targetId", + "messageId", + "correlationId", + "refused", + "hop" + ]){ + if (error[key] !== undefined) out[key] = error[key]; + } + if (out.reason === undefined && isUsage(error)) out.reason = "usage"; + } + if (out.delivery === undefined) out.delivery = "rejected"; + return /** @type {CodexSendOutcome & { error: string, exitCode: 1 }} */ { + ...out, + exitCode: 1 + }; +} +/** + * Normalize a successful send receipt into a document with exitCode. + * @param {Record} receipt + * @returns {CodexSendOutcome} + */ function outcomeFromReceipt(receipt) { + const base = { + ...receipt + }; + if (base.delivery === undefined) base.delivery = "accepted"; + const exitCode = sendExitCode(/** @type {{ delivery: CodexDelivery, reason?: string, error?: string }} */ base); + if (exitCode === 1 && base.error === undefined && base.reason === "approval-refused") { + base.error = typeof base.message === "string" ? base.message : "Codex refused one or more approvals."; + } + return /** @type {CodexSendOutcome} */ { + ...base, + exitCode + }; +} + +__webpack_require__.d(__webpack_exports__, { + AQ: () => (withStatusExitCode), + DG: () => (outcomeFromError), + Dz: () => (outcomeFromReceipt) +}); + + +}, +"./src/core/codex/conversation.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _contract_js__rspack_import_0 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var _codex_bridge_js__rspack_import_2 = __webpack_require__("./src/core/codex-bridge.js"); + + + +const ID = /^[A-Za-z0-9_.:-]{1,128}$/; +const BUDGET = 4 * 1024 * 1024; +function conversationId(value, name = 'threadId') { + if (typeof value !== 'string' || !ID.test(value)) throw new RangeError(`${name} must be 1-128 identifier characters`); + return value; +} +function boundedInteger(value, max, name) { + if (!Number.isInteger(value) || value < 1 || value > max) throw new RangeError(`${name} must be an integer 1-${max}`); + return value; +} +const terminal = (status)=>[ + 'completed', + 'failed', + 'interrupted' + ].includes(status); +const namedTurn = (p)=>p?.turnId ?? p?.turn_id ?? p?.turn?.id; +/** Bounded traversal; a coverage failure throws and must never be interpreted as not found. */ async function visitCodexHistory(session, threadId, method, params, visit, { signal, stopped = ()=>false } = {}) { + if (![ + 'thread/turns/list', + 'thread/items/list' + ].includes(method)) throw new RangeError('Unsupported history method'); + conversationId(threadId); + const client = session.client; + let cursor; + const seen = new Set(); + for(let page = 0; page < 20; page++){ + if (stopped() || signal?.aborted) throw new Error('History coverage incomplete: observation cancelled'); + const result = await client.request(method, { + ...params, + threadId, + limit: 100, + ...cursor ? { + cursor + } : {} + }); + if (stopped() || signal?.aborted) throw new Error('History coverage incomplete: observation cancelled'); + if (!Array.isArray(result?.data) || result.data.length > 100 || result.nextCursor != null && (typeof result.nextCursor !== 'string' || !result.nextCursor || result.nextCursor.length > 4096)) throw new Error(`Invalid ${method} page`); + if (visit(result.data)) return { + complete: false, + reason: 'matched', + pages: page + 1 + }; + if (result.nextCursor == null) return { + complete: true, + reason: 'exhausted', + pages: page + 1 + }; + if (seen.has(result.nextCursor)) throw new Error('History coverage incomplete: repeated pagination cursor'); + seen.add(result.nextCursor); + cursor = result.nextCursor; + } + throw new Error('History coverage incomplete: 20 page limit'); +} +/** A bounded observer. Cancellation ends observation, never the daemon's turn. */ async function openCodexConversation(threadId, options = {}) { + conversationId(threadId); + const { env = process.env, expectedCwd, signal, onEvent } = options; + (0,_codex_bridge_js__rspack_import_2/* .assertThreadAllowed */.$3)(threadId, env); + if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError('signal must be an AbortSignal'); + if (onEvent !== undefined && typeof onEvent !== 'function') throw new TypeError('onEvent must be a function'); + if (signal?.aborted) throw new Error('Observation cancelled'); + const expected = expectedCwd === undefined ? undefined : (0,node_fs__rspack_import_1.realpathSync)(expectedCwd); + const session = options.session ?? await (0,_codex_bridge_js__rspack_import_2/* .openCodexSession */.eC)(env, { + signal, + experimental: (0,_codex_bridge_js__rspack_import_2/* .experimentalEnabled */.e0)(env) + }); + const { client } = session; + const events = []; + const acceptedTurns = new Set(); + const wake = new Set(); + let bytes = 0, overflow = false, disconnected = client.closed, closed = false; + const record = (event)=>{ + const size = Buffer.byteLength(JSON.stringify(event)); + if (size > BUDGET) { + overflow = true; + } else { + while(events.length >= 500 || bytes + size > BUDGET){ + bytes -= events.shift().bytes; + overflow = true; + } + events.push({ + event, + bytes: size + }); + bytes += size; + } + for (const listener of [ + ...wake + ])listener(); + return onEvent?.(event); + }; + const observe = (kind)=>(message)=>{ + const p = message.params; + if ((p?.threadId ?? p?.thread_id) !== threadId) return; + return record({ + kind, + ...message + }); + }; + const unsubs = [ + client.onNotification(observe('notification')), + client.onServerRequest(observe('interaction')), + client.onClose((error)=>{ + disconnected = true; + return record({ + kind: 'disconnect', + error: error?.message + }); + }) + ]; + const close = async ()=>{ + if (closed) return; + closed = true; + for (const unsubscribe of unsubs)unsubscribe(); + for (const listener of wake)listener(); + if (!options.session) client.close(); + }; + let resumed; + try { + resumed = await client.request('thread/resume', { + threadId, + excludeTurns: true + }); + if (resumed?.thread?.id !== threadId) throw new Error('thread/resume returned a different thread ID'); + const cwd = resumed.cwd ?? resumed.thread.cwd; + if (expected !== undefined && (typeof cwd !== 'string' || (0,node_fs__rspack_import_1.realpathSync)(cwd) !== expected)) throw new Error('Codex thread cwd does not match expectedCwd'); + } catch (error) { + await close(); + throw error; + } + /** @param {{turnId: string, messageId?: string, afterMessageId?: string|string[], timeoutMs?: number, signal?: AbortSignal, maxOutputBytes?: number}} options */ async function wait({ turnId, messageId, afterMessageId, timeoutMs = 120000, signal: waitSignal, maxOutputBytes = 1048576 }) { + conversationId(turnId, 'turnId'); + if (messageId !== undefined) conversationId(messageId, 'messageId'); + const anchors = afterMessageId === undefined ? [] : Array.isArray(afterMessageId) ? afterMessageId : [ + afterMessageId + ]; + if (afterMessageId !== undefined) boundedInteger(anchors.length, 200, 'afterMessageId count'); + for (const anchor of anchors)conversationId(anchor, 'afterMessageId'); + boundedInteger(timeoutMs, 600000, 'timeoutMs'); + boundedInteger(maxOutputBytes, BUDGET, 'maxOutputBytes'); + if (waitSignal !== undefined && !(waitSignal instanceof AbortSignal)) throw new TypeError('signal must be an AbortSignal'); + let done = false, status = acceptedTurns.has(turnId) ? 'inProgress' : undefined, error, historyError, itemBytes = 0, truncated = overflow; + const items = new Map(); + const add = (item)=>{ + if (!item || typeof item.id !== 'string' || typeof item.type !== 'string') throw new Error('Invalid history item'); + if (item.type !== 'agentMessage' || typeof item.text !== 'string' || item.phase !== 'final_answer' && item.phase != null) return; + const normalized = { + id: item.id, + type: item.type, + phase: item.phase ?? null, + text: item.text + }; + const size = Buffer.byteLength(JSON.stringify(normalized)); + const prior = items.get(item.id); + if (itemBytes - (prior?.bytes ?? 0) + size > BUDGET || !prior && items.size >= 2000) { + truncated = true; + return; + } + itemBytes += size - (prior?.bytes ?? 0); + items.set(item.id, { + item: normalized, + bytes: size + }); + }; + const scan = ()=>{ + const interactions = new Map(); + for (const { event } of events){ + const p = event.params; + if (event.method === 'serverRequest/resolved') { + interactions.delete(p.requestId); + continue; + } + if (namedTurn(p) !== turnId) continue; + if (event.kind === 'interaction') interactions.set(event.id, event); + if (event.method === 'turn/started' && !terminal(status)) status = p.turn?.status; + if (event.method === 'item/completed' && afterMessageId === undefined) add(p.item); + if (event.method === 'turn/completed') { + status = p.turn?.status; + error = p.turn?.error; + if (afterMessageId === undefined) for (const item of p.turn?.items ?? [])add(item); + } + } + return [ + ...interactions.values() + ]; + }; + const result = (state, detail)=>{ + const interactions = scan(); + const candidates = [ + ...items.values() + ].map((x)=>x.item); + const finals = candidates.filter((i)=>i.phase === 'final_answer'); + // Old app-servers omit phase; use their completed agent items only at terminal status. + const selected = finals.length ? finals : terminal(state) ? candidates : []; + const reply = { + text: '', + items: [], + truncated: truncated || overflow + }; + for (const item of selected){ + const text = reply.text ? `${reply.text}\n${item.text}` : item.text; + if (Buffer.byteLength(JSON.stringify({ + text, + items: [ + ...reply.items, + item + ] + })) > maxOutputBytes) { + reply.truncated = true; + break; + } + reply.text = text; + reply.items.push(item); + } + return { + threadId, + turnId, + ...messageId === undefined ? {} : { + messageId + }, + execution: { + state, + ...detail ? { + error: detail + } : {} + }, + reply, + interactions + }; + }; + let timer, notify; + const abortSignals = [ + signal, + waitSignal + ].filter(Boolean); + const stopped = new Promise((resolve)=>{ + notify = ()=>{ + if (abortSignals.some((s)=>s.aborted) || closed) resolve([ + 'unknown', + 'Observation cancelled' + ]); + else if (disconnected) resolve([ + 'disconnected', + 'Codex connection closed' + ]); + }; + timer = setTimeout(()=>resolve([ + 'timeout', + 'Observation deadline reached' + ]), timeoutMs); + for (const s of abortSignals)s.addEventListener('abort', notify, { + once: true + }); + wake.add(notify); + notify(); + }); + const collect = async ()=>{ + scan(); + try { + let found = false, historyTerminal = false, anchorFound = afterMessageId === undefined; + const missingAnchors = new Set(anchors); + await visitCodexHistory(session, threadId, 'thread/turns/list', {}, (data)=>{ + for (const turn of data)if (!turn || typeof turn.id !== 'string' || typeof turn.status !== 'string') throw new Error('Invalid turn history'); + const turn = data.find((t)=>t.id === turnId); + if (!turn) return false; + found = true; + historyTerminal = terminal(turn.status); + if (!terminal(status)) { + status = turn.status; + error = turn.error; + } + return true; + }, { + stopped: ()=>done + }); + // Notifications can establish completion while the history response is in flight. + scan(); + if (!found && !status) return [ + 'unknown', + 'History coverage incomplete: selected turn not found' + ]; + await visitCodexHistory(session, threadId, 'thread/items/list', { + turnId, + sortDirection: 'asc' + }, (data)=>{ + for (const row of data){ + if (!row || row.turnId !== turnId || !row.item) throw new Error('Invalid thread/items/list wrapper'); + if (row.item.type === 'userMessage' && anchors.includes(row.item.clientId)) { + anchorFound = true; + missingAnchors.delete(row.item.clientId); + } + if (anchorFound) add(row.item); + } + return false; + }, { + stopped: ()=>done + }); + if (!anchorFound || missingAnchors.size) { + items.clear(); + return [ + 'unknown', + 'History coverage incomplete: reply anchor not found' + ]; + } + if (afterMessageId !== undefined && !historyTerminal) return scan().length ? [ + 'waiting-for-input' + ] : [ + 'unknown', + 'Anchored reply awaits terminal history' + ]; + } catch (err) { + historyError = err.message; + truncated = true; + } + if (afterMessageId !== undefined && historyError) { + items.clear(); + return [ + 'unknown', + historyError + ]; + } + while(!done){ + const interactions = scan(); + if (terminal(status)) return [ + status, + error ?? historyError + ]; + if (historyError || overflow) return [ + 'unknown', + historyError ?? 'Notification coverage overflow' + ]; + if (interactions.length) return [ + 'waiting-for-input' + ]; + await new Promise((resolve)=>{ + const listener = ()=>{ + wake.delete(listener); + resolve(); + }; + wake.add(listener); + }); + } + return [ + 'unknown', + 'Observation ended' + ]; + }; + try { + const [state, detail] = await Promise.race([ + stopped, + collect() + ]); + return result(state, detail); + } finally{ + done = true; + clearTimeout(timer); + wake.delete(notify); + for (const s of abortSignals)s.removeEventListener('abort', notify); + for (const listener of [ + ...wake + ])listener(); + } + } + /** @param {{timeoutMs?: number, maxEvents?: number, signal?: AbortSignal}} [options] */ async function watch({ timeoutMs = 30000, maxEvents = 100, signal: watchSignal } = {}) { + boundedInteger(timeoutMs, 600000, 'timeoutMs'); + boundedInteger(maxEvents, 500, 'maxEvents'); + if (watchSignal !== undefined && !(watchSignal instanceof AbortSignal)) throw new TypeError('signal must be an AbortSignal'); + const signals = [ + signal, + watchSignal + ].filter(Boolean); + let timer, listener; + const reason = await new Promise((resolve)=>{ + listener = ()=>{ + if (signals.some((s)=>s.aborted) || closed) resolve('cancelled'); + else if (disconnected) resolve('disconnected'); + else if (events.length >= maxEvents) resolve('event-limit'); + }; + timer = setTimeout(()=>resolve('timeout'), timeoutMs); + wake.add(listener); + for (const s of signals)s.addEventListener('abort', listener, { + once: true + }); + listener(); + }); + clearTimeout(timer); + wake.delete(listener); + for (const s of signals)s.removeEventListener('abort', listener); + return { + threadId, + events: events.slice(0, maxEvents).map((x)=>x.event), + reason, + truncated: overflow || events.length > maxEvents + }; + } + return { + threadId, + cwd: resumed.cwd ?? resumed.thread.cwd, + wait, + watch, + close, + /** @param {string} text + * @param {{envelope?: object, whenBusy?: string, expectedTurnId?: string, signal?: AbortSignal}} [options] */ async send (text, { envelope = (0,_codex_bridge_js__rspack_import_2/* .buildEnvelope */.nq)({ + env + }), whenBusy = 'reject', expectedTurnId, signal: sendSignal } = {}) { + if (closed) return (0,_contract_js__rspack_import_0/* .outcomeFromError */.DG)(Object.assign(new Error('Conversation closed'), { + delivery: 'rejected', + reason: 'closed', + threadId, + envelope + })); + if (sendSignal !== undefined && !(sendSignal instanceof AbortSignal)) throw new TypeError('signal must be an AbortSignal'); + const submissionSignal = signal && sendSignal ? AbortSignal.any([ + signal, + sendSignal + ]) : sendSignal ?? signal; + const receipt = await (0,_codex_bridge_js__rspack_import_2/* .sendToCodexThread */.ZS)(threadId, text, { + env, + envelope, + whenBusy, + expectedTurnId, + session, + expectedCwd, + signal: submissionSignal + }); + if (receipt.delivery === 'accepted' && receipt.turnId) { + acceptedTurns.add(receipt.turnId); + if (acceptedTurns.size > 100) acceptedTurns.delete(acceptedTurns.values().next().value); + } + return receipt; + } + }; +} + +__webpack_require__.d(__webpack_exports__, { + j: () => (openCodexConversation) +}); + + +}, +"./src/core/commands.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _store_js__rspack_import_0 = __webpack_require__("./src/core/store.js"); +/* import */ var _gateway_js__rspack_import_1 = __webpack_require__("./src/core/gateway.js"); + + +function chooseBackend(opts) { + const forceFiles = Boolean(opts.root) || opts.files; + const forceGw = Boolean(opts.gateway); + if (forceGw && forceFiles) { + throw new _store_js__rspack_import_0/* .StoreError */.AD("Use --dir/--files or --gateway, not both."); + } + if (forceGw || !forceFiles && _gateway_js__rspack_import_1/* .hasGatewayAuth */.nF()) return "gateway"; + return "files"; +} +async function openBackend(opts) { + const kind = chooseBackend(opts); + if (kind === "gateway") { + const session = await _gateway_js__rspack_import_1/* .connectGateway */.Vq(); + return { + kind, + session, + list: ()=>_gateway_js__rspack_import_1/* .listAgents */.vc(session), + resolve: (ref)=>_gateway_js__rspack_import_1/* .resolveRef */.qE(session, ref), + createAgent: (input)=>_gateway_js__rspack_import_1/* .createAgent */.Sn(session, input), + updateAgent: (ref, patch)=>_gateway_js__rspack_import_1/* .updateAgent */.x4(session, ref, patch), + deleteAgent: (ref)=>_gateway_js__rspack_import_1/* .deleteAgent */.RB(session, ref), + createGroup: (input)=>_gateway_js__rspack_import_1/* .createGroup */.wj(session, input), + setGroupMembers: (group, members)=>_gateway_js__rspack_import_1/* .setGroupMembers */.Td(session, group, members), + addGroupMember: (group, bot)=>_gateway_js__rspack_import_1/* .addGroupMember */.zr(session, group, bot), + removeGroupMember: (group, bot)=>_gateway_js__rspack_import_1/* .removeGroupMember */.A0(session, group, bot), + send: (ref, prompt, extra)=>_gateway_js__rspack_import_1/* .sendPrompt */.LV(session, ref, prompt, extra), + transcript: (ref, limit)=>_gateway_js__rspack_import_1/* .getTranscriptTail */.bA(session, ref, limit), + thread: (ref, rootId)=>_gateway_js__rspack_import_1/* .getThread */.fG(session, ref, rootId), + skills: ()=>_gateway_js__rspack_import_1/* .listSkills */.bG(session), + addSkill: (markdown)=>_gateway_js__rspack_import_1/* .addSkill */.L5(session, markdown), + removeSkill: (skillRef)=>_gateway_js__rspack_import_1/* .removeSkill */.uX(session, skillRef) + }; + } + const root = _store_js__rspack_import_0/* .resolveAgentsRoot */.v1(opts.root); + return { + kind, + root, + list: async ()=>_store_js__rspack_import_0/* .listRecords */.VI(root), + resolve: async (ref)=>_store_js__rspack_import_0/* .resolveRef */.qE(root, ref), + createAgent: async (input)=>_store_js__rspack_import_0/* .createAgent */.Sn(root, input), + updateAgent: async (ref, patch)=>_store_js__rspack_import_0/* .updateAgent */.x4(root, ref, patch), + deleteAgent: async (ref)=>_store_js__rspack_import_0/* .deleteAgent */.RB(root, ref), + createGroup: async (input)=>_store_js__rspack_import_0/* .createGroup */.wj(root, input), + setGroupMembers: async (group, members)=>_store_js__rspack_import_0/* .setGroupMembers */.Td(root, group, members), + addGroupMember: async (group, bot)=>_store_js__rspack_import_0/* .addGroupMember */.zr(root, group, bot), + removeGroupMember: async (group, bot)=>_store_js__rspack_import_0/* .removeGroupMember */.A0(root, group, bot), + send: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("send requires the live gateway"); + }, + transcript: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("thread requires the live gateway"); + }, + thread: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("thread requires the live gateway"); + }, + skills: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("skills requires the live gateway"); + }, + addSkill: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("skills requires the live gateway"); + }, + removeSkill: async ()=>{ + throw new _store_js__rspack_import_0/* .StoreError */.AD("skills requires the live gateway"); + } + }; +} + +__webpack_require__.d(__webpack_exports__, { + f: () => (openBackend) +}); + + +}, +"./src/core/desktop-shim-bridge.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +// Stdio JSONL (Desktop) <-> WebSocket-over-unix bridge onto the managed +// Codex app-server control socket. Vendored from uploads/codex-stdio-to-daemon-ws.py +// (ChatGPT Desktop -> managed daemon shim) with fail-open deltas, marked below: +// (1) ws_connect enforces one absolute monotonic deadline for connect + HTTP +// upgrade (CODEX_BRIDGE_CONNECT_TIMEOUT, default 10s), requires HTTP/1.1 101 +// plus a matching Sec-WebSocket-Accept (a 200 fails even with a valid hash), +// and retains bytes coalesced after the upgrade headers instead of discarding +// the first data frame. +// (2) read_message assembles continuation frames; control frames answer inline; +// every socket send/lock shares one monotonic budget (remaining first-RPC +// budget, else the mid-session write budget) so a non-reading peer cannot +// wedge pong writes or timeout cleanup; timeouts close and exit. Reads wait +// with no timeout after the handshake so healthy idle sessions survive. +// The wrapper never starts the daemon on the spawn path, so no daemon lock can +// block pre-stdin Desktop. +// (3) A first-response deadline (CODEX_BRIDGE_FIRST_MESSAGE_TIMEOUT, default +// 30s) bounds connect-to-matching-daemon-response covering the first RPC; +// unrelated notifications and foreign responses never satisfy it, only the +// matching response/error (or timeout) clears it. The preflight (3s) + +// upgrade (10s) + first RPC (30s) budget stays far below a daemon-lock hang. +// Exits are 0 served, 1 pre-stdio (wrapper falls back to real Codex on pristine +// stdio+stdout), 2 mid-session (wrapper exits so Desktop reconnects). +// (4) Byte-precise commit on input OR output, committed BEFORE the stdout +// write: os.read into a userspace line buffer counts every stdin byte (even +// an unforwarded blank line), and any daemon payload marks stdout used before +// it is written via a bounded stdout write, so the fallback only ever runs +// on truly pristine stdio+stdout and never spawns a second Codex after used +// stdout. Buffered EOF-tail data flushes before the WS Close, which drains +// via shutdown+close with a bounded join. The reader signals a done event so +// WS close wakes the select loop; no path leaves a thread hung. +// Desktop stdio hangs with stock `codex app-server proxy`, so this custom +// bridge is required. Install writes it to the CODEX_HOME bin dir. Never reads +// Desktop private pipes (CODEX_APP_TOOLS_PIPE_PATH, /tmp/codex-browser-use/). +const BRIDGE_SOURCE = "#!/usr/bin/env python3\n\"\"\"Stdio JSONL (Desktop) <-> WebSocket-over-unix (managed app-server daemon).\nReversible: remove CODEX_CLI_PATH wrapper. Does not read Desktop private pipes.\n\"\"\"\nfrom __future__ import annotations\nimport base64, hashlib, json, os, select, socket, struct, sys, threading, time\n\nSOCK = os.environ.get(\n \"CODEX_APP_SERVER_SOCK\",\n os.path.expanduser(\"~/.codex/app-server-control/app-server-control.sock\"),\n)\nLOG = os.environ.get(\"CODEX_STDIO_BRIDGE_LOG\", os.path.expanduser(\"~/.codex/bin/codex-stdio-to-daemon-ws.log\"))\nWS_GUID = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\n# Wrapper contract: 0 served the session, 1 failed while stdio was still\n# pristine -- no stdin byte consumed and no stdout frame committed (wrapper\n# falls back to real Codex), 2 failed mid-session (wrapper exits promptly so\n# Desktop reconnects; the fallback must never run on half-consumed stdin or\n# dirty stdout).\nEXIT_SERVED = 0\nEXIT_PRE_STDIO = 1\nEXIT_MID_SESSION = 2\n\nCONNECT_TIMEOUT_S = float(os.environ.get(\"CODEX_BRIDGE_CONNECT_TIMEOUT\", \"10\"))\n# Bound from connect to the matching first daemon response: a daemon that\n# completes the upgrade but never answers the first RPC must not hold Desktop\n# past this. Only the matching initialize response/error (or the deadline\n# itself) clears it; notifications never do.\nFIRST_MESSAGE_TIMEOUT_S = float(os.environ.get(\"CODEX_BRIDGE_FIRST_MESSAGE_TIMEOUT\", \"30\"))\n# Bound on every mid-session socket send and stdout write: a wedged or\n# non-reading peer must not hang Desktop past this. Reads after a successful\n# init block with no timeout so healthy idle sessions survive silence.\nIO_TIMEOUT_S = float(os.environ.get(\"CODEX_BRIDGE_IO_TIMEOUT\", \"30\"))\n\ndef log(msg: str) -> None:\n try:\n with open(LOG, \"a\") as f:\n f.write(time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()) + \" \" + msg + \"\\n\")\n except OSError:\n pass\n\ndef ws_connect(path: str, timeout: float = CONNECT_TIMEOUT_S):\n \"\"\"Connect + HTTP upgrade under one absolute monotonic deadline.\n\n Returns (socket, trailing) where trailing holds bytes coalesced after the\n upgrade headers (TCP may deliver the 101 and the first WS frame together;\n discarding them would lose the first message). Requires HTTP/1.1 101 plus\n a matching Sec-WebSocket-Accept so a 200 (or any non-101) fails fast even\n when the accept hash happens to be valid.\n \"\"\"\n deadline = time.monotonic() + timeout\n s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n s.settimeout(timeout)\n try:\n s.connect(path)\n key = base64.b64encode(os.urandom(16)).decode()\n expected = base64.b64encode(hashlib.sha1((key + WS_GUID).encode()).digest()).decode()\n req = (\n f\"GET /rpc HTTP/1.1\\r\\nHost: localhost\\r\\nUpgrade: websocket\\r\\n\"\n f\"Connection: Upgrade\\r\\nSec-WebSocket-Key: {key}\\r\\nSec-WebSocket-Version: 13\\r\\n\\r\\n\"\n ).encode()\n s.settimeout(max(0.0, deadline - time.monotonic()))\n s.sendall(req)\n buf = b\"\"\n while True:\n if b\"\\r\\n\\r\\n\" in buf:\n break\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\"WebSocket upgrade timed out\")\n if len(buf) > 65536:\n raise ConnectionError(\"WS upgrade headers too large\")\n s.settimeout(remaining)\n chunk = s.recv(4096)\n if not chunk:\n raise ConnectionError(\"daemon closed during WS upgrade\")\n buf += chunk\n head, _, trailing = buf.partition(b\"\\r\\n\\r\\n\")\n lines = head.split(b\"\\r\\n\")\n if not lines or lines[0].split(b\" \", 2)[:2] != [b\"HTTP/1.1\", b\"101\"]:\n raise ConnectionError(f\"WS upgrade failed: {head[:200]!r}\")\n accept = None\n for line in lines[1:]:\n name, sep, value = line.partition(b\":\")\n if sep and name.strip().lower() == b\"sec-websocket-accept\":\n accept = value.strip().decode(\"latin-1\")\n if accept != expected:\n raise ConnectionError(\"WS upgrade accept mismatch\")\n except Exception:\n try:\n s.close()\n except OSError:\n pass\n raise\n # Keep one socket mode across reader and writer threads. Reads wait\n # indefinitely in select; sends use their own absolute deadline.\n s.setblocking(False)\n return s, trailing\n\ndef mask_send(sock: socket.socket, payload: bytes, opcode: int = 1, deadline=None) -> None:\n mask = os.urandom(4)\n ln = len(payload)\n if ln < 126:\n hdr = bytes([0x80 | opcode, 0x80 | ln])\n elif ln < 65536:\n hdr = bytes([0x80 | opcode, 0x80 | 126]) + struct.pack(\"!H\", ln)\n else:\n hdr = bytes([0x80 | opcode, 0x80 | 127]) + struct.pack(\"!Q\", ln)\n view = memoryview(hdr + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))\n while view:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\"socket write timed out\")\n _, writable, _ = select.select([], [sock], [], remaining)\n if not writable:\n raise TimeoutError(\"socket write timed out\")\n try:\n n = sock.send(view)\n except BlockingIOError:\n continue\n if not n:\n raise ConnectionError(\"socket closed during write\")\n view = view[n:]\n\ndef locked_send(sock: socket.socket, lock: threading.Lock, payload: bytes, opcode: int = 1, timeout: float = CONNECT_TIMEOUT_S) -> None:\n \"\"\"Serialized send sharing one monotonic budget across lock wait + send.\n\n A non-reading peer must never wedge pong writes or timeout cleanup: on\n expiry raise TimeoutError so the caller closes and exits without hanging.\n \"\"\"\n if timeout is None:\n timeout = CONNECT_TIMEOUT_S\n deadline = time.monotonic() + timeout\n if timeout <= 0:\n raise TimeoutError(\"send budget expired\")\n if not lock.acquire(timeout=timeout):\n raise TimeoutError(\"send lock timed out\")\n try:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\"send budget expired\")\n mask_send(sock, payload, opcode=opcode, deadline=deadline)\n finally:\n lock.release()\n\ndef _buffered_reader(sock: socket.socket, initial: bytes = b\"\"):\n buf = bytearray(initial)\n def recv(n):\n while len(buf) < n:\n select.select([sock], [], [])\n try:\n chunk = sock.recv(n - len(buf))\n except BlockingIOError:\n continue\n if not chunk:\n raise ConnectionError(\"eof\")\n buf.extend(chunk)\n out = bytes(buf[:n])\n del buf[:n]\n return out\n return recv\n\ndef read_frame(recv):\n hdr = recv(2)\n fin = bool(hdr[0] & 0x80)\n opcode = hdr[0] & 0x0F\n masked = bool(hdr[1] & 0x80)\n ln = hdr[1] & 0x7F\n if ln == 126:\n ln = struct.unpack(\"!H\", recv(2))[0]\n elif ln == 127:\n ln = struct.unpack(\"!Q\", recv(8))[0]\n mask = recv(4) if masked else b\"\"\n payload = recv(ln)\n if masked:\n payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))\n return fin, opcode, payload\n\ndef read_message(recv, send_pong):\n \"\"\"Next complete data message, assembling continuation frames.\n\n Control frames are handled inline (pong answered, close reported) so a\n fragmented message split around a ping still reassembles.\n \"\"\"\n opcode = None\n parts = []\n while True:\n fin, op, payload = read_frame(recv)\n if op == 0x8:\n return (\"close\", None, b\"\")\n if op == 0x9:\n send_pong(payload)\n continue\n if op == 0xA:\n continue\n if op in (0x1, 0x2):\n if opcode is not None:\n raise ConnectionError(\"data frame inside fragmented message\")\n if fin:\n return (\"data\", op, payload)\n opcode = op\n parts.append(payload)\n continue\n if op == 0x0:\n if opcode is None:\n raise ConnectionError(\"stray continuation frame\")\n parts.append(payload)\n if fin:\n return (\"data\", opcode, b\"\".join(parts))\n continue\n raise ConnectionError(f\"unsupported opcode {op}\")\n\ndef _is_daemon_response(payload: bytes, expect_id=None, known_ids=None) -> bool:\n \"\"\"True only for the matching JSON-RPC response/error, never a notification.\n\n The first-RPC timer must survive unrelated daemon notifications and foreign\n responses: only the response/error whose id matches the client's initialize\n (or, before it is known, any id the client already sent) proves the first\n RPC got an answer. Timeouts clear it via the deadline, never via data.\n \"\"\"\n try:\n text = payload.decode(\"utf-8\").strip()\n msg = json.loads(text)\n except Exception:\n return False\n if not isinstance(msg, dict):\n return False\n rid = msg.get(\"id\")\n if rid is None or \"method\" in msg or (\"result\" not in msg and \"error\" not in msg):\n return False\n if expect_id is not None:\n return rid == expect_id\n if known_ids:\n return rid in known_ids\n return False\n\ndef _bounded_stdout_write(data: bytes, timeout: float = IO_TIMEOUT_S) -> None:\n \"\"\"Write one daemon frame to stdout without hanging on a non-reading peer.\n\n Waits for writability under the mid-session write budget and writes via\n os.write in a loop, so a Desktop that stopped reading cannot hang the\n bridge and then exit 1 on dirty stdout.\n \"\"\"\n if timeout is None:\n timeout = IO_TIMEOUT_S\n if timeout <= 0:\n raise TimeoutError(\"stdout budget expired\")\n fd = sys.stdout.fileno()\n deadline = time.monotonic() + timeout\n was_blocking = os.get_blocking(fd)\n os.set_blocking(fd, False)\n try:\n view = memoryview(data)\n while view:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\"stdout write timed out\")\n _, writable, _ = select.select([], [fd], [], remaining)\n if not writable:\n raise TimeoutError(\"stdout write timed out\")\n try:\n n = os.write(fd, view)\n except BlockingIOError:\n continue\n view = view[n:]\n finally:\n os.set_blocking(fd, was_blocking)\n\ndef stdout_writer(sock: socket.socket, recv, send_pong, done: threading.Event, first_msg: threading.Event, output_forwarded: threading.Event, client_ids=None, init_state=None) -> None:\n try:\n while True:\n kind, opcode, payload = read_message(recv, send_pong)\n if kind == \"close\":\n log(\"daemon WS close\")\n return\n if opcode == 0x1:\n # Desktop StdioConnection expects newline-delimited JSON text\n if not payload.endswith(b\"\\n\"):\n payload += b\"\\n\"\n # Commit BEFORE writing: once a daemon byte is about to hit\n # stdout, the session is dirty and the fallback must never run,\n # even if the write itself blocks or fails.\n output_forwarded.set()\n _bounded_stdout_write(payload)\n if opcode == 0x1:\n expect = (init_state or {}).get(\"initialize_id\") if isinstance(init_state, dict) else None\n if _is_daemon_response(payload, expect, client_ids or ()):\n first_msg.set()\n except Exception as e:\n log(f\"stdout_writer exit: {e}\")\n finally:\n done.set()\n\ndef main() -> int:\n log(f\"start sock={SOCK}\")\n try:\n sock, pending = ws_connect(SOCK)\n except Exception as e:\n log(f\"connect failed: {e}\")\n sys.stderr.write(f\"codex-stdio-to-daemon-ws: {e}\\n\")\n return EXIT_PRE_STDIO\n log(\"connected\")\n connected_at = time.monotonic()\n first_deadline = connected_at + FIRST_MESSAGE_TIMEOUT_S\n send_lock = threading.Lock()\n done = threading.Event()\n first_msg = threading.Event()\n output_forwarded = threading.Event()\n client_ids = set()\n init_state = {\"initialize_id\": None}\n\n def _send_timeout() -> float:\n # Before the first matching daemon response the remaining first-RPC\n # budget bounds every send; after it each send gets the mid-session\n # write budget. Idle reads are never timed out.\n if not first_msg.is_set():\n return max(0.0, first_deadline - time.monotonic())\n return IO_TIMEOUT_S\n\n def _cleanup_timeout() -> float:\n # Timeout cleanup stays within the expired session budget: once the\n # first-RPC deadline has passed, close directly instead of opening\n # fresh windows that let a short budget take several timeout periods.\n if not first_msg.is_set():\n return max(0.0, first_deadline - time.monotonic())\n return CONNECT_TIMEOUT_S\n\n def send_pong(payload: bytes) -> None:\n locked_send(sock, send_lock, payload, opcode=0xA, timeout=_send_timeout())\n recv = _buffered_reader(sock, pending)\n t = threading.Thread(target=stdout_writer, args=(sock, recv, send_pong, done, first_msg, output_forwarded, client_ids, init_state), daemon=True)\n t.start()\n # Byte-precise commit point: the fallback may run only while zero stdin\n # bytes have left the pipe and no daemon payload was committed to stdout.\n # Reads use os.read into a userspace line buffer (buffered readline could\n # readahead past the commit point), and every byte read counts -- even a\n # blank line. first_msg tracks the matching daemon response/error, never\n # a notification.\n stdin_bytes = 0\n pending_in = b\"\"\n clean_eof = False\n try:\n fd = sys.stdin.fileno()\n while not done.is_set():\n if not first_msg.is_set() and time.monotonic() >= first_deadline:\n log(\"first daemon message timed out\")\n break\n ready, _, _ = select.select([fd], [], [], 0.5)\n if not ready:\n continue\n chunk = os.read(fd, 65536)\n if not chunk:\n clean_eof = True\n break\n stdin_bytes += len(chunk)\n pending_in += chunk\n while b\"\\n\" in pending_in:\n line, _, pending_in = pending_in.partition(b\"\\n\")\n line = line.strip()\n if not line:\n continue\n try:\n try:\n obj = json.loads(line.decode(\"utf-8\"))\n except Exception:\n obj = None\n if isinstance(obj, dict) and obj.get(\"id\") is not None:\n client_ids.add(obj.get(\"id\"))\n if obj.get(\"method\") == \"initialize\" and init_state[\"initialize_id\"] is None:\n init_state[\"initialize_id\"] = obj.get(\"id\")\n except Exception:\n pass\n try:\n locked_send(sock, send_lock, line, timeout=_send_timeout())\n except TimeoutError as e:\n log(f\"stdin forward timed out: {e}\")\n break\n except Exception as e:\n log(f\"stdin forward failed: {e}\")\n break\n else:\n continue\n break\n except Exception as e:\n log(f\"stdin loop exit: {e}\")\n # Flush any buffered EOF-tail data BEFORE the WS Close: sending Close\n # first would let the daemon discard the tail.\n if clean_eof:\n tail = pending_in.strip()\n if tail and not done.is_set():\n try:\n locked_send(sock, send_lock, tail, timeout=_cleanup_timeout())\n except Exception as e:\n log(f\"eof flush failed: {e}\")\n try:\n locked_send(sock, send_lock, b\"\", opcode=0x8, timeout=_cleanup_timeout())\n except Exception as e:\n log(f\"close send failed: {e}\")\n try:\n try:\n sock.shutdown(socket.SHUT_RDWR)\n except OSError:\n pass\n sock.close()\n except OSError:\n pass\n # Bound termination: wake the reader so no thread is left hung on recv.\n t.join(timeout=0.5)\n # A reader still exiting could commit output after this check. In that\n # case pristine stdio cannot be proven, so never permit fallback.\n if t.is_alive():\n output_forwarded.set()\n if clean_eof:\n log(\"exit\")\n return EXIT_SERVED\n # Reader died, first RPC timed out, post-upgrade I/O timed out, or stdin\n # broke: fail open only while stdio is still pristine -- no stdin byte\n # ever consumed AND no daemon payload ever committed to stdout. Committed\n # output forces a mid-session exit so Desktop reconnects instead of\n # falling back to stock Codex on a corrupted stream.\n rc = EXIT_MID_SESSION if (stdin_bytes or output_forwarded.is_set()) else EXIT_PRE_STDIO\n log(f\"exit rc={rc}\")\n return rc\n\nif __name__ == \"__main__\":\n raise SystemExit(main())\n"; + +__webpack_require__.d(__webpack_exports__, { +}, { + w: BRIDGE_SOURCE +}); + + +}, +"./src/core/desktop-shim.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_child_process__rspack_import_0 = __webpack_require__("node:child_process"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_2 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_3 = __webpack_require__("node:path"); +/* import */ var _desktop_shim_bridge_js__rspack_import_4 = __webpack_require__("./src/core/desktop-shim-bridge.js"); + + + + + +/** + * ChatGPT Desktop -> managed Codex daemon shim (CODEX_CLI_PATH bridge). + * + * Desktop injects `codex_app` overrides so CODEX_APP_SERVER_USE_LOCAL_DAEMON=1 + * alone cannot select the managed daemon, and stock `codex app-server proxy` + * hangs for Desktop stdio. The winning path is a wrapper on CODEX_CLI_PATH + * that rewrites Desktop's `codex ... app-server` spawn into the stdio<->WS + * bridge (desktop-shim-bridge.js) onto the managed control socket. + * Provenance: uploads/codex-desktop-to-daemon + codex-desktop-shared-daemon-env.sh. + * + * Fail-open is the hard rule: the wrapper execs the real standalone `codex` + * for non-app-server spawns and whenever the bridge/python/socket side is + * missing or broken. Never touches Desktop binaries, /tmp/codex-browser-use/, + * or CODEX_APP_TOOLS_PIPE_PATH. No protocol change: gbot already speaks the + * managed control socket. + */ const SHIM_LABEL = "com.zackjackson.codex-desktop-shared-daemon"; +const WRAPPER_FILENAME = "codex-desktop-to-daemon"; +const BRIDGE_FILENAME = "codex-stdio-to-daemon-ws.py"; +const ENV_SCRIPT_FILENAME = "codex-desktop-shared-daemon-env.sh"; +const BRIDGE_LOG_FILENAME = "codex-stdio-to-daemon-ws.log"; +const WRAPPER_LOG_FILENAME = "codex-desktop-to-daemon.log"; +const ENV_LOG_FILENAME = "codex-desktop-shared-daemon-env.log"; +const STANDALONE_REAL_SUFFIX = (0,node_path__rspack_import_3.join)("packages", "standalone", "current", "bin", "codex"); +function codexHomeDir(env = process.env) { + return env.CODEX_HOME || join(env.HOME || homedir(), ".codex"); +} +function userHomeDir(env = process.env) { + return env.HOME || (0,node_os__rspack_import_2.homedir)(); +} +function defaultPaths({ env = process.env, home = userHomeDir(env) } = {}) { + const codexHome = env.CODEX_HOME || (0,node_path__rspack_import_3.join)(home, ".codex"); + const binDir = (0,node_path__rspack_import_3.join)(codexHome, "bin"); + return { + binDir, + bridgeLogPath: (0,node_path__rspack_import_3.join)(binDir, BRIDGE_LOG_FILENAME), + bridgePath: (0,node_path__rspack_import_3.join)(binDir, BRIDGE_FILENAME), + codexHome, + envLogPath: (0,node_path__rspack_import_3.join)(binDir, ENV_LOG_FILENAME), + envScriptPath: (0,node_path__rspack_import_3.join)(binDir, ENV_SCRIPT_FILENAME), + label: SHIM_LABEL, + launchAgentsDir: (0,node_path__rspack_import_3.join)(home, "Library", "LaunchAgents"), + plistPath: (0,node_path__rspack_import_3.join)(home, "Library", "LaunchAgents", `${SHIM_LABEL}.plist`), + realPath: (0,node_path__rspack_import_3.join)(codexHome, STANDALONE_REAL_SUFFIX), + socketPath: (0,node_path__rspack_import_3.join)(codexHome, "app-server-control", "app-server-control.sock"), + wrapperLogPath: (0,node_path__rspack_import_3.join)(binDir, WRAPPER_LOG_FILENAME), + wrapperPath: (0,node_path__rspack_import_3.join)(binDir, WRAPPER_FILENAME) + }; +} +/** + * Pure passthrough decision, mirroring the wrapper's argv scan. True only for + * a bare `app-server` spawn: Desktop's private-stdio case. `daemon`, `proxy`, + * and schema generations always exec the real Codex. + */ function shouldBridge(argv) { + let appServer = false; + let daemon = false; + let proxy = false; + let generate = false; + for (const arg of argv ?? []){ + if (arg === "app-server") appServer = true; + else if (arg === "daemon") daemon = true; + else if (arg === "proxy") proxy = true; + else if (arg === "generate-ts" || arg === "generate-json-schema") generate = true; + } + return appServer && !daemon && !proxy && !generate; +} +function renderWrapperScript({ realPath, bridgePath, wrapperLogPath, codexHome, bridgeLogPath }) { + return `#!/bin/bash +# Installed by \`gbot codex desktop-shim install\`. Rewrites ChatGPT Desktop's +# \`codex ... app-server\` spawn into a stdio<->WebSocket bridge onto the managed +# daemon's control socket. Reversible: \`gbot codex desktop-shim uninstall\`. +# The daemon is kept up by the LaunchAgent login script, not here: this hot path +# never starts the daemon itself, so a wedged daemon lock cannot hang +# Desktop. Fail-open runs ONLY while stdio is still pristine (no stdin +# consumed, no stdout written): an absent socket fails the preflight and a +# pre-session bridge failure (exit 1) falls through +# to the real standalone codex on pristine stdio. A mid-session bridge failure +# (exit 2+) exits promptly so Desktop reconnects; the fallback never runs on +# half-consumed stdin or dirty stdout. Bridge exit 0 means it served the session. Never touches +# Desktop binaries or its private tool pipe. +set -u +REAL="\${CODEX_DESKTOP_WRAPPER_REAL:-${realPath}}" +BRIDGE="\${CODEX_DESKTOP_BRIDGE:-${bridgePath}}" +export CODEX_HOME="\${CODEX_HOME:-${codexHome}}" +SOCK="\${CODEX_APP_SERVER_SOCK:-$CODEX_HOME/app-server-control/app-server-control.sock}" +BRIDGE_LOG="\${CODEX_STDIO_BRIDGE_LOG:-${bridgeLogPath}}" +LOG="\${CODEX_DESKTOP_WRAPPER_LOG:-${wrapperLogPath}}" +export CODEX_APP_SERVER_SOCK="$SOCK" +export CODEX_STDIO_BRIDGE_LOG="$BRIDGE_LOG" +ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } +echo "$(ts) argv: $*" >>"$LOG" 2>/dev/null || true + +if [[ ! -x "$REAL" ]]; then + FALLBACK="$(command -v codex 2>/dev/null || true)" + if [[ -n "$FALLBACK" && -x "$FALLBACK" ]]; then + if [[ "$FALLBACK" -ef "$0" ]] 2>/dev/null || { [[ -n "\${CODEX_CLI_PATH:-}" ]] && [[ "$FALLBACK" -ef "\${CODEX_CLI_PATH}" ]] 2>/dev/null; }; then + echo "$(ts) refusing self fallback $FALLBACK" >>"$LOG" 2>/dev/null || true + else + REAL="$FALLBACK" + fi + fi +fi + +has_app_server=0; has_daemon=0; has_proxy=0; has_generate=0 +for a in "$@"; do + case "$a" in + app-server) has_app_server=1 ;; + daemon) has_daemon=1 ;; + proxy) has_proxy=1 ;; + generate-ts|generate-json-schema) has_generate=1 ;; + esac +done + +# Preflight the daemon socket with a short deadline: a refused/absent socket +# means starting the bridge could never succeed, so skip straight to real codex. +preflight() { + python3 -c 'import os,socket,sys; s=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM); s.settimeout(float(os.environ.get("CODEX_DESKTOP_PREFLIGHT_TIMEOUT","3"))); s.connect(sys.argv[1]); s.close()' "$SOCK" 2>/dev/null +} + +if [[ "$has_app_server" -eq 1 && "$has_daemon" -eq 0 && "$has_proxy" -eq 0 && "$has_generate" -eq 0 ]]; then + if [[ -f "$BRIDGE" ]] && command -v python3 >/dev/null 2>&1; then + if preflight; then + echo "$(ts) rewrite -> stdio-ws bridge" >>"$LOG" 2>/dev/null || true + python3 "$BRIDGE" + rc=$? + case "$rc" in + 0) + echo "$(ts) bridge served session" >>"$LOG" 2>/dev/null || true + exit 0 + ;; + 1) + echo "$(ts) bridge failed before session start, falling through to real codex" >>"$LOG" 2>/dev/null || true + ;; + *) + echo "$(ts) bridge failed mid-session (rc=$rc); exiting so Desktop reconnects" >>"$LOG" 2>/dev/null || true + exit "$rc" + ;; + esac + else + echo "$(ts) daemon socket unreachable, passthrough to real codex" >>"$LOG" 2>/dev/null || true + fi + else + echo "$(ts) bridge unavailable, passthrough to real codex" >>"$LOG" 2>/dev/null || true + fi +fi +if [[ -x "$REAL" ]]; then + exec "$REAL" "$@" +fi +echo "codex-desktop-to-daemon: no runnable codex found" >&2 +exit 1 +`; +} +function renderEnvScript({ wrapperPath, realPath, envLogPath, codexHome }) { + return `#!/bin/bash +# Installed by \`gbot codex desktop-shim install\`. Re-applies the GUI-domain env +# so ChatGPT.app inherits CODEX_CLI_PATH after login, then best-effort starts the +# managed daemon (this login script — never Desktop's spawn hot path — owns +# daemon upkeep). No -e: every step is best-effort so login never breaks. +# Revert: \`gbot codex desktop-shim uninstall\`. +set -u +WRAPPER="${wrapperPath}" +REAL="${realPath}" +LOG="${envLogPath}" +CODEX_HOME_DIR="${codexHome}" +# One CODEX_HOME for the GUI domain and this script's own daemon start, so the +# daemon that is kept up is the one the wrapper bridges to. +export CODEX_HOME="$CODEX_HOME_DIR" +ts() { date -u +%Y-%m-%dT%H:%M:%SZ; } +{ + echo "$(ts) start" + if [[ ! -x "$WRAPPER" ]]; then + echo "$(ts) missing wrapper: $WRAPPER" + exit 0 + fi + # GUI domain setenv so ChatGPT.app inherits CODEX_CLI_PATH after login + launchctl setenv CODEX_CLI_PATH "$WRAPPER" + launchctl setenv CODEX_HOME "$CODEX_HOME_DIR" + launchctl setenv CODEX_APP_SERVER_USE_LOCAL_DAEMON 1 + launchctl unsetenv CODEX_APP_SERVER_WS_URL 2>/dev/null || true + echo "$(ts) CODEX_CLI_PATH=$(launchctl getenv CODEX_CLI_PATH)" + if [[ -x "$REAL" ]]; then + "$REAL" app-server daemon start >/dev/null 2>&1 || true + echo "$(ts) daemon start attempted" + fi + echo "$(ts) done" +} >>"$LOG" 2>&1 +`; +} +function renderPlist({ envScriptPath, label = SHIM_LABEL }) { + return ` + + + +\tLabel +\t${label} +\tProgramArguments +\t +\t\t/bin/bash +\t\t${envScriptPath} +\t +\tRunAtLoad +\t +\tLimitLoadToSessionType +\tAqua + + +`; +} +const defaultRunner = (file, args)=>{ + try { + return (0,node_child_process__rspack_import_0.spawnSync)(file, args, { + encoding: "utf8", + timeout: 15000 + }); + } catch (error) { + return { + error, + status: null + }; + } +}; +function runBestEffort(runner, warnings, what, file, args) { + const out = runner(file, args); + if (out && (out.error || typeof out.status === "number" && out.status !== 0)) { + const detail = out.error && out.error.message || out.stderr && String(out.stderr).trim() || `exit ${out.status}`; + warnings.push(`${what} failed (${detail}); continuing`); + } + return out; +} +function writeExecutable(path, content) { + (0,node_fs__rspack_import_1.writeFileSync)(path, content, { + mode: 493 + }); + (0,node_fs__rspack_import_1.chmodSync)(path, 493); +} +function isExecutable(path) { + try { + (0,node_fs__rspack_import_1.statSync)(path); + } catch { + return false; + } + try { + // X_OK without throwing: accessSync is clearer; stat mode bit check is sync-safe. + return ((0,node_fs__rspack_import_1.statSync)(path).mode & 73) !== 0; + } catch { + return false; + } +} +function fileExists(path) { + try { + (0,node_fs__rspack_import_1.statSync)(path); + return true; + } catch { + return false; + } +} +/** + * Copy the wrapper + bridge + login env script out of the package into durable + * ~/.codex paths (never a git checkout), then persist CODEX_CLI_PATH for the + * macOS Aqua session via LaunchAgent. Idempotent. + */ function installDesktopShim({ env = process.env, home = userHomeDir(env), platform = process.platform, runner = defaultRunner } = {}) { + const paths = defaultPaths({ + env, + home + }); + const warnings = []; + (0,node_fs__rspack_import_1.mkdirSync)(paths.binDir, { + recursive: true + }); + writeExecutable(paths.wrapperPath, renderWrapperScript(paths)); + (0,node_fs__rspack_import_1.writeFileSync)(paths.bridgePath, _desktop_shim_bridge_js__rspack_import_4/* .BRIDGE_SOURCE.endsWith */.w.endsWith("\n") ? _desktop_shim_bridge_js__rspack_import_4/* .BRIDGE_SOURCE */.w : `${_desktop_shim_bridge_js__rspack_import_4/* .BRIDGE_SOURCE */.w}\n`, { + mode: 420 + }); + writeExecutable(paths.envScriptPath, renderEnvScript(paths)); + let persisted = false; + if (platform === "darwin") { + (0,node_fs__rspack_import_1.mkdirSync)(paths.launchAgentsDir, { + recursive: true + }); + (0,node_fs__rspack_import_1.writeFileSync)(paths.plistPath, renderPlist({ + envScriptPath: paths.envScriptPath + }), { + mode: 420 + }); + const uid = typeof process.getuid === "function" ? process.getuid() : null; + if (uid === null || uid === undefined) { + warnings.push("could not determine uid; LaunchAgent file written but not bootstrapped — log out/in or bootstrap it manually"); + } else { + const target = `gui/${uid}/${paths.label}`; + runBestEffort(runner, warnings, "launchctl bootout (previous agent)", "launchctl", [ + "bootout", + target + ]); + runBestEffort(runner, warnings, "launchctl bootstrap", "launchctl", [ + "bootstrap", + `gui/${uid}`, + paths.plistPath + ]); + } + runBestEffort(runner, warnings, "launchctl setenv CODEX_CLI_PATH", "launchctl", [ + "setenv", + "CODEX_CLI_PATH", + paths.wrapperPath + ]); + runBestEffort(runner, warnings, "launchctl setenv CODEX_APP_SERVER_USE_LOCAL_DAEMON", "launchctl", [ + "setenv", + "CODEX_APP_SERVER_USE_LOCAL_DAEMON", + "1" + ]); + runBestEffort(runner, warnings, "launchctl unsetenv CODEX_APP_SERVER_WS_URL", "launchctl", [ + "unsetenv", + "CODEX_APP_SERVER_WS_URL" + ]); + persisted = true; + } else { + warnings.push("LaunchAgent persistence is macOS-only; wrapper and bridge installed — export CODEX_CLI_PATH manually"); + } + if (isExecutable(paths.realPath)) { + runBestEffort(runner, warnings, "codex app-server daemon start", paths.realPath, [ + "app-server", + "daemon", + "start" + ]); + } else { + warnings.push(`managed daemon not started: no executable at ${paths.realPath}`); + } + return { + action: "install", + bridgePath: paths.bridgePath, + envScriptPath: paths.envScriptPath, + exitCode: 0, + persisted, + plistPath: platform === "darwin" ? paths.plistPath : null, + realPath: paths.realPath, + warnings, + wrapperPath: paths.wrapperPath + }; +} +/** Remove what install wrote and unset the GUI env; Desktop/Codex fall back to stock. */ function uninstallDesktopShim({ env = process.env, home = userHomeDir(env), platform = process.platform, runner = defaultRunner } = {}) { + const paths = defaultPaths({ + env, + home + }); + const warnings = []; + const removed = []; + for (const path of [ + paths.wrapperPath, + paths.bridgePath, + paths.envScriptPath + ]){ + const existed = fileExists(path); + try { + if ((0,node_fs__rspack_import_1.rmSync)(path, { + force: true + }) === undefined && fileExists(path)) warnings.push(`could not remove ${path}`); + else if (existed && !fileExists(path)) removed.push(path); + } catch (error) { + warnings.push(`could not remove ${path} (${error instanceof Error ? error.message : String(error)})`); + } + } + let plistRemoved = false; + if (platform === "darwin") { + const uid = typeof process.getuid === "function" ? process.getuid() : null; + if (uid !== null && uid !== undefined) { + runBestEffort(runner, warnings, "launchctl bootout", "launchctl", [ + "bootout", + `gui/${uid}/${paths.label}` + ]); + } + try { + (0,node_fs__rspack_import_1.rmSync)(paths.plistPath, { + force: true + }); + plistRemoved = !fileExists(paths.plistPath); + } catch (error) { + warnings.push(`could not remove ${paths.plistPath} (${error instanceof Error ? error.message : String(error)})`); + } + runBestEffort(runner, warnings, "launchctl unsetenv CODEX_CLI_PATH", "launchctl", [ + "unsetenv", + "CODEX_CLI_PATH" + ]); + runBestEffort(runner, warnings, "launchctl unsetenv CODEX_HOME", "launchctl", [ + "unsetenv", + "CODEX_HOME" + ]); + runBestEffort(runner, warnings, "launchctl unsetenv CODEX_APP_SERVER_USE_LOCAL_DAEMON", "launchctl", [ + "unsetenv", + "CODEX_APP_SERVER_USE_LOCAL_DAEMON" + ]); + runBestEffort(runner, warnings, "launchctl unsetenv CODEX_APP_SERVER_WS_URL", "launchctl", [ + "unsetenv", + "CODEX_APP_SERVER_WS_URL" + ]); + } + return { + action: "uninstall", + exitCode: 0, + plistPath: platform === "darwin" ? paths.plistPath : null, + plistRemoved, + removed, + warnings, + wrapperPath: paths.wrapperPath + }; +} +function socketStateOf(path) { + try { + return (0,node_fs__rspack_import_1.statSync)(path).isSocket() ? "socket" : "not-a-socket"; + } catch (error) { + return error && (error.code === "EACCES" || error.code === "EPERM") ? "permission-denied" : "absent"; + } +} +/** + * Inspect the shim without touching Desktop, pipes, or sockets beyond a stat. + * On macOS the Desktop-facing CODEX_CLI_PATH lives in launchd's GUI domain, + * which a shell-spawned `gbot` does not inherit — so status queries + * `launchctl getenv` there (via the injectable runner) and reports the caller + * environment separately. Elsewhere the process env is the whole story. + */ function desktopShimStatus({ env = process.env, home = userHomeDir(env), platform = process.platform, runner = defaultRunner } = {}) { + const paths = defaultPaths({ + env, + home + }); + const warnings = []; + const wrapperPresent = fileExists(paths.wrapperPath); + const bridgePresent = fileExists(paths.bridgePath); + const envScriptPresent = fileExists(paths.envScriptPath); + const plistPresent = platform === "darwin" ? fileExists(paths.plistPath) : false; + const cliPath = env.CODEX_CLI_PATH || null; + let guiCliPath = null; + if (platform === "darwin") { + try { + const out = runner("launchctl", [ + "getenv", + "CODEX_CLI_PATH" + ]); + const value = out && typeof out.stdout === "string" ? out.stdout.trim() : ""; + guiCliPath = value || null; + if (out && (out.error || typeof out.status === "number" && out.status !== 0)) { + warnings.push("launchctl getenv CODEX_CLI_PATH failed; GUI-domain state unknown"); + guiCliPath = null; + } + } catch (error) { + warnings.push(`launchctl getenv CODEX_CLI_PATH failed (${error instanceof Error ? error.message : String(error)})`); + guiCliPath = null; + } + } + // Desktop-facing value: the GUI domain on macOS, the caller env elsewhere. + const desktopCliPath = platform === "darwin" ? guiCliPath : cliPath; + const installed = wrapperPresent && isExecutable(paths.wrapperPath) && bridgePresent; + // Effective socket, resolved exactly like gbot's own client (CODEX_APP_SERVER_SOCK + // wins, else the install-time CODEX_HOME) so status and send/queue/status never + // disagree. Inlined here so codex-bridge can reuse desktopShimStatus without a cycle. + const socketPath = env.CODEX_APP_SERVER_SOCK || (0,node_path__rspack_import_3.join)(paths.codexHome, "app-server-control", "app-server-control.sock"); + return { + action: "status", + bridgePath: paths.bridgePath, + bridgePresent, + cliPath, + codexHome: paths.codexHome, + desktopCliPath, + envScriptPath: paths.envScriptPath, + envScriptPresent, + exitCode: installed ? 0 : 1, + guiCliPath, + installed, + persisted: platform === "darwin" ? plistPresent : null, + platform, + plistPath: platform === "darwin" ? paths.plistPath : null, + plistPresent, + realPath: paths.realPath, + socketPath, + socketSource: env.CODEX_APP_SERVER_SOCK ? "CODEX_APP_SERVER_SOCK" : "CODEX_HOME", + socketState: socketStateOf(socketPath), + warnings, + wrapperExecutable: wrapperPresent && isExecutable(paths.wrapperPath), + wrapperPath: paths.wrapperPath, + wrapperPointsAtShim: desktopCliPath === paths.wrapperPath, + wrapperPresent + }; +} + +__webpack_require__.d(__webpack_exports__, { + B0: () => (installDesktopShim), + em: () => (desktopShimStatus), + gM: () => (uninstallDesktopShim) +}); + + +}, +"./src/core/format.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _transcript_js__rspack_import_0 = __webpack_require__("./src/core/transcript.js"); + +/** Strip CSI/OSC and other C0/C1 controls so thread fields cannot drive the terminal. */ function stripTerminalControls(text) { + return String(text).replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, "").replace(/\u001b./g, "").replace(/[\u0000-\u001F\u007F-\u009F]/g, ""); +} +function summarize(rec) { + return { + id: rec.id, + name: rec.name, + title: rec.title || undefined, + description: rec.description || undefined, + avatarShape: rec.avatarShape || undefined, + avatarColor: rec.avatarColor || undefined, + ...rec.notifyOnAgentUpdates !== undefined ? { + notifyOnAgentUpdates: rec.notifyOnAgentUpdates + } : {}, + ...rec.hiddenFromSidebar !== undefined ? { + hiddenFromSidebar: rec.hiddenFromSidebar + } : {}, + kind: rec.isGroup ? "group" : "bot", + members: rec.isGroup ? rec.memberIds : undefined + }; +} +function formatRecord(rec, all) { + const kind = rec.isGroup ? "group" : "bot"; + const members = rec.isGroup ? rec.memberIds.map((id)=>{ + const m = all.find((r)=>r.id === id); + return m ? m.name + " (" + id + ")" : id; + }).join(", ") : ""; + const title = rec.title ? " - " + rec.title : ""; + const desc = rec.description ? "\n " + rec.description : ""; + const avatar = rec.avatarShape || rec.avatarColor ? "\n avatar: " + [ + rec.avatarShape, + rec.avatarColor + ].filter(Boolean).join(" ") : ""; + const settings = []; + if (rec.notifyOnAgentUpdates !== undefined) settings.push("notify " + (rec.notifyOnAgentUpdates ? "on" : "off")); + if (rec.hiddenFromSidebar !== undefined) settings.push("hidden " + (rec.hiddenFromSidebar ? "on" : "off")); + const settingsLine = settings.length ? "\n " + settings.join(", ") : ""; + const extra = rec.isGroup ? "\n members (" + rec.memberIds.length + "): " + (members || "(none)") : ""; + return kind + " " + rec.name + title + "\n " + rec.id + desc + avatar + settingsLine + extra; +} +function formatTranscript(out, { full = false } = {}) { + const rec = out.target; + const payload = out.transcript || out.thread || {}; + const entries = (0,_transcript_js__rspack_import_0/* .transcriptEntries */.xw)(payload); + const header = (rec.isGroup ? "group" : "bot") + " " + rec.name + "\n " + rec.id; + if (!Array.isArray(entries) || entries.length === 0) { + return header + "\n (no messages)"; + } + const lines = [ + header, + "" + ]; + for (const e of entries){ + const role = e.role || e.kind || e.sender || e.type || "msg"; + const text = (0,_transcript_js__rspack_import_0/* .entryText */.u0)(e); + const id = e.id || ""; + lines.push("[" + role + (id ? " " + id : "") + "] " + (full ? text : truncateCliText(text))); + } + return lines.join("\n"); +} +function truncateCliText(text, max = 400) { + if (text.length <= max) return text; + return text.slice(0, max) + "… [+" + (text.length - max) + " chars; --full or --json for complete text]"; +} +function formatCodexStatus(s) { + const lines = [ + "socket: " + s.socketPath + " (" + s.socketState + ")" + ]; + if (s.desktopShimConfigured) lines.push("desktop shim: configured (managed attachment unverified)"); + if (!s.reachable) return lines.concat("reachable: no (" + s.mode + ")", s.message).join("\n"); + if (s.mode !== "daemon") { + return lines.concat("reachable: yes, but unusable (" + s.mode + ")", s.message).join("\n"); + } + lines.push("reachable: yes (daemon)"); + const cli = s.cliVersion ?? (s.cliVersionProbe === "ok" ? "unknown" : "unknown, probe " + s.cliVersionProbe); + lines.push("daemon version: " + (s.daemonVersion ?? "unknown") + " cli version: " + cli + " pinned schema: " + s.pinnedVersion + " (" + s.schema.compatibility + ")"); + lines.push(s.desktopAttached === "private-stdio" ? "desktop attached: private-stdio (Desktop-bundled app-server process observed; managed attachment unverified)" : "desktop attached: unknown (not observable from the socket)"); + if (s.versionMismatch) { + lines.push("warning: daemon and CLI versions differ; `codex app-server daemon restart` picks up the installed CLI"); + } + return lines.join("\n"); +} +function formatCodexQueue({ threadId, queued }) { + if (queued.length === 0) return "No queued submissions on Codex thread " + threadId + "."; + return queued.map((q)=>q.id + " " + (q.clientUserMessageId ?? "") + "\n " + stripTerminalControls(q.text).replace(/\s+/g, " ").slice(0, 200)).join("\n\n"); +} +function formatCodexThread(t) { + const title = t.name ? " - " + stripTerminalControls(t.name) : ""; + const preview = t.preview ? "\n " + stripTerminalControls(String(t.preview).replace(/\s+/g, " ")).slice(0, 200) : ""; + return stripTerminalControls(t.id) + " " + stripTerminalControls(t.status) + title + "\n " + stripTerminalControls(t.cwd ?? "") + preview; +} +/** Shell-safe single-quoting for copy-pasteable export lines (spaces, quotes, $). */ function shellQuote(value) { + return "'" + String(value).replace(/'/g, "'\\''") + "'"; +} +function formatDesktopShimStatus(s) { + const mark = (ok)=>ok ? "yes" : "no"; + const cliLine = s.platform === "darwin" ? "CODEX_CLI_PATH: GUI domain " + (s.guiCliPath ?? "(unset)") + " / this shell " + (s.cliPath ?? "(unset)") + (s.wrapperPointsAtShim ? " (Desktop-facing value points at shim)" : "") : "CODEX_CLI_PATH: " + (s.cliPath ?? "(unset)") + (s.wrapperPointsAtShim ? " (points at shim)" : ""); + const lines = [ + "wrapper: " + s.wrapperPath + " (" + (s.wrapperExecutable ? "executable" : s.wrapperPresent ? "present, not executable" : "absent") + ")", + "bridge: " + s.bridgePath + " (" + mark(s.bridgePresent) + ")", + "login env: " + s.envScriptPath + " (" + mark(s.envScriptPresent) + ")", + s.platform === "darwin" ? "LaunchAgent: " + s.plistPath + " (" + mark(s.plistPresent) + ")" : "LaunchAgent: n/a (macOS-only)", + cliLine, + "daemon socket: " + s.socketPath + " (" + s.socketState + ", from " + (s.socketSource ?? "CODEX_HOME") + ")" + ]; + if (!s.installed) { + lines.push("shim: not installed — run `gbot codex desktop-shim install` (Desktop keeps stock behavior until then)"); + } else if (!s.wrapperPointsAtShim) { + lines.push(s.platform === "darwin" ? "shim: installed but CODEX_CLI_PATH does not point at it — reinstall or relaunch ChatGPT.app after login" : "shim: installed but CODEX_CLI_PATH does not point at it — export CODEX_CLI_PATH=" + shellQuote(s.wrapperPath)); + } else { + lines.push("shim: active — Desktop app-server spawns bridge onto the managed daemon"); + } + for (const warning of s.warnings ?? [])lines.push("warning: " + String(warning)); + return lines.join("\n"); +} + +__webpack_require__.d(__webpack_exports__, { + P2: () => (formatCodexStatus), + bM: () => (formatRecord), + e_: () => (formatCodexQueue), + eh: () => (summarize), + fX: () => (formatDesktopShimStatus), + nz: () => (formatCodexThread), + oZ: () => (formatTranscript) +}); + + +}, +"./src/core/gateway.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var _headers_js__rspack_import_5 = __webpack_require__("./src/core/headers.js"); +/* import */ var _app_session_js__rspack_import_1 = __webpack_require__("./src/core/app-session.js"); +/* import */ var _store_js__rspack_import_2 = __webpack_require__("./src/core/store.js"); +/* import */ var _url_policy_js__rspack_import_3 = __webpack_require__("./src/core/url-policy.js"); +/* import */ var _grok_approvals_js__rspack_import_4 = __webpack_require__("./src/core/grok-approvals.js"); + + + + + + +class GatewayError extends Error { + constructor(message, { status, method } = {}){ + super(message); + this.name = "GatewayError"; + this.status = status; + this.method = method; + } +} +// ponytail: fixed 30 s deadline and buffered byte cap; upgrade path is per-method budgets plus streaming reads. +const GATEWAY_TIMEOUT_MS = 30000; +const GATEWAY_MAX_RESPONSE_BYTES = 2 * 1024 * 1024; +function assertGatewayActive(signal) { + if (signal?.aborted) { + const error = new GatewayError("Gateway submission cancelled before transmission"); + error.delivery = "rejected"; + error.reason = "cancelled"; + throw error; + } +} +function gatewayDeadline(signal) { + const timeout = AbortSignal.timeout(GATEWAY_TIMEOUT_MS); + return signal ? AbortSignal.any([ + signal, + timeout + ]) : timeout; +} +function backendBase() { + return (process.env.CURSOR_API_BASE_URL || "https://api2.cursor.sh").replace(/\/$/, ""); +} +function accessTokenFromEnv() { + return (process.env.CURSOR_ACCESS_TOKEN || "").trim(); +} +function gatewayTokenFromEnv() { + return (process.env.GROK_BOT_GATEWAY_TOKEN || "").trim(); +} +function gatewayOverride() { + const token = gatewayTokenFromEnv(); + const url = (process.env.GROK_BOT_GATEWAY_URL || "").trim(); + if (url && token) { + return { + gatewayUrl: (0,_url_policy_js__rspack_import_3/* .assertAllowedCredentialUrl */.Re)(url.replace(/\/$/, ""), { + kind: "gateway" + }), + gatewayToken: token, + gatewayHeaders: (0,_headers_js__rspack_import_5/* .headersFromEnv */.gx)() + }; + } + return null; +} +function sessionFromApp() { + let loaded; + try { + loaded = (0,_app_session_js__rspack_import_1/* .loadGrokBotGatewaySession */.Z2)(); + } catch (error) { + // Descriptor present but unusable (e.g. Windows Local State missing). Fall + // through to CURSOR_ACCESS_TOKEN → EnsureSandBox when that token is set. + if (accessTokenFromEnv()) return null; + throw error instanceof Error ? new GatewayError(error.message) : error; + } + if (!loaded) return null; + return { + gatewayUrl: (0,_url_policy_js__rspack_import_3/* .assertAllowedCredentialUrl */.Re)(loaded.gatewayUrl, { + kind: "gateway" + }), + gatewayToken: loaded.gatewayToken, + gatewayHeaders: (0,_headers_js__rspack_import_5/* .mergeGatewayHeaders */.bQ)((0,_headers_js__rspack_import_5/* .normalizeHeaderMap */.dk)(loaded.headers), (0,_headers_js__rspack_import_5/* .headersFromEnv */.gx)()) + }; +} +function hasGatewayAuth() { + return Boolean(gatewayOverride() || accessTokenFromEnv() || (0,_app_session_js__rspack_import_1/* .hasGrokBotGatewaySession */.ZN)()); +} +async function readTextCapped(res, maxBytes) { + if (!res.body || typeof res.body.getReader !== "function") { + const text = await res.text(); + if (Buffer.byteLength(text, "utf8") > maxBytes) { + throw new GatewayError("Gateway response too large (over " + maxBytes + " bytes)"); + } + return text; + } + const reader = res.body.getReader(); + const chunks = []; + let bytes = 0; + for(;;){ + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength ?? value.length; + if (bytes > maxBytes) { + try { + await reader.cancel(); + } catch {} + throw new GatewayError("Gateway response too large (over " + maxBytes + " bytes)"); + } + chunks.push(value); + } + return Buffer.concat(chunks.map((c)=>Buffer.from(c.buffer ?? c, c.byteOffset ?? 0, c.byteLength ?? c.length))).toString("utf8"); +} +async function readJson(res) { + const text = await readTextCapped(res, GATEWAY_MAX_RESPONSE_BYTES); + if (!text) return {}; + try { + return JSON.parse(text); + } catch { + return { + raw: text + }; + } +} +function pick(obj, ...keys) { + if (!obj || typeof obj !== "object") return undefined; + for (const key of keys){ + if (obj[key] != null && obj[key] !== "") return obj[key]; + } + return undefined; +} +async function ensureSandbox(accessToken, { signal } = {}) { + assertGatewayActive(signal); + const url = (0,_url_policy_js__rspack_import_3/* .assertAllowedCredentialUrl */.Re)(backendBase(), { + kind: "backend" + }) + "/aiserver.v1.GrokBotService/EnsureSandBox"; + let res, body; + try { + res = await fetch(url, { + method: "POST", + redirect: "error", + signal: gatewayDeadline(signal), + headers: (0,_headers_js__rspack_import_5/* .ensureSandboxHeaders */._6)(accessToken), + body: "{}" + }); + body = await readJson(res); + } catch (error) { + assertGatewayActive(signal); + throw error; + } + assertGatewayActive(signal); + if (!res.ok) { + const detail = body.message || body.error || body.raw || res.statusText; + throw new GatewayError("EnsureSandBox failed: " + res.status + " " + (0,_url_policy_js__rspack_import_3/* .redactSecrets */.fp)(detail), { + status: res.status, + method: "EnsureSandBox" + }); + } + const gatewayUrl = pick(body, "gatewayUrl", "gateway_url"); + const gatewayToken = pick(body, "gatewayToken", "gateway_token"); + if (!gatewayUrl || !gatewayToken) { + throw new GatewayError("EnsureSandBox returned no gatewayUrl/gatewayToken. Auth may be a dashboard API key (those do not work)."); + } + return { + gatewayUrl: (0,_url_policy_js__rspack_import_3/* .assertAllowedCredentialUrl */.Re)(String(gatewayUrl).replace(/\/$/, ""), { + kind: "gateway" + }), + gatewayToken: String(gatewayToken), + gatewayHeaders: (0,_headers_js__rspack_import_5/* .mergeGatewayHeaders */.bQ)((0,_headers_js__rspack_import_5/* .headersFromEnsureSandbox */.Ew)(body), (0,_headers_js__rspack_import_5/* .headersFromEnv */.gx)()) + }; +} +async function connectGateway({ signal } = {}) { + assertGatewayActive(signal); + const override = gatewayOverride(); + if (override) return override; + const fromApp = sessionFromApp(); + if (fromApp) return fromApp; + const token = accessTokenFromEnv(); + if (!token) { + throw new GatewayError("Set CURSOR_ACCESS_TOKEN, or GROK_BOT_GATEWAY_URL + GROK_BOT_GATEWAY_TOKEN. Do not use a Cursor dashboard API key."); + } + return ensureSandbox(token, { + signal + }); +} +async function gatewayCall(session, method, body = {}, { signal } = {}) { + assertGatewayActive(signal); + const base = (0,_url_policy_js__rspack_import_3/* .assertAllowedCredentialUrl */.Re)(session.gatewayUrl, { + kind: "gateway" + }); + const url = base + "/api/" + method; + // Cancellation can abort read/auth preflights. Once a prompt request starts, + // observe its actual receipt (or timeout) instead of losing certainty on stop. + const prompt = method === "sendPrompt"; + const options = { + method: "POST", + redirect: "error", + signal: gatewayDeadline(prompt ? undefined : signal), + headers: (0,_headers_js__rspack_import_5/* .requestHeaders */.A1)(session), + body: JSON.stringify(body) + }; + assertGatewayActive(signal); // Final synchronous boundary before transmission. + let res, data; + try { + res = await fetch(url, options); + data = await readJson(res); + } catch (error) { + if (!prompt) assertGatewayActive(signal); + throw error; + } + if (!prompt) assertGatewayActive(signal); + if (!res.ok) { + const detail = data.message || data.error || data.raw || res.statusText; + throw new GatewayError(method + " failed: " + res.status + " " + (0,_url_policy_js__rspack_import_3/* .redactSecrets */.fp)(String(detail).slice(0, 300)), { + status: res.status, + method + }); + } + return data; +} +function asRecord(agent) { + if (!agent) return null; + const id = agent.id || agent.agentId; + const memberIds = agent.memberIds || agent.memberAgentIds || []; + const notify = agent.notifyOnUpdatesEnabled ?? agent.notifyOnAgentUpdates; + const hidden = agent.isHiddenFromSidebar ?? agent.hiddenFromSidebar; + return { + id, + name: agent.name || "", + title: agent.title || "", + description: agent.description || "", + avatarShape: agent.avatarShape || "", + avatarColor: agent.avatarColor || "", + ...notify !== undefined ? { + notifyOnAgentUpdates: Boolean(notify) + } : {}, + ...hidden !== undefined ? { + hiddenFromSidebar: Boolean(hidden) + } : {}, + isGroup: agent.isGroup === true || agent.isGroup == null && Array.isArray(memberIds) && memberIds.length > 0, + memberIds: Array.isArray(memberIds) ? memberIds : [] + }; +} +function assertAvatar(kind, value, allowed) { + const trimmed = (value ?? "").trim(); + if (!trimmed) return ""; + if (!allowed.includes(trimmed)) { + throw new GatewayError("Unknown avatar " + kind + " \"" + value + "\". Use: " + allowed.join(" ")); + } + return trimmed; +} +function unwrapList(data) { + if (Array.isArray(data)) return data; + if (Array.isArray(data.agents)) return data.agents; + if (data.agent) return [ + data.agent + ]; + return []; +} +function unwrapOne(data) { + return asRecord(data.agent || data); +} +async function listAgents(session, { signal } = {}) { + const data = await gatewayCall(session, "listAgents", {}, { + signal + }); + return unwrapList(data).map(asRecord).filter((r)=>r && r.id); +} +function resolveFromList(records, ref) { + const needle = String(ref).trim().toLowerCase(); + const byId = records.find((r)=>r.id.toLowerCase() === needle); + if (byId) return byId; + const matches = records.filter((r)=>r.name.toLowerCase() === needle || r.title.toLowerCase() === needle); + if (matches.length === 1) return matches[0]; + if (matches.length === 0) throw new GatewayError("No bot or group named \"" + ref + "\""); + throw new GatewayError("Ambiguous name \"" + ref + "\""); +} +async function resolveRef(session, ref, { signal } = {}) { + return resolveFromList(await listAgents(session, { + signal + }), ref); +} +async function createAgent(session, input) { + const data = await gatewayCall(session, "createAgent", { + name: input.name, + description: input.description || "", + title: input.title || "", + avatarShape: assertAvatar("shape", input.avatarShape, _store_js__rspack_import_2/* .AVATAR_SHAPES */.Jb), + avatarColor: assertAvatar("color", input.avatarColor, _store_js__rspack_import_2/* .AVATAR_COLORS */.T7), + origin: "user" + }); + return unwrapOne(data); +} +async function updateAgent(session, ref, patch = {}) { + const rec = await resolveRef(session, ref); + if (patch.name !== undefined && !String(patch.name).trim()) { + throw new GatewayError("Name cannot be blank."); + } + const profile = { + name: patch.name !== undefined ? String(patch.name).trim() : rec.name, + description: patch.description !== undefined ? String(patch.description) : rec.description + }; + if (patch.title !== undefined) profile.title = String(patch.title); + if (patch.avatarShape !== undefined) profile.avatarShape = assertAvatar("shape", patch.avatarShape, _store_js__rspack_import_2/* .AVATAR_SHAPES */.Jb); + if (patch.avatarColor !== undefined) profile.avatarColor = assertAvatar("color", patch.avatarColor, _store_js__rspack_import_2/* .AVATAR_COLORS */.T7); + await gatewayCall(session, "updateAgent", { + id: rec.id, + profile + }); + if (patch.notifyOnAgentUpdates !== undefined) { + await gatewayCall(session, "setAgentNotifyOnUpdates", { + id: rec.id, + isEnabled: Boolean(patch.notifyOnAgentUpdates) + }); + } + if (patch.hiddenFromSidebar !== undefined) { + await gatewayCall(session, "setAgentHiddenFromSidebar", { + id: rec.id, + isHidden: Boolean(patch.hiddenFromSidebar) + }); + } + const fresh = (await listAgents(session)).find((r)=>r.id === rec.id); + return fresh || rec; +} +async function deleteAgent(session, ref) { + const rec = await resolveRef(session, ref); + await gatewayCall(session, "deleteAgent", { + id: rec.id + }); + return rec; +} +// Grok Bot keeps one skill library per box. Every bot reads the same list, and the +// workflow RPCs take any bot id only to say whose automations ride along. +const SKILL_MAX_BODY_LENGTH = 100000; +const SKILL_SOURCES = { + workflow: "your library", + managed: "team-managed", + plugin: "a plugin", + automation: "a scheduled automation" +}; +function asSkill(skill) { + return { + id: String(skill.id), + name: skill.name || "", + description: skill.description || "", + source: String(skill.source || "workflow"), + ...skill.sourceRef ? { + sourceRef: String(skill.sourceRef) + } : {}, + ...skill.pluginId ? { + pluginId: String(skill.pluginId) + } : {} + }; +} +function asSkills(data) { + const list = Array.isArray(data) ? data : Array.isArray(data?.workflows) ? data.workflows : []; + return list.filter((s)=>s && s.id).map(asSkill); +} +async function anyBotId(session) { + const bot = (await listAgents(session)).find((r)=>!r.isGroup); + if (!bot) throw new GatewayError("Skills need at least one bot. Run gbot bots create first."); + return bot.id; +} +async function listSkills(session) { + return asSkills(await gatewayCall(session, "getAgentWorkflows", { + id: await anyBotId(session) + })); +} +async function addSkill(session, markdown) { + const text = String(markdown); + if (!text.trim()) throw new GatewayError("Skill markdown is empty."); + if (text.length > SKILL_MAX_BODY_LENGTH) { + throw new GatewayError(`Skill markdown is ${text.length} characters. Grok Bot truncates bodies over ${SKILL_MAX_BODY_LENGTH}; shorten it.`); + } + const id = await anyBotId(session); + let data; + try { + data = await gatewayCall(session, "importAgentWorkflowText", { + id, + markdown: text + }); + } catch (error) { + if (error instanceof GatewayError && /response too large/.test(error.message)) { + throw new GatewayError("Grok Bot echoed a skill list too large to read; the import may still have landed. Run gbot skills list."); + } + throw error; + } + const imported = data.result?.imported?.[0]; + if (!imported) { + const reason = data.result?.skipped?.[0]?.reason || "rejected"; + throw new GatewayError(`Grok Bot did not import the skill (${reason}). It needs a name, a non-empty body, and library room.`); + } + return asSkills(data).find((s)=>s.id === String(imported.id)) ?? asSkill(imported); +} +async function removeSkill(session, skillRef) { + const id = await anyBotId(session); + const skills = asSkills(await gatewayCall(session, "getAgentWorkflows", { + id + })); + const needle = String(skillRef).trim().toLowerCase(); + const matches = skills.filter((s)=>s.id.toLowerCase() === needle || s.name.toLowerCase() === needle); + if (matches.length === 0) throw new GatewayError(`No skill "${skillRef}".`); + if (matches.length > 1) throw new GatewayError(`Ambiguous skill name "${skillRef}". Use the id.`); + if (matches[0].source !== "workflow") { + const kind = SKILL_SOURCES[matches[0].source] || matches[0].source; + throw new GatewayError(`"${matches[0].name}" is ${kind}, not a library skill. Manage it where it came from.`); + } + await gatewayCall(session, "deleteAgentWorkflow", { + id, + workflowId: matches[0].id + }); + return matches[0]; +} +function normalizeMemberIds(records, memberRefs) { + const memberIds = new Set(); + for (const ref of memberRefs){ + const rec = resolveFromList(records, ref); + if (rec.isGroup) { + throw new GatewayError(`Cannot add group "${rec.name}" as a member. Nested groups are not allowed.`); + } + memberIds.add(rec.id); + } + if (memberIds.size === 0) { + throw new GatewayError("A group needs at least one existing member agent."); + } + if (memberIds.size > (/* inlined export .MAX_GROUP_MEMBERS */6)) { + throw new GatewayError(`A group can have at most ${(/* inlined export .MAX_GROUP_MEMBERS */6)} members.`); + } + return [ + ...memberIds + ]; +} +async function createGroup(session, input) { + const records = await listAgents(session); + const memberAgentIds = normalizeMemberIds(records, input.memberIds || []); + const data = await gatewayCall(session, "createGroup", { + name: input.name, + description: input.description || "", + memberAgentIds + }); + const rec = unwrapOne(data); + const extras = {}; + if (input.title) extras.title = input.title; + if (input.avatarShape) extras.avatarShape = input.avatarShape; + if (input.avatarColor) extras.avatarColor = input.avatarColor; + if (Object.keys(extras).length && rec?.id) return updateAgent(session, rec.id, extras); + return rec; +} +async function setGroupMembers(session, groupRef, memberRefs) { + const records = await listAgents(session); + const group = resolveFromList(records, groupRef); + if (!group.isGroup) throw new GatewayError(`"${group.name}" is a bot, not a group.`); + const memberAgentIds = normalizeMemberIds(records, memberRefs); + const data = await gatewayCall(session, "setGroupMembers", { + id: group.id, + memberAgentIds + }); + return unwrapOne(data) || { + ...group, + memberIds: memberAgentIds, + isGroup: true + }; +} +async function addGroupMember(session, groupRef, memberRef) { + const records = await listAgents(session); + const group = resolveFromList(records, groupRef); + if (!group.isGroup) throw new GatewayError(`"${group.name}" is a bot, not a group.`); + const member = resolveFromList(records, memberRef); + const next = [ + ...new Set([ + ...group.memberIds, + member.id + ]) + ]; + return setGroupMembers(session, group.id, next); +} +async function removeGroupMember(session, groupRef, memberRef) { + const records = await listAgents(session); + const group = resolveFromList(records, groupRef); + if (!group.isGroup) throw new GatewayError(`"${group.name}" is a bot, not a group.`); + const member = resolveFromList(records, memberRef); + const next = group.memberIds.filter((id)=>id !== member.id); + return setGroupMembers(session, group.id, next); +} +async function sendPrompt(session, ref, prompt, extra = {}) { + assertGatewayActive(extra.signal); + const rec = await resolveRef(session, ref, { + signal: extra.signal + }); + const body = { + agentId: rec.id, + prompt, + clientNonce: extra.clientNonce || (0,node_crypto__rspack_import_0.randomUUID)() + }; + if (extra.replyToId) body.replyToId = extra.replyToId; + let data; + try { + data = await gatewayCall(session, "sendPrompt", body, { + signal: extra.signal + }); + } catch (err) { + // Delivery states: the server answered no (rejected) vs the request may have landed (unknown). + // Never retry an unknown delivery blindly; read the thread first. + if (err && err.delivery == null) { + err.delivery = err instanceof GatewayError && err.status != null && err.status < 500 ? "rejected" : "unknown"; + } + if (err && err.targetId == null) err.targetId = rec.id; + if (err && err.delivery === "unknown" && err instanceof Error && !/delivery unknown/.test(err.message)) { + err.message += " (delivery unknown; check the thread before resending)"; + } + throw err; + } + const messageId = data && typeof data === "object" && typeof data.messageId === "string" ? data.messageId : null; + // Only a confirmed receipt counts as accepted; anything else is unknown, never a silent accept. + // ponytail: full send/execution correlation envelope stays in #37. + return { + target: rec, + result: data && typeof data === "object" ? data : {}, + delivery: messageId ? "accepted" : "unknown", + ...messageId ? { + messageId + } : {} + }; +} +async function getTranscriptTail(session, ref, limit = 40) { + const rec = await resolveRef(session, ref); + const bounded = Math.min(Math.max(Math.trunc(limit) || 40, 1), 200); + const data = await gatewayCall(session, "getAgentTranscriptTail", { + id: rec.id, + limit: bounded + }); + return { + target: rec, + transcript: data + }; +} +async function getThread(session, ref, rootId) { + const rec = await resolveRef(session, ref); + const data = await gatewayCall(session, "getAgentThread", { + id: rec.id, + rootId + }); + return { + target: rec, + thread: data + }; +} +async function listGrokApprovals(session, ref) { + const { target, transcript } = await getTranscriptTail(session, ref, 200); + if (!Array.isArray(transcript?.entries) || transcript.entries.length > 200) throw new GatewayError("Invalid approval transcript coverage"); + return { + target: { + id: target.id, + name: target.name + }, + approvals: transcript.entries.map(_grok_approvals_js__rspack_import_4/* .grokApproval */.Ny).filter(Boolean), + coverage: "Latest 200 transcript entries only; older requests require the owning Grok UI." + }; +} +async function respondGrokApproval(session, ref, input) { + const { entryId, requestId, decision } = _grok_approvals_js__rspack_import_4/* .grokApprovalResponseSchema.parse */.T5.parse({ + ...input, + target: ref + }); + const { target, approvals } = await listGrokApprovals(session, ref); + const matches = approvals.filter((card)=>card.entryId === entryId && card.requestId === requestId); + if (matches.length !== 1) throw new GatewayError("Stale, foreign or unsupported Grok approval; refresh pending requests or use the owning Grok UI"); + const approval = matches[0]; + if (decision === "accept" && approval.truncated) throw new GatewayError("Approval details are truncated; acceptance requires the owning Grok UI"); + const local = approval.type === "local-tool-permission"; + await gatewayCall(session, local ? "resolveLocalToolPermission" : "resolveAutoReviewApproval", { + agentId: target.id, + entryId, + requestId, + resolution: local ? decision === "accept" ? "allow-once" : "deny" : decision === "accept" ? "approved" : "denied" + }); + return { + target, + entryId, + requestId, + decision, + delivery: "accepted" + }; +} + +__webpack_require__.d(__webpack_exports__, { + A0: () => (removeGroupMember), + L5: () => (addSkill), + LV: () => (sendPrompt), + MI: () => (listGrokApprovals), + OR: () => (respondGrokApproval), + RB: () => (deleteAgent), + Sn: () => (createAgent), + Td: () => (setGroupMembers), + Vq: () => (connectGateway), + bA: () => (getTranscriptTail), + bG: () => (listSkills), + fG: () => (getThread), + nF: () => (hasGatewayAuth), + qE: () => (resolveRef), + uX: () => (removeSkill), + vc: () => (listAgents), + wj: () => (createGroup), + x4: () => (updateAgent), + zr: () => (addGroupMember) +}); + + +}, +"./src/core/grok-approvals.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_1 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _url_policy_js__rspack_import_0 = __webpack_require__("./src/core/url-policy.js"); + + +const id = zod__rspack_import_1/* .string */.YjP().min(1).max(1024); +const grokApprovalResponseSchema = zod__rspack_import_1/* .strictObject */.rej({ + target: id, + entryId: id, + requestId: id, + decision: zod__rspack_import_1/* ["enum"] */.k5n([ + "accept", + "decline" + ]) +}); +function grokApproval(entry) { + if (entry?.kind !== "send-message") return null; + const type = entry.message?.type; + const card = type === "auto-review-approval" ? entry.message.approval : type === "local-tool-permission" ? entry.message.ask : null; + if (card?.status !== "pending" || !id.safeParse(card.requestId).success || !id.safeParse(entry.id).success) return null; + const details = {}; + let truncated = false; + for (const key of [ + "reason", + "command", + "summary", + "action", + "description", + "target", + "machineId", + "surface", + "workingDirectory" + ]){ + if (typeof card[key] !== "string") continue; + const text = (0,_url_policy_js__rspack_import_0/* .redactSecrets */.fp)(card[key]); + truncated ||= text.length > 2048; + details[key] = text.slice(0, 2048); + } + return { + entryId: entry.id, + requestId: card.requestId, + type, + ...details, + truncated + }; +} +function grokApprovalNotice(entry, target) { + const approval = grokApproval(entry); + return approval ? `Grok approval pending. Requires an explicit user decision; never approve automatically.\n${JSON.stringify({ + botTarget: target, + ...approval + })}\nUse gbot_grok_respond with target=${JSON.stringify(target)}, entryId, requestId and decision accept (once) or decline.${approval.truncated ? " Details are truncated; acceptance requires the owning Grok UI." : ""} A chat reply is not authorization.` : null; +} + +__webpack_require__.d(__webpack_exports__, { + Ny: () => (grokApproval) +}, { + T5: grokApprovalResponseSchema +}); + + +}, +"./src/core/headers.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +function normalizeHeaderMap(obj) { + if (!obj || typeof obj !== "object" || Array.isArray(obj)) return {}; + const out = {}; + for (const [key, value] of Object.entries(obj)){ + if (value == null || value === "") continue; + out[String(key).toLowerCase()] = String(value); + } + return out; +} +function parseGatewayHeaders(raw) { + if (raw == null || String(raw).trim() === "") return {}; + const parsed = JSON.parse(String(raw)); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("GROK_BOT_GATEWAY_HEADERS must be a JSON object"); + } + return normalizeHeaderMap(parsed); +} +function headersFromEnsureSandbox(body) { + if (!body || typeof body !== "object") return {}; + const mapped = normalizeHeaderMap(body.gatewayHeaders || body.gateway_headers); + if (Object.keys(mapped).length) return mapped; + const token = body.anyrunNetworkToken || body.anyrun_network_token || body.networkToken; + return token ? { + "x-anyrun-network-token": String(token) + } : {}; +} +function headersFromEnv() { + return parseGatewayHeaders(process.env.GROK_BOT_GATEWAY_HEADERS); +} +function mergeGatewayHeaders(sessionHeaders, envHeaders) { + return { + ...sessionHeaders || {}, + ...envHeaders || {} + }; +} +function requestHeaders(session) { + return { + "content-type": "application/json", + authorization: "Bearer " + session.gatewayToken, + ...session.gatewayHeaders || {} + }; +} +function ensureSandboxHeaders(accessToken) { + return { + "content-type": "application/json", + "connect-protocol-version": "1", + authorization: "Bearer " + accessToken, + "x-cursor-client-type": "sand", + "x-cursor-client-version": process.env.SAND_CLIENT_VERSION || "0.20.0", + "x-sand-box-namespace": process.env.SAND_BOX_NAMESPACE || "prod" + }; +} + +__webpack_require__.d(__webpack_exports__, { + A1: () => (requestHeaders), + Ew: () => (headersFromEnsureSandbox), + _6: () => (ensureSandboxHeaders), + bQ: () => (mergeGatewayHeaders), + dk: () => (normalizeHeaderMap), + gx: () => (headersFromEnv) +}); + + +}, +"./src/core/history.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_fs__rspack_import_0 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_1 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_2 = __webpack_require__("node:path"); +/* import */ var node_readline__rspack_import_3 = __webpack_require__("node:readline"); +/* import */ var _transcript_js__rspack_import_4 = __webpack_require__("./src/core/transcript.js"); + + + + + +function historyPath(dir) { + return (0,node_path__rspack_import_2.join)((0,node_path__rspack_import_2.resolve)(dir || process.env.GROK_BOT_HISTORY_DIR || (0,node_path__rspack_import_2.join)((0,node_os__rspack_import_1.homedir)(), ".grok-bot-cli")), "history.jsonl"); +} +// Keep only conversation fields, never gateway responses, session credentials or bot instructions. +function saveHistory(out, { dir, disabled, event, prompt, rootId } = {}) { + // Opt-in only: plaintext local history stays off unless GROK_BOT_HISTORY=on (or true/1). + if (disabled || !/^(on|true|1)$/i.test(process.env.GROK_BOT_HISTORY || "")) return; + try { + const recordedAt = new Date().toISOString(); + const target = { + id: out.target.id, + name: out.target.name, + kind: out.target.isGroup ? "group" : "bot" + }; + const payload = out.transcript || out.thread || out; + const entries = event === "send" ? [ + { + role: "user", + text: prompt + } + ] : (0,_transcript_js__rspack_import_4/* .transcriptEntries */.xw)(payload); + const rows = entries.map((entry)=>({ + version: 1, + recordedAt, + event, + target, + ...rootId ? { + rootId + } : {}, + role: String(entry.role || entry.kind || entry.sender || entry.type || "msg"), + ...entry.id ? { + messageId: String(entry.id) + } : {}, + ...entry.timestamp || entry.createdAt ? { + timestamp: String(entry.timestamp || entry.createdAt) + } : {}, + text: (0,_transcript_js__rspack_import_4/* .entryText */.u0)(entry) + })); + if (!rows.length) return; + const path = historyPath(dir); + (0,node_fs__rspack_import_0.mkdirSync)((0,node_path__rspack_import_2.dirname)(path), { + recursive: true, + mode: 448 + }); + const fd = (0,node_fs__rspack_import_0.openSync)(path, node_fs__rspack_import_0.constants.O_CREAT | node_fs__rspack_import_0.constants.O_APPEND | node_fs__rspack_import_0.constants.O_RDWR | node_fs__rspack_import_0.constants.O_NOFOLLOW, 384); + try { + // Separate a previous interrupted append from the next complete record. + const size = (0,node_fs__rspack_import_0.fstatSync)(fd).size; + const last = Buffer.alloc(1); + if (size) (0,node_fs__rspack_import_0.readSync)(fd, last, 0, 1, size - 1); + const prefix = size && last[0] !== 10 ? "\n" : ""; + (0,node_fs__rspack_import_0.appendFileSync)(fd, prefix + rows.map((row)=>JSON.stringify(row)).join("\n") + "\n"); + } finally{ + (0,node_fs__rspack_import_0.closeSync)(fd); + } + } catch { + // A successful remote send must not look failed and invite an accidental resend. + process.stderr.write("Warning: could not save local history. Check the history directory and permissions.\n"); + } +} +/** + * @param {string} path + * @param {{ ref?: string, search?: string, limit?: number }} [options] + */ async function readHistory(path, { ref, search, limit = 40 } = {}) { + const rows = []; + let malformed = 0; + const input = (0,node_fs__rspack_import_0.createReadStream)(path, { + encoding: "utf8" + }); + const lines = (0,node_readline__rspack_import_3.createInterface)({ + input, + crlfDelay: Infinity + }); + try { + for await (const line of lines){ + if (!line.trim()) continue; + let row; + try { + row = JSON.parse(line); + if (row?.version !== 1 || typeof row.text !== "string" || typeof row.role !== "string" || typeof row.recordedAt !== "string" || typeof row.target?.id !== "string" || typeof row.target?.name !== "string") { + throw new Error("Invalid history record"); + } + } catch { + malformed++; + continue; + } + if (ref && row.target.id !== ref && row.target.name.toLowerCase() !== ref.toLowerCase()) continue; + if (search !== undefined && !row.text.toLowerCase().includes(search.toLowerCase())) continue; + rows.push(row); + if (rows.length > limit) rows.shift(); + } + } catch (err) { + if (err.code !== "ENOENT") throw err; + } finally{ + lines.close(); + input.destroy(); + } + if (malformed) process.stderr.write("Warning: skipped " + malformed + " malformed local history record(s).\n"); + return rows; +} + +__webpack_require__.d(__webpack_exports__, { + Lu: () => (readHistory), + QX: () => (saveHistory), + ae: () => (historyPath) +}); + + +}, +"./src/core/relay/control.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_string_decoder__rspack_import_0 = __webpack_require__("node:string_decoder"); +/* import */ var node_net__rspack_import_1 = __webpack_require__("node:net"); +/* import */ var node_crypto__rspack_import_2 = __webpack_require__("node:crypto"); +/* import */ var _profile_js__rspack_import_3 = __webpack_require__("./src/core/relay/profile.js"); + + + + +const RELAY_PROTOCOL = 1; +const CONTROL_BYTES = 1024 * 1024; +const CONTROL_TIMEOUT = 45000; +function relayRequest(options, method, input = {}, { timeoutMs = CONTROL_TIMEOUT, signal, requestId = (0,node_crypto__rspack_import_2.randomUUID)() } = {}) { + const { socketPath, profile } = (0,_profile_js__rspack_import_3/* .relayLocation */.hQ)(options); + return new Promise((resolve, reject)=>{ + const decoder = new node_string_decoder__rspack_import_0.StringDecoder("utf8"); + let buffer = "", bytes = 0, settled = false, connected = false; + const socket = (0,node_net__rspack_import_1.connect)(socketPath); + const finish = (error, value)=>{ + if (settled) return; + settled = true; + clearTimeout(timer); + signal?.removeEventListener("abort", abort); + socket.destroy(); + error ? reject(error) : resolve(value); + }; + const uncertain = ()=>Object.assign(Error(`Relay control connection lost; do not resend with a new requestId (${requestId}). Check bridge status.`), { + requestId + }); + const abort = ()=>finish(uncertain()); + const timer = setTimeout(abort, timeoutMs); + signal?.addEventListener("abort", abort, { + once: true + }); + if (signal?.aborted) return abort(); + socket.on("error", (error)=>finish(connected ? uncertain() : error)); + socket.on("close", ()=>finish(uncertain())); + socket.on("connect", ()=>{ + connected = true; + const line = JSON.stringify({ + version: RELAY_PROTOCOL, + profile, + requestId, + method, + input + }) + "\n"; + if (Buffer.byteLength(line) > CONTROL_BYTES) return finish(Error("Relay control request exceeds budget")); + socket.write(line); + }); + socket.on("data", (chunk)=>{ + bytes += chunk.length; + if (bytes > CONTROL_BYTES) return finish(Error("Relay control response exceeds budget")); + buffer += decoder.write(chunk); + const end = buffer.indexOf("\n"); + if (end < 0) return; + try { + const reply = JSON.parse(buffer.slice(0, end)); + if (reply.version !== RELAY_PROTOCOL || reply.requestId !== requestId) throw Error("Relay protocol identity mismatch"); + if (reply.error) throw Error(reply.error); + if (reply.profile !== profile) throw Error("Relay profile mismatch"); + finish(null, reply.result); + } catch (error) { + finish(error); + } + }); + }); +} + +__webpack_require__.d(__webpack_exports__, { + lJ: () => (relayRequest) +}); + + +}, +"./src/core/relay/managed.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_child_process__rspack_import_0 = __webpack_require__("node:child_process"); +/* import */ var node_fs_promises__rspack_import_1 = __webpack_require__("node:fs/promises"); +/* import */ var node_path__rspack_import_2 = __webpack_require__("node:path"); +/* import */ var node_url__rspack_import_3 = __webpack_require__("node:url"); +/* import */ var node_crypto__rspack_import_4 = __webpack_require__("node:crypto"); +/* import */ var _profile_js__rspack_import_5 = __webpack_require__("./src/core/relay/profile.js"); +/* import */ var _control_js__rspack_import_6 = __webpack_require__("./src/core/relay/control.js"); + + + + + + + +/** @param {{pluginRoot?: string, moduleUrl?: string}} options */ async function resolveRelayWorker({ pluginRoot, moduleUrl = import.meta.url } = {}) { + const roots = []; + if (pluginRoot) roots.push(pluginRoot); + let path = (0,node_path__rspack_import_2.dirname)((0,node_url__rspack_import_3.fileURLToPath)(moduleUrl)); + for(let i = 0; i < 5; i++){ + roots.push(path); + path = (0,node_path__rspack_import_2.dirname)(path); + } + for (const candidate of new Set(roots)){ + let manifest; + try { + manifest = JSON.parse(await (0,node_fs_promises__rspack_import_1.readFile)((0,node_path__rspack_import_2.join)(candidate, "agent-bundle.manifest.json"), "utf8")); + } catch (error) { + if (error.code === "ENOENT") continue; + throw error; + } + const relative = "scripts/gbot-relay.mjs"; + const file = manifest.files?.find((f)=>f.path === relative); + if (manifest.application?.name !== "gbot" || !file || !manifest.executables?.scripts?.some((s)=>s.path === relative)) continue; + const root = await (0,node_fs_promises__rspack_import_1.realpath)(candidate), worker = (0,node_path__rspack_import_2.join)(root, relative), stat = await (0,node_fs_promises__rspack_import_1.lstat)(worker); + if (!stat.isFile() || stat.isSymbolicLink() || await (0,node_fs_promises__rspack_import_1.realpath)(worker) !== worker) throw Error("Relay worker must be a regular packaged script"); + if (stat.size !== file.bytes || (0,_profile_js__rspack_import_5/* .digest */.br)(await (0,node_fs_promises__rspack_import_1.readFile)(worker)) !== file.sha256) throw Error("Packaged relay worker checksum mismatch"); + return worker; + } + throw Error("Packaged relay worker not found; rebuild or reinstall the plugin"); +} +const unavailable = (error)=>[ + "ENOENT", + "ECONNREFUSED" + ].includes(error.code); +async function ensureRelayWorker(options = {}) { + const location = (0,_profile_js__rspack_import_5/* .relayLocation */.hQ)(options); + try { + return await (0,_control_js__rspack_import_6/* .relayRequest */.lJ)(location, "hello", {}, { + timeoutMs: 1500 + }); + } catch (error) { + if (!unavailable(error)) throw error; + } + const workerPath = await resolveRelayWorker(options); + const child = (0,node_child_process__rspack_import_0.spawn)(process.execPath, [ + workerPath + ], { + detached: true, + stdio: "ignore", + env: { + ...location.env, + GROK_BOT_RELAY_DIR: location.stateDir + }, + cwd: (0,node_path__rspack_import_2.dirname)(workerPath) + }); + let spawnError; + child.on("error", (error)=>{ + spawnError = error; + }); + child.unref(); + const end = Date.now() + 10000; + while(Date.now() < end){ + if (spawnError) throw spawnError; + if (options.signal?.aborted) throw Error("Relay startup cancelled before submission"); + try { + return await (0,_control_js__rspack_import_6/* .relayRequest */.lJ)(location, "hello", {}, { + timeoutMs: 1000, + signal: options.signal + }); + } catch (error) { + if (!unavailable(error)) throw error; + } + await new Promise((resolve)=>setTimeout(resolve, 75)); + } + throw Error("Relay worker startup failed or timed out; no untracked send was attempted. Inspect bridge status and the relay owner lock."); +} +async function managedOperation(method, input, options = {}) { + const location = (0,_profile_js__rspack_import_5/* .relayLocation */.hQ)(options); + const requestId = input.requestId ?? (0,node_crypto__rspack_import_4.randomUUID)(); + if (![ + "status", + "stop", + "respond" + ].includes(method)) await ensureRelayWorker(options); + try { + return await (0,_control_js__rspack_import_6/* .relayRequest */.lJ)(location, method, input, { + signal: options.signal, + requestId + }); + } catch (error) { + if (method === "status" && unavailable(error)) return { + worker: { + state: "stopped", + profile: location.profile, + supervised: false + }, + reason: "Worker is not running. Start a route or tracked send to resume saved routes." + }; + // Never retry a disconnected mutation. Its durable request ID is the recovery handle. + throw error; + } +} + +__webpack_require__.d(__webpack_exports__, { + Bb: () => (managedOperation), + _v: () => (resolveRelayWorker) +}); + + +}, +"./src/core/relay/profile.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_os__rspack_import_1 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_2 = __webpack_require__("node:path"); +/* import */ var _codex_bridge_js__rspack_import_3 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _app_session_js__rspack_import_4 = __webpack_require__("./src/core/app-session.js"); + + + + + +const digest = (value)=>(0,node_crypto__rspack_import_0.createHash)("sha256").update(value).digest("hex"); +// Only explicit overrides are hashed. App-session token refresh retains its source identity. +function relayProfile(env = process.env) { + const keys = [ + "GROK_BOT_GATEWAY_URL", + "SAND_HOST_GATEWAY_URL", + "SAND_HOST_PORT", + "GROK_BOT_GATEWAY_TOKEN", + "SAND_HOST_GATEWAY_TOKEN", + "SAND_GATEWAY_TOKEN", + "CURSOR_ACCESS_TOKEN", + "GROK_BOT_ACCESS_TOKEN", + "SAND_ACCESS_TOKEN", + "GROK_BOT_GATEWAY_HEADERS", + "SAND_BACKEND_URL", + "CURSOR_API_BASE_URL", + "SAND_BOX_NAMESPACE", + "SAND_CLIENT_VERSION", + "GROK_BOT_CODEX_THREADS", + "GROK_BOT_MAX_HOPS", + "GROK_BOT_CODEX_EXPERIMENTAL", + "GROK_BOT_ALLOW_LOCAL_GATEWAY", + "GROK_BOT_ALLOW_ANY_GATEWAY", + "GROK_BOT_TEST", + "NODE_ENV", + // Secret Service credentials depend on the caller's desktop session. + "DBUS_SESSION_BUS_ADDRESS", + "DISPLAY" + ]; + return digest(JSON.stringify([ + (0,node_path__rspack_import_2.resolve)((0,_codex_bridge_js__rspack_import_3/* .codexSocketPath */.ql)(env)), + (0,_app_session_js__rspack_import_4/* .grokBotGatewayDescriptorPath */.dQ)((0,node_os__rspack_import_1.homedir)(), process.platform, env), + ...keys.map((key)=>[ + key, + env[key] ?? "" + ]) + ])); +} +function relayLocation({ env = process.env, stateDir, profile = relayProfile(env) } = {}) { + if (process.platform === "win32") throw Error("Codex relay requires Unix-domain sockets; Windows is unsupported."); + const dir = (0,node_path__rspack_import_2.resolve)(stateDir ?? env.GROK_BOT_RELAY_DIR ?? (0,node_path__rspack_import_2.join)((0,node_os__rspack_import_1.homedir)(), ".grok-bot-cli", "relay", profile.slice(0, 24))); + // macOS Unix sockets cannot use arbitrarily long installation/state paths. + const socketDir = Buffer.byteLength((0,node_path__rspack_import_2.join)(dir, "control.sock")) < 100 ? dir : (0,node_path__rspack_import_2.join)("/tmp", `gbot-relay-${process.getuid()}`, digest(dir).slice(0, 24)); + return { + stateDir: dir, + profile, + env, + socketDir, + socketPath: (0,node_path__rspack_import_2.join)(socketDir, "control.sock") + }; +} + +__webpack_require__.d(__webpack_exports__, { + hQ: () => (relayLocation) +}, { + br: digest +}); + + +}, +"./src/core/store.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_2 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_3 = __webpack_require__("node:path"); + + + + +const GROUP_JSON_VERSION = 1; +const MAX_GROUP_MEMBERS = 6; +const PROFILE_FILE = "profile.json"; +const GROUP_FILE = "group.json"; +const SETTINGS_FILE = "settings.json"; +const AVATAR_SHAPES = [ + "blob", + "pebble", + "bean", + "egg", + "squircle", + "tablet", + "capsule", + "cylinder", + "hex", + "gem", + "crystal", + "wedge", + "shield", + "dome", + "arch", + "cloud", + "teardrop", + "leaf" +]; +const AVATAR_COLORS = [ + "black", + "brown", + "red", + "orange", + "yellow", + "green", + "cyan", + "blue", + "violet", + "magenta", + "gray" +]; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +class StoreError extends Error { + constructor(message){ + super(message); + this.name = "StoreError"; + } +} +function readJson(path) { + return JSON.parse((0,node_fs__rspack_import_1.readFileSync)(path, "utf8")); +} +function writeJson(path, value) { + (0,node_fs__rspack_import_1.writeFileSync)(path, `${JSON.stringify(value, null, 2)}\n`, "utf8"); +} +function isUuid(value) { + return UUID_RE.test(value); +} +function defaultCandidateRoots() { + const home = (0,node_os__rspack_import_2.homedir)(); + const env = [ + process.env.GROK_BOT_AGENTS_DIR + ].filter(Boolean); + return [ + ...env, + "/home/box/agent-data/agents", + "/home/box/sand-data/agents", + (0,node_path__rspack_import_3.join)(home, ".grokbot", "agent-data", "agents"), + (0,node_path__rspack_import_3.join)(home, ".grokbot", "sand-data", "agents"), + (0,node_path__rspack_import_3.join)(home, "Library", "Application Support", "Grok Bot", "agent-data", "agents"), + (0,node_path__rspack_import_3.join)(home, "Library", "Application Support", "Grok Bot", "sand-data", "agents") + ]; +} +function looksLikeAgentsRoot(dir) { + if (!dir || !(0,node_fs__rspack_import_1.existsSync)(dir) || !(0,node_fs__rspack_import_1.statSync)(dir).isDirectory()) return false; + const entries = (0,node_fs__rspack_import_1.readdirSync)(dir, { + withFileTypes: true + }); + return entries.some((e)=>e.isDirectory() && isUuid(e.name) && (0,node_fs__rspack_import_1.existsSync)((0,node_path__rspack_import_3.join)(dir, e.name, PROFILE_FILE))); +} +function resolveAgentsRoot(explicit) { + if (explicit) { + (0,node_fs__rspack_import_1.mkdirSync)(explicit, { + recursive: true + }); + return explicit; + } + for (const candidate of defaultCandidateRoots()){ + if (looksLikeAgentsRoot(candidate)) return candidate; + } + throw new StoreError("Could not find a Grok Bot agents directory. Pass --dir or set GROK_BOT_AGENTS_DIR.\nThe macOS app keeps the live roster on its cloud computer (agent-data/agents), not in ~/Library/Application Support/Grok Bot."); +} +function readProfile(dir) { + const path = (0,node_path__rspack_import_3.join)(dir, PROFILE_FILE); + if (!(0,node_fs__rspack_import_1.existsSync)(path)) return null; + const raw = readJson(path); + return { + name: String(raw.name ?? ""), + description: String(raw.description ?? ""), + title: String(raw.title ?? ""), + avatarShape: String(raw.avatarShape ?? ""), + avatarColor: String(raw.avatarColor ?? "") + }; +} +function readGroup(dir) { + const path = (0,node_path__rspack_import_3.join)(dir, GROUP_FILE); + if (!(0,node_fs__rspack_import_1.existsSync)(path)) return null; + const raw = readJson(path); + const memberIds = Array.isArray(raw.memberIds) ? raw.memberIds.map(String) : []; + return { + version: Number(raw.version ?? GROUP_JSON_VERSION), + memberIds + }; +} +function readRawSettings(dir) { + const path = (0,node_path__rspack_import_3.join)(dir, SETTINGS_FILE); + if (!(0,node_fs__rspack_import_1.existsSync)(path)) return {}; + try { + const raw = readJson(path); + return raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; + } catch { + return {}; + } +} +function readSettings(dir) { + const raw = readRawSettings(dir); + return { + notifyOnAgentUpdates: typeof raw.notifyOnAgentUpdates === "boolean" ? raw.notifyOnAgentUpdates : true, + hiddenFromSidebar: typeof raw.hiddenFromSidebar === "boolean" ? raw.hiddenFromSidebar : false + }; +} +function listRecords(root) { + if (!(0,node_fs__rspack_import_1.existsSync)(root)) return []; + const out = []; + for (const entry of (0,node_fs__rspack_import_1.readdirSync)(root, { + withFileTypes: true + })){ + if (!entry.isDirectory() || !isUuid(entry.name)) continue; + const dir = (0,node_path__rspack_import_3.join)(root, entry.name); + const profile = readProfile(dir); + if (!profile) continue; + const group = readGroup(dir); + out.push({ + id: entry.name, + path: dir, + ...profile, + ...readSettings(dir), + isGroup: group != null, + memberIds: group?.memberIds ?? [] + }); + } + return out.sort((a, b)=>a.name.localeCompare(b.name) || a.id.localeCompare(b.id)); +} +function resolveRef(root, ref) { + const records = listRecords(root); + if (isUuid(ref)) { + const exact = records.find((r)=>r.id.toLowerCase() === ref.toLowerCase()); + if (!exact) throw new StoreError(`No bot or group with id ${ref}`); + return exact; + } + const needle = ref.trim().toLowerCase(); + const matches = records.filter((r)=>r.name.toLowerCase() === needle || r.title.toLowerCase() === needle); + if (matches.length === 1) return matches[0]; + if (matches.length === 0) throw new StoreError(`No bot or group named "${ref}"`); + throw new StoreError(`Ambiguous name "${ref}": ${matches.map((m)=>`${m.name} (${m.id})`).join(", ")}`); +} +function assertAvatar(kind, value, allowed) { + const trimmed = (value ?? "").trim(); + if (!trimmed) return ""; + if (!allowed.includes(trimmed)) { + throw new StoreError(`Unknown avatar ${kind} "${value}". Use: ${allowed.join(" ")}`); + } + return trimmed; +} +function writeProfile(dir, profile) { + writeJson((0,node_path__rspack_import_3.join)(dir, PROFILE_FILE), { + name: profile.name.trim(), + description: (profile.description ?? "").trim(), + title: (profile.title ?? "").trim(), + avatarShape: assertAvatar("shape", profile.avatarShape, AVATAR_SHAPES), + avatarColor: assertAvatar("color", profile.avatarColor, AVATAR_COLORS) + }); +} +function writeSettings(dir) { + writeJson((0,node_path__rspack_import_3.join)(dir, SETTINGS_FILE), { + notifyOnAgentUpdates: true + }); +} +function mergeSettings(dir, patch) { + const update = {}; + if (patch.notifyOnAgentUpdates !== undefined) update.notifyOnAgentUpdates = Boolean(patch.notifyOnAgentUpdates); + if (patch.hiddenFromSidebar !== undefined) update.hiddenFromSidebar = Boolean(patch.hiddenFromSidebar); + if (Object.keys(update).length === 0) return; + writeJson((0,node_path__rspack_import_3.join)(dir, SETTINGS_FILE), { + ...readRawSettings(dir), + ...update + }); +} +function writeGroup(dir, memberIds) { + writeJson((0,node_path__rspack_import_3.join)(dir, GROUP_FILE), { + version: GROUP_JSON_VERSION, + memberIds + }); +} +function normalizeMemberIds(root, memberRefs) { + const records = listRecords(root); + const groups = new Set(records.filter((r)=>r.isGroup).map((r)=>r.id)); + const resolved = []; + const seen = new Set(); + for (const ref of memberRefs){ + const rec = resolveRef(root, ref); + if (groups.has(rec.id)) { + throw new StoreError(`Cannot add group "${rec.name}" as a member. Nested groups are not allowed.`); + } + if (seen.has(rec.id)) continue; + seen.add(rec.id); + resolved.push(rec.id); + } + if (resolved.length > MAX_GROUP_MEMBERS) { + throw new StoreError(`A group can have at most ${MAX_GROUP_MEMBERS} members.`); + } + return resolved; +} +function createAgent(root, input) { + const name = (input.name ?? "").trim(); + if (!name) throw new StoreError("Name is required."); + const id = (0,node_crypto__rspack_import_0.randomUUID)(); + const dir = (0,node_path__rspack_import_3.join)(root, id); + (0,node_fs__rspack_import_1.mkdirSync)(dir, { + recursive: true + }); + (0,node_fs__rspack_import_1.mkdirSync)((0,node_path__rspack_import_3.join)(dir, "memory"), { + recursive: true + }); + (0,node_fs__rspack_import_1.mkdirSync)((0,node_path__rspack_import_3.join)(dir, "automations"), { + recursive: true + }); + writeProfile(dir, { + name, + description: input.description ?? "", + title: input.title ?? "", + avatarShape: input.avatarShape ?? "", + avatarColor: input.avatarColor ?? "" + }); + writeSettings(dir); + return resolveRef(root, id); +} +function updateAgent(root, ref, patch = {}) { + const rec = resolveRef(root, ref); + if (patch.name !== undefined) { + const name = String(patch.name).trim(); + if (!name) throw new StoreError("Name cannot be blank."); + } + const hasProfile = patch.name !== undefined || patch.description !== undefined || patch.title !== undefined || patch.avatarShape !== undefined || patch.avatarColor !== undefined; + if (hasProfile) { + writeProfile(rec.path, { + name: patch.name !== undefined ? String(patch.name) : rec.name, + description: patch.description !== undefined ? String(patch.description) : rec.description, + title: patch.title !== undefined ? String(patch.title) : rec.title, + avatarShape: patch.avatarShape !== undefined ? String(patch.avatarShape) : rec.avatarShape, + avatarColor: patch.avatarColor !== undefined ? String(patch.avatarColor) : rec.avatarColor + }); + } + mergeSettings(rec.path, patch); + return resolveRef(root, rec.id); +} +function deleteAgent(root, ref) { + const rec = resolveRef(root, ref); + (0,node_fs__rspack_import_1.rmSync)(rec.path, { + recursive: true, + force: true + }); + for (const other of listRecords(root).filter((r)=>r.isGroup)){ + if (!other.memberIds.includes(rec.id)) continue; + writeGroup(other.path, other.memberIds.filter((id)=>id !== rec.id)); + } + return rec; +} +function createGroup(root, input) { + const memberIds = normalizeMemberIds(root, input.memberIds ?? []); + if (memberIds.length === 0) { + throw new StoreError("A group needs at least one existing member agent."); + } + const existing = listRecords(root).find((r)=>r.isGroup && r.memberIds.length === memberIds.length && r.memberIds.every((id)=>memberIds.includes(id))); + if (existing) return existing; + const group = createAgent(root, { + name: input.name, + description: input.description ?? "", + title: input.title ?? "", + avatarShape: input.avatarShape ?? "", + avatarColor: input.avatarColor ?? "" + }); + writeGroup((0,node_path__rspack_import_3.join)(root, group.id), memberIds); + return resolveRef(root, group.id); +} +function setGroupMembers(root, groupRef, memberRefs) { + const group = resolveRef(root, groupRef); + if (!group.isGroup) throw new StoreError(`"${group.name}" is a bot, not a group.`); + const memberIds = normalizeMemberIds(root, memberRefs); + if (memberIds.length === 0) { + throw new StoreError("A group needs at least one existing member agent."); + } + writeGroup(group.path, memberIds); + return resolveRef(root, group.id); +} +function addGroupMember(root, groupRef, memberRef) { + const group = resolveRef(root, groupRef); + return setGroupMembers(root, group.id, [ + ...group.memberIds, + memberRef + ]); +} +function removeGroupMember(root, groupRef, memberRef) { + const group = resolveRef(root, groupRef); + const member = resolveRef(root, memberRef); + return setGroupMembers(root, group.id, group.memberIds.filter((id)=>id !== member.id)); +} + +__webpack_require__.d(__webpack_exports__, { + A0: () => (removeGroupMember), + A8: () => (looksLikeAgentsRoot), + AD: () => (StoreError), + RB: () => (deleteAgent), + Sn: () => (createAgent), + Td: () => (setGroupMembers), + VI: () => (listRecords), + qE: () => (resolveRef), + v1: () => (resolveAgentsRoot), + wj: () => (createGroup), + x4: () => (updateAgent), + ye: () => (defaultCandidateRoots), + zr: () => (addGroupMember) +}, { + Jb: AVATAR_SHAPES, + T7: AVATAR_COLORS +}); + + +}, +"./src/core/transcript.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** Coerce anything to a string without throwing (numbers, BigInt, unserializable objects). */ function toSafeText(value) { + if (typeof value === "string") return value; + if (value == null) return ""; + if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value); + try { + const out = JSON.stringify(value); + return typeof out === "string" ? out : ""; + } catch { + return "[unserializable]"; + } +} +/** Coerce to string and replace lone surrogates so downstream slicing/JSON never breaks. */ function normalizeText(value) { + return toSafeText(value).replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?{ + if (typeof part === "string") return part; + if (part && typeof part === "object") return part.text || part.content || ""; + return ""; + }).filter(Boolean).join("\n"); + } + if (content && typeof content === "object") return content.text || toSafeText(content); + // Bot replies arrive as `{ kind: "send-message", message: { type, content } }`. + if (e.message && typeof e.message === "object" && typeof e.message.content === "string") return e.message.content; + return typeof e.preview === "string" ? e.preview : ""; +} +function transcriptEntries(payload) { + if (!payload || typeof payload !== "object") return []; + return Array.isArray(payload.entries) ? payload.entries : []; +} +function sourceEntryId(entry) { + if (!entry || typeof entry !== "object") return ""; + return typeof entry.id === "string" ? entry.id : ""; +} +function lastSourceId(entries, fallback = "") { + for(let index = entries.length - 1; index >= 0; index -= 1){ + const id = sourceEntryId(entries[index]); + if (id) return id; + } + return fallback; +} +function transcriptDelta(payload, { after, limit = 40 } = /** @type {{ after?: string, limit?: number }} */ {}) { + const bounded = Math.min(Math.max(Math.trunc(limit) || 40, 1), 200); + const page = transcriptEntries(payload).slice(-bounded); + if (after === undefined) { + const gapReset = page.length > 0 && !sourceEntryId(page[page.length - 1]); + return { + cursor: lastSourceId(page), + entries: page, + entryCount: page.length, + gapReset + }; + } + const afterIndex = page.findIndex((entry)=>sourceEntryId(entry) === after); + if (afterIndex === -1) { + return { + cursor: lastSourceId(page), + entries: page, + entryCount: page.length, + gapReset: true + }; + } + const entries = page.slice(afterIndex + 1); + if (entries.length > 0 && !sourceEntryId(entries[entries.length - 1])) { + return { + cursor: lastSourceId(page), + entries: page, + entryCount: page.length, + gapReset: true + }; + } + return { + cursor: lastSourceId(entries, after), + entries, + entryCount: entries.length, + gapReset: false + }; +} + +__webpack_require__.d(__webpack_exports__, { + N3: () => (transcriptDelta), + u0: () => (entryText), + xw: () => (transcriptEntries) +}); + + +}, +"./src/core/url-policy.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Gateway / backend URL policy: only send credentials to expected hosts. + * + * Gateway (box + API): https on *.cursor.sh / *.cursor.com (and apex) / + * *.cursorvm.com (EnsureSandBox box hosts, e.g. -pod-.us12.cursorvm.com). + * Backend (EnsureSandBox / Cursor API): https on *.cursor.sh / *.cursor.com only — + * never *.cursorvm.com, so a CURSOR_ACCESS_TOKEN cannot be pointed at a box host. + * Local/dev gateways: http(s)://127.0.0.1|localhost|::1 when GROK_BOT_ALLOW_LOCAL_GATEWAY=1. + * Escape hatch: GROK_BOT_ALLOW_ANY_GATEWAY=1 (unsafe; disables host checks; warns once). + * Test mode (GROK_BOT_TEST=1 or NODE_ENV=test): loopback only, for gateway and backend + * alike, and the escape hatches are ignored — a test can never reach a live thread. + */ function truthyEnv(name) { + const v = (process.env[name] || "").trim().toLowerCase(); + return v === "1" || v === "true" || v === "yes"; +} +function allowAnyGateway() { + return truthyEnv("GROK_BOT_ALLOW_ANY_GATEWAY"); +} +function allowLocalGateway() { + return truthyEnv("GROK_BOT_ALLOW_LOCAL_GATEWAY"); +} +function testMode() { + return truthyEnv("GROK_BOT_TEST") || process.env.NODE_ENV === "test"; +} +const warned = new Set(); +function warnOnce(key, message) { + if (warned.has(key)) return; + warned.add(key); + process.stderr.write(message + "\n"); +} +/** Test hook: clear the one-shot warn set. */ function resetPolicyWarnings() { + warned.clear(); +} +function isLocalHostname(hostname) { + const h = String(hostname || "").toLowerCase().replace(/^\[|\]$/g, ""); + return h === "localhost" || h === "127.0.0.1" || h === "::1"; +} +function isCursorApiHostname(hostname) { + const h = String(hostname || "").toLowerCase(); + if (!h) return false; + if (h === "cursor.sh" || h === "cursor.com") return true; + return h.endsWith(".cursor.sh") || h.endsWith(".cursor.com"); +} +function isCursorGatewayHostname(hostname) { + const h = String(hostname || "").toLowerCase(); + return isCursorApiHostname(h) || h.endsWith(".cursorvm.com"); +} +/** + * @param {string} rawUrl + * @param {{ kind?: "gateway" | "backend" }} [opts] + * @returns {string} normalized URL without trailing slash + */ function assertAllowedCredentialUrl(rawUrl, opts = {}) { + const kind = opts.kind || "gateway"; + const label = kind === "backend" ? "backend URL" : "gateway URL"; + let parsed; + try { + parsed = new URL(String(rawUrl)); + } catch { + throw new Error("Invalid " + label + "."); + } + if (parsed.username || parsed.password) { + throw new Error("Rejected " + label + ": userinfo is not allowed."); + } + if (testMode()) { + if (!isLocalHostname(parsed.hostname) || parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error("Rejected " + label + " host \"" + parsed.hostname + "\": test mode (GROK_BOT_TEST / NODE_ENV=test) only allows http(s) loopback gateways."); + } + return String(rawUrl).replace(/\/$/, ""); + } + if (allowAnyGateway()) { + warnOnce("ALLOW_ANY", "warning: GROK_BOT_ALLOW_ANY_GATEWAY is set; credential host checks are disabled."); + return String(rawUrl).replace(/\/$/, ""); + } + const host = parsed.hostname; + const local = isLocalHostname(host); + if (local) { + if (kind === "backend") { + throw new Error("Rejected backend URL host \"" + host + "\". EnsureSandBox backends must be https on *.cursor.sh / *.cursor.com."); + } + if (!allowLocalGateway()) { + throw new Error("Rejected " + label + " host \"" + host + "\". Set GROK_BOT_ALLOW_LOCAL_GATEWAY=1 to permit localhost/127.0.0.1 gateways."); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error("Rejected " + label + ": local gateways must use http or https."); + } + warnOnce("ALLOW_LOCAL", "warning: GROK_BOT_ALLOW_LOCAL_GATEWAY is set; credentials may be sent to a loopback gateway."); + return String(rawUrl).replace(/\/$/, ""); + } + if (parsed.protocol !== "https:") { + throw new Error("Rejected " + label + ": only https is allowed (got " + parsed.protocol + ")."); + } + const allowed = kind === "backend" ? isCursorApiHostname(host) : isCursorGatewayHostname(host); + if (!allowed) { + const expected = kind === "backend" ? "*.cursor.sh / *.cursor.com" : "*.cursor.sh / *.cursor.com / *.cursorvm.com"; + throw new Error("Rejected " + label + " host \"" + host + "\". Expected " + expected + ", or set GROK_BOT_ALLOW_LOCAL_GATEWAY=1 / GROK_BOT_ALLOW_ANY_GATEWAY=1."); + } + return String(rawUrl).replace(/\/$/, ""); +} +/** + * Redact common credential shapes from error / log strings. + * Covers Bearer/Basic/scheme Authorization values, cookie headers, and named token fields. + */ function redactSecrets(text) { + let s = String(text); + // Cookie headers first so a later Authorization pass cannot swallow them. + // Stop the value before the next header-shaped token on the same line. + s = s.replace(/(^|[\s,{;])((?:set-cookie|cookie)\s*[:=]\s*)([^\n;]+?)(?=\s+(?:set-cookie|cookie|authorization|proxy-authorization)\b|\s*$)/gi, "$1$2"); + // Scheme + credential only (e.g. "Basic abc", "Bearer xyz") — not the rest of the line. + s = s.replace(/(^|[\s,{;])((?:authorization|proxy-authorization)\s*[:=]\s*)(\S+(?:\s+\S+)?)/gi, "$1$2"); + s = s.replace(/Bearer\s+[A-Za-z0-9._+\/=-]+/gi, "Bearer "); + s = s.replace(/(["']?(?:authorization|gatewayToken|gateway_token|access_token|accessToken|refresh_token|refreshToken|token|x-anyrun-network-token|cookie|set-cookie)["']?\s*[:=]\s*["']?)([^"',\s}]+)/gi, "$1"); + s = s.replace(/(x-anyrun-network-token\s*[=:]\s*)(\S+)/gi, "$1"); + return s; +} + +__webpack_require__.d(__webpack_exports__, { + Re: () => (assertAllowedCredentialUrl), + fp: () => (redactSecrets) +}); + + +}, +"./package.json"(module) { +module.exports = {"rE":"0.9.0"} + +}, + +}); +// The module cache +var __webpack_module_cache__ = {}; + +// The require function +function __webpack_require__(moduleId) { + +// Check if module is in cache +var cachedModule = __webpack_module_cache__[moduleId]; +if (cachedModule !== undefined) { +return cachedModule.exports; +} +// Create a new module (and put it into the cache) +var module = (__webpack_module_cache__[moduleId] = { +exports: {} +}); +// Execute the module function +__webpack_modules__[moduleId](module, module.exports, __webpack_require__); + +// Return the exports of the module +return module.exports; + +} + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/ensure_chunk +(() => { +// The chunk loading function for additional chunks +// Since all referenced chunks are already included +// in this file, this function is empty here. +__webpack_require__.e = () => (Promise.resolve()) +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); +var __webpack_exports__ = {}; +/* import */ var node_worker_threads__rspack_import_0 = __webpack_require__("node:worker_threads"); +/* import */ var react__rspack_import_1 = __webpack_require__("./node_modules/react/react.react-server.js"); +/* import */ var _agent_bundle_runtime_flight_server__rspack_import_40 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/flight/server.js"); +/* import */ var _agent_bundle_runtime__rspack_import_38 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/49.js"); +/* import */ var _agent_bundle_runtime__rspack_import_39 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var node_url__rspack_import_2 = __webpack_require__("node:url"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_approvals_list_tsx__rspack_import_3 = __webpack_require__("./src/cli/approvals/list.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_approvals_respond_tsx__rspack_import_4 = __webpack_require__("./src/cli/approvals/respond.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_bots_create_tsx__rspack_import_5 = __webpack_require__("./src/cli/bots/create.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_bots_delete_tsx__rspack_import_6 = __webpack_require__("./src/cli/bots/delete.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_bots_get_tsx__rspack_import_7 = __webpack_require__("./src/cli/bots/get.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_bots_list_tsx__rspack_import_8 = __webpack_require__("./src/cli/bots/list.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_bots_update_tsx__rspack_import_9 = __webpack_require__("./src/cli/bots/update.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_respond_tsx__rspack_import_10 = __webpack_require__("./src/cli/codex/bridge/respond.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_run_tsx__rspack_import_11 = __webpack_require__("./src/cli/codex/bridge/run.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_start_tsx__rspack_import_12 = __webpack_require__("./src/cli/codex/bridge/start.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_status_tsx__rspack_import_13 = __webpack_require__("./src/cli/codex/bridge/status.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_stop_tsx__rspack_import_14 = __webpack_require__("./src/cli/codex/bridge/stop.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_desktop_shim_tsx__rspack_import_15 = __webpack_require__("./src/cli/codex/desktop-shim.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_list_threads_tsx__rspack_import_16 = __webpack_require__("./src/cli/codex/list-threads.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_queue_tsx__rspack_import_17 = __webpack_require__("./src/cli/codex/queue.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_send_tsx__rspack_import_18 = __webpack_require__("./src/cli/codex/send.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_status_tsx__rspack_import_19 = __webpack_require__("./src/cli/codex/status.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_wait_tsx__rspack_import_20 = __webpack_require__("./src/cli/codex/wait.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_codex_watch_tsx__rspack_import_21 = __webpack_require__("./src/cli/codex/watch.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_doctor_tsx__rspack_import_22 = __webpack_require__("./src/cli/doctor.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_add_tsx__rspack_import_23 = __webpack_require__("./src/cli/groups/add.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_create_tsx__rspack_import_24 = __webpack_require__("./src/cli/groups/create.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_delete_tsx__rspack_import_25 = __webpack_require__("./src/cli/groups/delete.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_get_tsx__rspack_import_26 = __webpack_require__("./src/cli/groups/get.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_list_tsx__rspack_import_27 = __webpack_require__("./src/cli/groups/list.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_members_tsx__rspack_import_28 = __webpack_require__("./src/cli/groups/members.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_remove_tsx__rspack_import_29 = __webpack_require__("./src/cli/groups/remove.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_set_tsx__rspack_import_30 = __webpack_require__("./src/cli/groups/set.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_groups_update_tsx__rspack_import_31 = __webpack_require__("./src/cli/groups/update.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_history_tsx__rspack_import_32 = __webpack_require__("./src/cli/history.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_send_tsx__rspack_import_33 = __webpack_require__("./src/cli/send.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_skills_add_tsx__rspack_import_34 = __webpack_require__("./src/cli/skills/add.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_skills_list_tsx__rspack_import_35 = __webpack_require__("./src/cli/skills/list.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_skills_remove_tsx__rspack_import_36 = __webpack_require__("./src/cli/skills/remove.tsx"); +/* import */ var _tmp_gbot_agent_bundle_native_src_cli_thread_tsx__rspack_import_37 = __webpack_require__("./src/cli/thread.tsx"); + + + + + + +const route0 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_approvals_list_tsx__rspack_import_3, 'default'), _tmp_gbot_agent_bundle_native_src_cli_approvals_list_tsx__rspack_import_3); + +const route1 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_approvals_respond_tsx__rspack_import_4, 'default'), _tmp_gbot_agent_bundle_native_src_cli_approvals_respond_tsx__rspack_import_4); + +const route2 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_bots_create_tsx__rspack_import_5, 'default'), _tmp_gbot_agent_bundle_native_src_cli_bots_create_tsx__rspack_import_5); + +const route3 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_bots_delete_tsx__rspack_import_6, 'default'), _tmp_gbot_agent_bundle_native_src_cli_bots_delete_tsx__rspack_import_6); + +const route4 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_bots_get_tsx__rspack_import_7, 'default'), _tmp_gbot_agent_bundle_native_src_cli_bots_get_tsx__rspack_import_7); + +const route5 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_bots_list_tsx__rspack_import_8, 'default'), _tmp_gbot_agent_bundle_native_src_cli_bots_list_tsx__rspack_import_8); + +const route6 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_bots_update_tsx__rspack_import_9, 'default'), _tmp_gbot_agent_bundle_native_src_cli_bots_update_tsx__rspack_import_9); + +const route7 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_bridge_respond_tsx__rspack_import_10, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_respond_tsx__rspack_import_10); + +const route8 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_bridge_run_tsx__rspack_import_11, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_run_tsx__rspack_import_11); + +const route9 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_bridge_start_tsx__rspack_import_12, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_start_tsx__rspack_import_12); + +const route10 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_bridge_status_tsx__rspack_import_13, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_status_tsx__rspack_import_13); + +const route11 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_bridge_stop_tsx__rspack_import_14, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_bridge_stop_tsx__rspack_import_14); + +const route12 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_desktop_shim_tsx__rspack_import_15, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_desktop_shim_tsx__rspack_import_15); + +const route13 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_list_threads_tsx__rspack_import_16, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_list_threads_tsx__rspack_import_16); + +const route14 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_queue_tsx__rspack_import_17, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_queue_tsx__rspack_import_17); + +const route15 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_send_tsx__rspack_import_18, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_send_tsx__rspack_import_18); + +const route16 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_status_tsx__rspack_import_19, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_status_tsx__rspack_import_19); + +const route17 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_wait_tsx__rspack_import_20, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_wait_tsx__rspack_import_20); + +const route18 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_codex_watch_tsx__rspack_import_21, 'default'), _tmp_gbot_agent_bundle_native_src_cli_codex_watch_tsx__rspack_import_21); + +const route19 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_doctor_tsx__rspack_import_22, 'default'), _tmp_gbot_agent_bundle_native_src_cli_doctor_tsx__rspack_import_22); + +const route20 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_add_tsx__rspack_import_23, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_add_tsx__rspack_import_23); + +const route21 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_create_tsx__rspack_import_24, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_create_tsx__rspack_import_24); + +const route22 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_delete_tsx__rspack_import_25, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_delete_tsx__rspack_import_25); + +const route23 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_get_tsx__rspack_import_26, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_get_tsx__rspack_import_26); + +const route24 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_list_tsx__rspack_import_27, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_list_tsx__rspack_import_27); + +const route25 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_members_tsx__rspack_import_28, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_members_tsx__rspack_import_28); + +const route26 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_remove_tsx__rspack_import_29, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_remove_tsx__rspack_import_29); + +const route27 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_set_tsx__rspack_import_30, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_set_tsx__rspack_import_30); + +const route28 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_groups_update_tsx__rspack_import_31, 'default'), _tmp_gbot_agent_bundle_native_src_cli_groups_update_tsx__rspack_import_31); + +const route29 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_history_tsx__rspack_import_32, 'default'), _tmp_gbot_agent_bundle_native_src_cli_history_tsx__rspack_import_32); + +const route30 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_send_tsx__rspack_import_33, 'default'), _tmp_gbot_agent_bundle_native_src_cli_send_tsx__rspack_import_33); + +const route31 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_skills_add_tsx__rspack_import_34, 'default'), _tmp_gbot_agent_bundle_native_src_cli_skills_add_tsx__rspack_import_34); + +const route32 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_skills_list_tsx__rspack_import_35, 'default'), _tmp_gbot_agent_bundle_native_src_cli_skills_list_tsx__rspack_import_35); + +const route33 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_skills_remove_tsx__rspack_import_36, 'default'), _tmp_gbot_agent_bundle_native_src_cli_skills_remove_tsx__rspack_import_36); + +const route34 = Object.assign({}, Reflect.get(_tmp_gbot_agent_bundle_native_src_cli_thread_tsx__rspack_import_37, 'default'), _tmp_gbot_agent_bundle_native_src_cli_thread_tsx__rspack_import_37); +const pluginRoot = (0,_agent_bundle_runtime__rspack_import_38/* .resolvePluginRoot */.E7)({ + fallback: (0,node_url__rspack_import_2.fileURLToPath)(new URL('..', import.meta.url)), + stateAnchor: 'user-data' +}); +// Generated routes contain only intrinsic Agent protocol elements, so no client references exist. +globalThis.__rspack_rsc_manifest__ ??= Object.freeze({ + clientManifest: Object.freeze({}) +}); +if (node_worker_threads__rspack_import_0.parentPort === null) throw new Error('Generated render worker requires a parent port.'); +// Machine output owns the parent stdout; anything a route logs goes to stderr. +process.stdout.write = process.stderr.write.bind(process.stderr); +const processLifetime = { + hits: 0, + instanceId: crypto.randomUUID(), + pid: process.pid +}; +const composeLayouts = (route, props)=>/*#__PURE__*/ (0,react__rspack_import_1.createElement)(route.module.default, props); +const routes = Object.freeze({ + "cli:approvals/list": Object.freeze({ + id: "cli:approvals/list", + kind: "cli", + name: "approvals list", + module: route0 + }), + "cli:approvals/respond": Object.freeze({ + id: "cli:approvals/respond", + kind: "cli", + name: "approvals respond", + module: route1 + }), + "cli:bots/create": Object.freeze({ + id: "cli:bots/create", + kind: "cli", + name: "bots create", + module: route2 + }), + "cli:bots/delete": Object.freeze({ + id: "cli:bots/delete", + kind: "cli", + name: "bots delete", + module: route3 + }), + "cli:bots/get": Object.freeze({ + id: "cli:bots/get", + kind: "cli", + name: "bots get", + module: route4 + }), + "cli:bots/list": Object.freeze({ + id: "cli:bots/list", + kind: "cli", + name: "bots list", + module: route5 + }), + "cli:bots/update": Object.freeze({ + id: "cli:bots/update", + kind: "cli", + name: "bots update", + module: route6 + }), + "cli:codex/bridge/respond": Object.freeze({ + id: "cli:codex/bridge/respond", + kind: "cli", + name: "codex bridge respond", + module: route7 + }), + "cli:codex/bridge/run": Object.freeze({ + id: "cli:codex/bridge/run", + kind: "cli", + name: "codex bridge run", + module: route8 + }), + "cli:codex/bridge/start": Object.freeze({ + id: "cli:codex/bridge/start", + kind: "cli", + name: "codex bridge start", + module: route9 + }), + "cli:codex/bridge/status": Object.freeze({ + id: "cli:codex/bridge/status", + kind: "cli", + name: "codex bridge status", + module: route10 + }), + "cli:codex/bridge/stop": Object.freeze({ + id: "cli:codex/bridge/stop", + kind: "cli", + name: "codex bridge stop", + module: route11 + }), + "cli:codex/desktop-shim": Object.freeze({ + id: "cli:codex/desktop-shim", + kind: "cli", + name: "codex desktop-shim", + module: route12 + }), + "cli:codex/list-threads": Object.freeze({ + id: "cli:codex/list-threads", + kind: "cli", + name: "codex list-threads", + module: route13 + }), + "cli:codex/queue": Object.freeze({ + id: "cli:codex/queue", + kind: "cli", + name: "codex queue", + module: route14 + }), + "cli:codex/send": Object.freeze({ + id: "cli:codex/send", + kind: "cli", + name: "codex send", + module: route15 + }), + "cli:codex/status": Object.freeze({ + id: "cli:codex/status", + kind: "cli", + name: "codex status", + module: route16 + }), + "cli:codex/wait": Object.freeze({ + id: "cli:codex/wait", + kind: "cli", + name: "codex wait", + module: route17 + }), + "cli:codex/watch": Object.freeze({ + id: "cli:codex/watch", + kind: "cli", + name: "codex watch", + module: route18 + }), + "cli:doctor": Object.freeze({ + id: "cli:doctor", + kind: "cli", + name: "doctor", + module: route19 + }), + "cli:groups/add": Object.freeze({ + id: "cli:groups/add", + kind: "cli", + name: "groups add", + module: route20 + }), + "cli:groups/create": Object.freeze({ + id: "cli:groups/create", + kind: "cli", + name: "groups create", + module: route21 + }), + "cli:groups/delete": Object.freeze({ + id: "cli:groups/delete", + kind: "cli", + name: "groups delete", + module: route22 + }), + "cli:groups/get": Object.freeze({ + id: "cli:groups/get", + kind: "cli", + name: "groups get", + module: route23 + }), + "cli:groups/list": Object.freeze({ + id: "cli:groups/list", + kind: "cli", + name: "groups list", + module: route24 + }), + "cli:groups/members": Object.freeze({ + id: "cli:groups/members", + kind: "cli", + name: "groups members", + module: route25 + }), + "cli:groups/remove": Object.freeze({ + id: "cli:groups/remove", + kind: "cli", + name: "groups remove", + module: route26 + }), + "cli:groups/set": Object.freeze({ + id: "cli:groups/set", + kind: "cli", + name: "groups set", + module: route27 + }), + "cli:groups/update": Object.freeze({ + id: "cli:groups/update", + kind: "cli", + name: "groups update", + module: route28 + }), + "cli:history": Object.freeze({ + id: "cli:history", + kind: "cli", + name: "history", + module: route29 + }), + "cli:send": Object.freeze({ + id: "cli:send", + kind: "cli", + name: "send", + module: route30 + }), + "cli:skills/add": Object.freeze({ + id: "cli:skills/add", + kind: "cli", + name: "skills add", + module: route31 + }), + "cli:skills/list": Object.freeze({ + id: "cli:skills/list", + kind: "cli", + name: "skills list", + module: route32 + }), + "cli:skills/remove": Object.freeze({ + id: "cli:skills/remove", + kind: "cli", + name: "skills remove", + module: route33 + }), + "cli:thread": Object.freeze({ + id: "cli:thread", + kind: "cli", + name: "thread", + module: route34 + }) +}); +const requests = new Map(); +const render = async (message)=>{ + const route = routes[message.routeId]; + if (route === undefined || typeof route.module.default !== 'function') throw new TypeError('Generated rendered route must default-export a function component.'); + const observedRoute = message.observe !== true ? route : { + ...route, + module: { + ...route.module, + default: async (props)=>{ + const handlerStartedAt = performance.now(); + try { + return await route.module.default(props); + } finally{ + node_worker_threads__rspack_import_0.parentPort.postMessage({ + durationMs: performance.now() - handlerStartedAt, + id: message.id, + type: 'observed-handler' + }); + } + } + } + }; + const controller = new AbortController(); + requests.set(message.id, controller); + processLifetime.hits += 1; + const processHit = { + hits: processLifetime.hits, + instanceId: processLifetime.instanceId, + pid: processLifetime.pid + }; + try { + const cwd = process.cwd(); + await (0,_agent_bundle_runtime__rspack_import_39/* .runAgentRequest */.iC)({ + capabilities: { + command: (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)(), + filesystem: (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)(), + network: (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)(), + projectRoot: (0,_agent_bundle_runtime__rspack_import_39/* .available */.qC)({ + root: cwd + }, 'derived') + }, + host: (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)('unsupported-surface'), + invocation: message.request, + lineage: (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)('unsupported-surface'), + plugin: pluginRoot.identity, + progress: { + report: async (update)=>{ + node_worker_threads__rspack_import_0.parentPort.postMessage({ + id: message.id, + type: 'progress', + update + }); + } + }, + process: processHit, + signal: controller.signal, + terminal: message.terminal === undefined ? (0,_agent_bundle_runtime__rspack_import_39/* .unavailable */.hU)('not-provided') : (0,_agent_bundle_runtime__rspack_import_39/* .available */.qC)(message.terminal, 'native'), + workspace: (0,_agent_bundle_runtime__rspack_import_39/* .available */.qC)({ + root: cwd + }, 'derived') + }, async ()=>{ + if (message.observe === true) node_worker_threads__rspack_import_0.parentPort.postMessage({ + id: message.id, + type: 'observed-render-start' + }); + const renderStartedAt = performance.now(); + const flight = (0,_agent_bundle_runtime_flight_server__rspack_import_40/* .renderAgentFlight */.y)(composeLayouts(observedRoute, { + ...message.props, + signal: controller.signal + }, controller.signal), { + onError: ()=>undefined, + signal: controller.signal + }); + const reader = flight.getReader(); + while(true){ + const next = await reader.read(); + if (next.done) break; + const bytes = next.value; + node_worker_threads__rspack_import_0.parentPort.postMessage({ + bytes, + id: message.id, + type: 'chunk' + }, [ + bytes.buffer + ]); + } + if (message.observe === true) node_worker_threads__rspack_import_0.parentPort.postMessage({ + durationMs: performance.now() - renderStartedAt, + id: message.id, + type: 'observed-render-finish' + }); + }); + node_worker_threads__rspack_import_0.parentPort.postMessage({ + id: message.id, + type: 'end' + }); + } catch (error) { + node_worker_threads__rspack_import_0.parentPort.postMessage({ + id: message.id, + message: error instanceof Error ? error.message : String(error), + type: 'error' + }); + } finally{ + requests.delete(message.id); + } +}; +node_worker_threads__rspack_import_0.parentPort.on('message', (message)=>{ + if (message.type === 'cancel') { + requests.get(message.id)?.abort(); + return; + } + if (message.type === 'render') void render(message); +}); + diff --git a/artifact/bin/gbot.mjs b/artifact/bin/gbot.mjs new file mode 100755 index 0000000..f86712b --- /dev/null +++ b/artifact/bin/gbot.mjs @@ -0,0 +1,91619 @@ +#!/usr/bin/env node +import * as __rspack_external_node_async_hooks_4d8b1b4a from "node:async_hooks"; +import * as __rspack_external_node_buffer_4f2f74e0 from "node:buffer"; +import * as __rspack_external_node_child_process_cd435d64 from "node:child_process"; +import * as __rspack_external_node_crypto_2e7c4b46 from "node:crypto"; +import * as __rspack_external_node_fs_1b05aee1 from "node:fs"; +import * as __rspack_external_node_fs_promises_3b710708 from "node:fs/promises"; +import * as __rspack_external_node_net_5ed819e1 from "node:net"; +import * as __rspack_external_node_os_4f3c9d58 from "node:os"; +import * as __rspack_external_node_path_806ed179 from "node:path"; +import * as __rspack_external_node_readline_d8f53bef from "node:readline"; +import * as __rspack_external_node_string_decoder_69b9bd04 from "node:string_decoder"; +import * as __rspack_external_node_url_3991086a from "node:url"; +import * as __rspack_external_node_worker_threads_28ca7740 from "node:worker_threads"; +import { createRequire as __rspack_createRequire } from "node:module"; +const __rspack_createRequire_require = __rspack_createRequire(import.meta.url); +var __webpack_modules__ = ({ +"./node_modules/react-dom/cjs/react-dom.development.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-dom.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function noop() {} + function testStringCoercion(value) { + return "" + value; + } + function createPortal$1(children, containerInfo, implementation) { + var key = + 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; + if (null == key) key = null; + else if (key === REACT_OPTIMISTIC_KEY) key = REACT_OPTIMISTIC_KEY; + else { + try { + testStringCoercion(key); + var JSCompiler_inline_result = !1; + } catch (e) { + JSCompiler_inline_result = !0; + } + JSCompiler_inline_result && + (console.error( + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + ("function" === typeof Symbol && + Symbol.toStringTag && + key[Symbol.toStringTag]) || + key.constructor.name || + "Object" + ), + testStringCoercion(key)); + key = "" + key; + } + return { + $$typeof: REACT_PORTAL_TYPE, + key: key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; + } + function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; + } + function getValueDescriptorExpectingObjectForWarning(thing) { + return null === thing + ? "`null`" + : void 0 === thing + ? "`undefined`" + : "" === thing + ? "an empty string" + : 'something with type "' + typeof thing + '"'; + } + function getValueDescriptorExpectingEnumForWarning(thing) { + return null === thing + ? "`null`" + : void 0 === thing + ? "`undefined`" + : "" === thing + ? "an empty string" + : "string" === typeof thing + ? JSON.stringify(thing) + : "number" === typeof thing + ? "`" + thing + "`" + : 'something with type "' + typeof thing + '"'; + } + function resolveDispatcher() { + var dispatcher = ReactSharedInternals.H; + null === dispatcher && + console.error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return dispatcher; + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && + "function" === + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var React = __webpack_require__("./node_modules/react/index.js"), + Internals = { + d: { + f: noop, + r: function () { + throw Error( + "Invalid form element. requestFormReset must be passed a form that was rendered by React." + ); + }, + D: noop, + C: noop, + L: noop, + m: noop, + X: noop, + S: noop, + M: noop + }, + p: 0, + findDOMNode: null + }, + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_RECOVERABLE_TYPE = Symbol.for("react.recoverable"), + REACT_OPTIMISTIC_KEY = Symbol.for("react.optimistic_key"), + ReactSharedInternals = + React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + ("function" === typeof Map && + null != Map.prototype && + "function" === typeof Map.prototype.forEach && + "function" === typeof Set && + null != Set.prototype && + "function" === typeof Set.prototype.clear && + "function" === typeof Set.prototype.forEach) || + console.error( + "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills" + ); + exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + Internals; + exports.browser = function (reason) { + return { $$typeof: REACT_RECOVERABLE_TYPE, _reason: reason }; + }; + exports.createPortal = function (children, container) { + var key = + 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; + if ( + !container || + (1 !== container.nodeType && + 9 !== container.nodeType && + 11 !== container.nodeType) + ) + throw Error("Target container is not a DOM element."); + return createPortal$1(children, container, null, key); + }; + exports.flushSync = function (fn) { + var previousTransition = ReactSharedInternals.T, + previousUpdatePriority = Internals.p; + try { + if (((ReactSharedInternals.T = null), (Internals.p = 2), fn)) + return fn(); + } finally { + (ReactSharedInternals.T = previousTransition), + (Internals.p = previousUpdatePriority), + Internals.d.f() && + console.error( + "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task." + ); + } + }; + exports.preconnect = function (href, options) { + "string" === typeof href && href + ? null != options && "object" !== typeof options + ? console.error( + "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : null != options && + "string" !== typeof options.crossOrigin && + console.error( + "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.", + getValueDescriptorExpectingObjectForWarning(options.crossOrigin) + ) + : console.error( + "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + "string" === typeof href && + (options + ? ((options = options.crossOrigin), + (options = + "string" === typeof options + ? "use-credentials" === options + ? options + : "" + : void 0)) + : (options = null), + Internals.d.C(href, options)); + }; + exports.prefetchDNS = function (href) { + if ("string" !== typeof href || !href) + console.error( + "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + else if (1 < arguments.length) { + var options = arguments[1]; + "object" === typeof options && options.hasOwnProperty("crossOrigin") + ? console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : console.error( + "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", + getValueDescriptorExpectingEnumForWarning(options) + ); + } + "string" === typeof href && Internals.d.D(href); + }; + exports.preinit = function (href, options) { + "string" === typeof href && href + ? null == options || "object" !== typeof options + ? console.error( + "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.", + getValueDescriptorExpectingEnumForWarning(options) + ) + : "style" !== options.as && + "script" !== options.as && + console.error( + 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".', + getValueDescriptorExpectingEnumForWarning(options.as) + ) + : console.error( + "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", + getValueDescriptorExpectingObjectForWarning(href) + ); + if ( + "string" === typeof href && + options && + "string" === typeof options.as + ) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), + integrity = + "string" === typeof options.integrity ? options.integrity : void 0, + fetchPriority = + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0; + "style" === as + ? Internals.d.S( + href, + "string" === typeof options.precedence + ? options.precedence + : void 0, + { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority + } + ) + : "script" === as && + Internals.d.X(href, { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } + }; + exports.preinitModule = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + void 0 !== options && "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : options && + "as" in options && + "script" !== options.as && + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingEnumForWarning(options.as) + + "."); + if (encountered) + console.error( + "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s", + encountered + ); + else + switch ( + ((encountered = + options && "string" === typeof options.as ? options.as : "script"), + encountered) + ) { + case "script": + break; + default: + (encountered = + getValueDescriptorExpectingEnumForWarning(encountered)), + console.error( + 'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)', + encountered, + href + ); + } + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) + (encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + )), + Internals.d.M(href, { + crossOrigin: encountered, + integrity: + "string" === typeof options.integrity + ? options.integrity + : void 0, + nonce: + "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } else null == options && Internals.d.M(href); + }; + exports.preload = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + null == options || "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : ("string" === typeof options.as && options.as) || + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingObjectForWarning(options.as) + + "."); + encountered && + console.error( + 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + if ( + "string" === typeof href && + "object" === typeof options && + null !== options && + "string" === typeof options.as + ) { + encountered = options.as; + var crossOrigin = getCrossOriginStringAs( + encountered, + options.crossOrigin + ); + Internals.d.L(href, encountered, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0, + referrerPolicy: + "string" === typeof options.referrerPolicy + ? options.referrerPolicy + : void 0, + imageSrcSet: + "string" === typeof options.imageSrcSet + ? options.imageSrcSet + : void 0, + imageSizes: + "string" === typeof options.imageSizes + ? options.imageSizes + : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } + }; + exports.preloadModule = function (href, options) { + var encountered = ""; + ("string" === typeof href && href) || + (encountered += + " The `href` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(href) + + "."); + void 0 !== options && "object" !== typeof options + ? (encountered += + " The `options` argument encountered was " + + getValueDescriptorExpectingObjectForWarning(options) + + ".") + : options && + "as" in options && + "string" !== typeof options.as && + (encountered += + " The `as` option encountered was " + + getValueDescriptorExpectingObjectForWarning(options.as) + + "."); + encountered && + console.error( + 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `` tag.%s', + encountered + ); + "string" === typeof href && + (options + ? ((encountered = getCrossOriginStringAs( + options.as, + options.crossOrigin + )), + Internals.d.m(href, { + as: + "string" === typeof options.as && "script" !== options.as + ? options.as + : void 0, + crossOrigin: encountered, + integrity: + "string" === typeof options.integrity + ? options.integrity + : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + })) + : Internals.d.m(href)); + }; + exports.requestFormReset = function (form) { + Internals.d.r(form); + }; + exports.unstable_batchedUpdates = function (fn, a) { + return fn(a); + }; + exports.useFormState = function (action, initialState, permalink) { + return resolveDispatcher().useFormState(action, initialState, permalink); + }; + exports.useFormStatus = function () { + return resolveDispatcher().useHostTransitionStatus(); + }; + exports.version = "19.3.0"; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && + "function" === + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + + +}, +"./node_modules/react-dom/cjs/react-dom.production.js"(__unused_rspack_module, exports, __webpack_require__) { +/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var React = __webpack_require__("./node_modules/react/index.js"); +function formatProdErrorMessage(code) { + var url = "https://react.dev/errors/" + code; + if (1 < arguments.length) { + url += "?args[]=" + encodeURIComponent(arguments[1]); + for (var i = 2; i < arguments.length; i++) + url += "&args[]=" + encodeURIComponent(arguments[i]); + } + return ( + "Minified React error #" + + code + + "; visit " + + url + + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings." + ); +} +function noop() {} +var Internals = { + d: { + f: noop, + r: function () { + throw Error(formatProdErrorMessage(522)); + }, + D: noop, + C: noop, + L: noop, + m: noop, + X: noop, + S: noop, + M: noop + }, + p: 0, + findDOMNode: null + }, + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_RECOVERABLE_TYPE = Symbol.for("react.recoverable"), + REACT_OPTIMISTIC_KEY = Symbol.for("react.optimistic_key"); +function createPortal$1(children, containerInfo, implementation) { + var key = + 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; + return { + $$typeof: REACT_PORTAL_TYPE, + key: + null == key + ? null + : key === REACT_OPTIMISTIC_KEY + ? REACT_OPTIMISTIC_KEY + : "" + key, + children: children, + containerInfo: containerInfo, + implementation: implementation + }; +} +var ReactSharedInternals = + React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; +function getCrossOriginStringAs(as, input) { + if ("font" === as) return ""; + if ("string" === typeof input) + return "use-credentials" === input ? input : ""; +} +exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + Internals; +exports.browser = function (reason) { + return { $$typeof: REACT_RECOVERABLE_TYPE, _reason: reason }; +}; +exports.createPortal = function (children, container) { + var key = + 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; + if ( + !container || + (1 !== container.nodeType && + 9 !== container.nodeType && + 11 !== container.nodeType) + ) + throw Error(formatProdErrorMessage(299)); + return createPortal$1(children, container, null, key); +}; +exports.flushSync = function (fn) { + var previousTransition = ReactSharedInternals.T, + previousUpdatePriority = Internals.p; + try { + if (((ReactSharedInternals.T = null), (Internals.p = 2), fn)) return fn(); + } finally { + (ReactSharedInternals.T = previousTransition), + (Internals.p = previousUpdatePriority), + Internals.d.f(); + } +}; +exports.preconnect = function (href, options) { + "string" === typeof href && + (options + ? ((options = options.crossOrigin), + (options = + "string" === typeof options + ? "use-credentials" === options + ? options + : "" + : void 0)) + : (options = null), + Internals.d.C(href, options)); +}; +exports.prefetchDNS = function (href) { + "string" === typeof href && Internals.d.D(href); +}; +exports.preinit = function (href, options) { + if ("string" === typeof href && options && "string" === typeof options.as) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), + integrity = + "string" === typeof options.integrity ? options.integrity : void 0, + fetchPriority = + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0; + "style" === as + ? Internals.d.S( + href, + "string" === typeof options.precedence ? options.precedence : void 0, + { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority + } + ) + : "script" === as && + Internals.d.X(href, { + crossOrigin: crossOrigin, + integrity: integrity, + fetchPriority: fetchPriority, + nonce: "string" === typeof options.nonce ? options.nonce : void 0 + }); + } +}; +exports.preinitModule = function (href, options) { + if ("string" === typeof href) + if ("object" === typeof options && null !== options) { + if (null == options.as || "script" === options.as) { + var crossOrigin = getCrossOriginStringAs( + options.as, + options.crossOrigin + ); + Internals.d.M(href, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } + } else null == options && Internals.d.M(href); +}; +exports.preload = function (href, options) { + if ( + "string" === typeof href && + "object" === typeof options && + null !== options && + "string" === typeof options.as + ) { + var as = options.as, + crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); + Internals.d.L(href, as, { + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + type: "string" === typeof options.type ? options.type : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0, + referrerPolicy: + "string" === typeof options.referrerPolicy + ? options.referrerPolicy + : void 0, + imageSrcSet: + "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, + imageSizes: + "string" === typeof options.imageSizes ? options.imageSizes : void 0, + media: "string" === typeof options.media ? options.media : void 0 + }); + } +}; +exports.preloadModule = function (href, options) { + if ("string" === typeof href) + if (options) { + var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); + Internals.d.m(href, { + as: + "string" === typeof options.as && "script" !== options.as + ? options.as + : void 0, + crossOrigin: crossOrigin, + integrity: + "string" === typeof options.integrity ? options.integrity : void 0, + nonce: "string" === typeof options.nonce ? options.nonce : void 0, + fetchPriority: + "string" === typeof options.fetchPriority + ? options.fetchPriority + : void 0 + }); + } else Internals.d.m(href); +}; +exports.requestFormReset = function (form) { + Internals.d.r(form); +}; +exports.unstable_batchedUpdates = function (fn, a) { + return fn(a); +}; +exports.useFormState = function (action, initialState, permalink) { + return ReactSharedInternals.H.useFormState(action, initialState, permalink); +}; +exports.useFormStatus = function () { + return ReactSharedInternals.H.useHostTransitionStatus(); +}; +exports.version = "19.3.0"; + + +}, +"./node_modules/react-dom/index.js"(module, __unused_rspack_exports, __webpack_require__) { + + +function checkDCE() { + /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ + if ( + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' + ) { + return; + } + if (process.env.NODE_ENV !== 'production') { + // This branch is unreachable because this function is only called + // in production, but the condition is true only in development. + // Therefore if the branch is still here, dead code elimination wasn't + // properly applied. + // Don't change the message. React DevTools relies on it. Also make sure + // this message doesn't occur elsewhere in this function, or it will cause + // a false positive. + throw new Error('^_^'); + } + try { + // Verify that the code above has been dead code eliminated (DCE'd). + __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); + } catch (err) { + // DevTools shouldn't crash React, no matter what. + // We should still report in case we break this code. + console.error(err); + } +} + +if (process.env.NODE_ENV === 'production') { + // DCE check should happen before ReactDOM bundle executes so that + // DevTools can report bad minification during injection. + checkDCE(); + module.exports = __webpack_require__("./node_modules/react-dom/cjs/react-dom.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react-dom/cjs/react-dom.development.js"); +} + + +}, +"./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; +/** + * @license React + * react-server-dom-rspack-client.node.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function checkEvalAvailabilityOnceDev() { + if (!hasConfirmedEval) { + hasConfirmedEval = !0; + try { + (0, eval)("null"); + } catch ($jscomp$unused$catch) { + console.error( + "eval() is not supported in this environment. This can happen if you started the Node.js process with --disallow-code-generation-from-strings, or if `eval` was patched by other means. React requires eval() in development mode for various debugging features like reconstructing callstacks from a different environment.\nReact will never use eval() in production mode" + ); + } + } + } + function resolveClientReference(bundlerConfig, metadata) { + if (bundlerConfig) { + var moduleExports = bundlerConfig[metadata[0]]; + if ((bundlerConfig = moduleExports && moduleExports[metadata[2]])) + moduleExports = bundlerConfig.name; + else { + bundlerConfig = moduleExports && moduleExports["*"]; + if (!bundlerConfig) + throw Error( + 'Could not find the module "' + + metadata[0] + + '" in the React Server Consumer Manifest. This is probably a bug in the React Server Components bundler.' + ); + moduleExports = metadata[2]; + } + return 4 === metadata.length + ? [bundlerConfig.id, bundlerConfig.chunks, moduleExports, 1] + : [bundlerConfig.id, bundlerConfig.chunks, moduleExports]; + } + return metadata; + } + function resolveServerReference(bundlerConfig, id) { + var name = "", + resolvedModuleData = bundlerConfig[id]; + if (resolvedModuleData) name = resolvedModuleData.name; + else { + var idx = id.lastIndexOf("#"); + -1 !== idx && + ((name = id.slice(idx + 1)), + (resolvedModuleData = bundlerConfig[id.slice(0, idx)])); + if (!resolvedModuleData) + throw Error( + 'Could not find the module "' + + id + + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.' + ); + } + return resolvedModuleData.async + ? [resolvedModuleData.id, resolvedModuleData.chunks, name, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, name]; + } + function requireAsyncModule(id) { + var promise = __webpack_require__(id); + if ("function" !== typeof promise.then || "fulfilled" === promise.status) + return null; + promise.then( + function (value) { + promise.status = "fulfilled"; + promise.value = value; + }, + function (reason) { + promise.status = "rejected"; + promise.reason = reason; + } + ); + return promise; + } + function ignoreReject() {} + function preloadModule(metadata) { + for ( + var chunks = metadata[1], promises = [], i = 0; + i < chunks.length; + + ) { + var chunkId = chunks[i++]; + chunks[i++]; + var entry = chunkCache.get(chunkId); + if (void 0 === entry) { + entry = __webpack_require__.e(chunkId); + promises.push(entry); + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + entry.then(resolve, ignoreReject); + chunkCache.set(chunkId, entry); + } else null !== entry && promises.push(entry); + } + return 4 === metadata.length + ? 0 === promises.length + ? requireAsyncModule(metadata[0]) + : Promise.all(promises).then(function () { + return requireAsyncModule(metadata[0]); + }) + : 0 < promises.length + ? Promise.all(promises) + : null; + } + function requireModule(metadata) { + var moduleExports = __webpack_require__(metadata[0]); + if (4 === metadata.length && "function" === typeof moduleExports.then) + if ("fulfilled" === moduleExports.status) + moduleExports = moduleExports.value; + else throw moduleExports.reason; + if ("*" === metadata[2]) return moduleExports; + if ("" === metadata[2]) + return moduleExports.__esModule ? moduleExports.default : moduleExports; + if (hasOwnProperty.call(moduleExports, metadata[2])) + return moduleExports[metadata[2]]; + } + function prepareDestinationWithChunks( + moduleLoading, + chunks, + nonce$jscomp$0 + ) { + if (null !== moduleLoading) + for (var i = 1; i < chunks.length; i += 2) { + var nonce = nonce$jscomp$0, + JSCompiler_temp_const = ReactDOMSharedInternals.d, + JSCompiler_temp_const$jscomp$0 = JSCompiler_temp_const.X, + JSCompiler_temp_const$jscomp$1 = moduleLoading.prefix + chunks[i]; + var JSCompiler_inline_result = moduleLoading.crossOrigin; + JSCompiler_inline_result = + "string" === typeof JSCompiler_inline_result + ? "use-credentials" === JSCompiler_inline_result + ? JSCompiler_inline_result + : "" + : void 0; + JSCompiler_temp_const$jscomp$0.call( + JSCompiler_temp_const, + JSCompiler_temp_const$jscomp$1, + { + crossOrigin: JSCompiler_inline_result, + integrity: void 0, + fetchPriority: void 0, + nonce: nonce + } + ); + } + } + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) + return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + function isObjectPrototype(object) { + if (!object) return !1; + var ObjectPrototype = Object.prototype; + if (object === ObjectPrototype) return !0; + if (getPrototypeOf(object)) return !1; + object = Object.getOwnPropertyNames(object); + for (var i = 0; i < object.length; i++) + if (!(object[i] in ObjectPrototype)) return !1; + return !0; + } + function isSimpleObject(object) { + if (!isObjectPrototype(getPrototypeOf(object))) return !1; + for ( + var names = Object.getOwnPropertyNames(object), i = 0; + i < names.length; + i++ + ) { + var descriptor = Object.getOwnPropertyDescriptor(object, names[i]); + if ( + !descriptor || + (!descriptor.enumerable && + (("key" !== names[i] && "ref" !== names[i]) || + "function" !== typeof descriptor.get)) + ) + return !1; + } + return !0; + } + function objectName(object) { + object = Object.prototype.toString.call(object); + return object.slice(8, object.length - 1); + } + function describeKeyForErrorMessage(key) { + var encodedKey = JSON.stringify(key); + return '"' + key + '"' === encodedKey ? key : encodedKey; + } + function describeValueForErrorMessage(value) { + switch (typeof value) { + case "string": + return JSON.stringify( + 10 >= value.length ? value : value.slice(0, 10) + "..." + ); + case "object": + if (isArrayImpl(value)) return "[...]"; + if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG) + return "client"; + value = objectName(value); + return "Object" === value ? "{...}" : value; + case "function": + return value.$$typeof === CLIENT_REFERENCE_TAG + ? "client" + : (value = value.displayName || value.name) + ? "function " + value + : "function"; + default: + return String(value); + } + } + function describeElementType(type) { + if ("string" === typeof type) return type; + switch (type) { + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeElementType(type.render); + case REACT_MEMO_TYPE: + return describeElementType(type.type); + case REACT_LAZY_TYPE: + var payload = type._payload; + type = type._init; + try { + return describeElementType(type(payload)); + } catch (x) {} + } + return ""; + } + function describeObjectForErrorMessage(objectOrArray, expandedName) { + var objKind = objectName(objectOrArray); + if ("Object" !== objKind && "Array" !== objKind) return objKind; + var start = -1, + length = 0; + if (isArrayImpl(objectOrArray)) + if (jsxChildrenParents.has(objectOrArray)) { + var type = jsxChildrenParents.get(objectOrArray); + objKind = "<" + describeElementType(type) + ">"; + for (var i = 0; i < objectOrArray.length; i++) { + var value = objectOrArray[i]; + value = + "string" === typeof value + ? value + : "object" === typeof value && null !== value + ? "{" + describeObjectForErrorMessage(value) + "}" + : "{" + describeValueForErrorMessage(value) + "}"; + "" + i === expandedName + ? ((start = objKind.length), + (length = value.length), + (objKind += value)) + : (objKind = + 15 > value.length && 40 > objKind.length + value.length + ? objKind + value + : objKind + "{...}"); + } + objKind += ""; + } else { + objKind = "["; + for (type = 0; type < objectOrArray.length; type++) + 0 < type && (objKind += ", "), + (i = objectOrArray[type]), + (i = + "object" === typeof i && null !== i + ? describeObjectForErrorMessage(i) + : describeValueForErrorMessage(i)), + "" + type === expandedName + ? ((start = objKind.length), + (length = i.length), + (objKind += i)) + : (objKind = + 10 > i.length && 40 > objKind.length + i.length + ? objKind + i + : objKind + "..."); + objKind += "]"; + } + else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE) + objKind = "<" + describeElementType(objectOrArray.type) + "/>"; + else { + if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client"; + if (jsxPropsParents.has(objectOrArray)) { + objKind = jsxPropsParents.get(objectOrArray); + objKind = "<" + (describeElementType(objKind) || "..."); + type = Object.keys(objectOrArray); + for (i = 0; i < type.length; i++) { + objKind += " "; + value = type[i]; + objKind += describeKeyForErrorMessage(value) + "="; + var _value2 = objectOrArray[value]; + var _substr2 = + value === expandedName && + "object" === typeof _value2 && + null !== _value2 + ? describeObjectForErrorMessage(_value2) + : describeValueForErrorMessage(_value2); + "string" !== typeof _value2 && (_substr2 = "{" + _substr2 + "}"); + value === expandedName + ? ((start = objKind.length), + (length = _substr2.length), + (objKind += _substr2)) + : (objKind = + 10 > _substr2.length && 40 > objKind.length + _substr2.length + ? objKind + _substr2 + : objKind + "..."); + } + objKind += ">"; + } else { + objKind = "{"; + type = Object.keys(objectOrArray); + for (i = 0; i < type.length; i++) + 0 < i && (objKind += ", "), + (value = type[i]), + (objKind += describeKeyForErrorMessage(value) + ": "), + (_value2 = objectOrArray[value]), + (_value2 = + "object" === typeof _value2 && null !== _value2 + ? describeObjectForErrorMessage(_value2) + : describeValueForErrorMessage(_value2)), + value === expandedName + ? ((start = objKind.length), + (length = _value2.length), + (objKind += _value2)) + : (objKind = + 10 > _value2.length && 40 > objKind.length + _value2.length + ? objKind + _value2 + : objKind + "..."); + objKind += "}"; + } + } + return void 0 === expandedName + ? objKind + : -1 < start && 0 < length + ? ((objectOrArray = " ".repeat(start) + "^".repeat(length)), + "\n " + objKind + "\n " + objectOrArray) + : "\n " + objKind; + } + function serializeNumber(number) { + return Number.isFinite(number) + ? 0 === number && -Infinity === 1 / number + ? "$-0" + : number + : Infinity === number + ? "$Infinity" + : -Infinity === number + ? "$-Infinity" + : "$NaN"; + } + function processReply( + root, + formFieldPrefix, + temporaryReferences, + resolve, + reject + ) { + function serializeTypedArray(tag, typedArray) { + typedArray = new Blob([ + new Uint8Array( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength + ) + ]); + var blobId = nextPartId++; + null === formData && (formData = new FormData()); + formData.append(formFieldPrefix + blobId, typedArray); + return "$" + tag + blobId.toString(16); + } + function serializeBinaryReader(reader) { + function progress(entry) { + entry.done + ? ((entry = nextPartId++), + data.append(formFieldPrefix + entry, new Blob(buffer)), + data.append( + formFieldPrefix + streamId, + '"$o' + entry.toString(16) + '"' + ), + data.append(formFieldPrefix + streamId, "C"), + pendingParts--, + 0 === pendingParts && resolve(data)) + : (buffer.push(entry.value), + reader.read(new Uint8Array(1024)).then(progress, reject)); + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++, + buffer = []; + reader.read(new Uint8Array(1024)).then(progress, reject); + return "$r" + streamId.toString(16); + } + function serializeReader(reader) { + function progress(entry) { + if (entry.done) + data.append(formFieldPrefix + streamId, "C"), + pendingParts--, + 0 === pendingParts && resolve(data); + else + try { + var partJSON = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, partJSON); + reader.read().then(progress, reject); + } catch (x) { + reject(x); + } + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++; + reader.read().then(progress, reject); + return "$R" + streamId.toString(16); + } + function serializeReadableStream(stream) { + try { + var binaryReader = stream.getReader({ mode: "byob" }); + } catch (x) { + return serializeReader(stream.getReader()); + } + return serializeBinaryReader(binaryReader); + } + function serializeAsyncIterable(iterable, iterator) { + function progress(entry) { + if (entry.done) { + if (void 0 === entry.value) + data.append(formFieldPrefix + streamId, "C"); + else + try { + var partJSON = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, "C" + partJSON); + } catch (x) { + reject(x); + return; + } + pendingParts--; + 0 === pendingParts && resolve(data); + } else + try { + var _partJSON = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, _partJSON); + iterator.next().then(progress, reject); + } catch (x$0) { + reject(x$0); + } + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++; + iterable = iterable === iterator; + iterator.next().then(progress, reject); + return "$" + (iterable ? "x" : "X") + streamId.toString(16); + } + function resolveToJSON(key, value) { + "__proto__" === key && + console.error( + "Expected not to serialize an object with own property `__proto__`. When parsed this property will be omitted.%s", + describeObjectForErrorMessage(this, key) + ); + var originalValue = this[key]; + "object" !== typeof originalValue || + originalValue === value || + originalValue instanceof Date || + ("Object" !== objectName(originalValue) + ? console.error( + "Only plain objects can be passed to Server Functions from the Client. %s objects are not supported.%s", + objectName(originalValue), + describeObjectForErrorMessage(this, key) + ) + : console.error( + "Only plain objects can be passed to Server Functions from the Client. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.%s", + describeObjectForErrorMessage(this, key) + )); + if (null === value) return null; + if ("object" === typeof value) { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + if (void 0 !== temporaryReferences && -1 === key.indexOf(":")) { + var parentReference = writtenObjects.get(this); + if (void 0 !== parentReference) + return ( + temporaryReferences.set(parentReference + ":" + key, value), + "$T" + ); + } + if (void 0 !== temporaryReferences && modelRoot === value) + return (modelRoot = null), "$T"; + throw Error( + "React Element cannot be passed to Server Functions from the Client without a temporary reference set. Pass a TemporaryReferenceSet to the options." + + describeObjectForErrorMessage(this, key) + ); + case REACT_LAZY_TYPE: + originalValue = value._payload; + var init = value._init; + null === formData && (formData = new FormData()); + pendingParts++; + try { + parentReference = init(originalValue); + var lazyId = nextPartId++, + partJSON = serializeModel(parentReference, lazyId); + formData.append(formFieldPrefix + lazyId, partJSON); + return "$" + lazyId.toString(16); + } catch (x) { + if ( + "object" === typeof x && + null !== x && + "function" === typeof x.then + ) { + pendingParts++; + var _lazyId = nextPartId++; + parentReference = function () { + try { + var _partJSON2 = serializeModel(value, _lazyId), + _data = formData; + _data.append(formFieldPrefix + _lazyId, _partJSON2); + pendingParts--; + 0 === pendingParts && resolve(_data); + } catch (reason) { + reject(reason); + } + }; + x.then(parentReference, parentReference); + return "$" + _lazyId.toString(16); + } + reject(x); + return null; + } finally { + pendingParts--; + } + } + parentReference = writtenObjects.get(value); + if ("function" === typeof value.then) { + if (void 0 !== parentReference) + if (modelRoot === value) modelRoot = null; + else return parentReference; + null === formData && (formData = new FormData()); + pendingParts++; + var promiseId = nextPartId++; + key = "$@" + promiseId.toString(16); + writtenObjects.set(value, key); + value.then(function (partValue) { + try { + var previousReference = writtenObjects.get(partValue); + var _partJSON3 = + void 0 !== previousReference + ? JSON.stringify(previousReference) + : serializeModel(partValue, promiseId); + partValue = formData; + partValue.append(formFieldPrefix + promiseId, _partJSON3); + pendingParts--; + 0 === pendingParts && resolve(partValue); + } catch (reason) { + reject(reason); + } + }, reject); + return key; + } + if (void 0 !== parentReference) + if (modelRoot === value) modelRoot = null; + else return parentReference; + else + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference && + ((parentReference = parentReference + ":" + key), + writtenObjects.set(value, parentReference), + void 0 !== temporaryReferences && + temporaryReferences.set(parentReference, value))); + if (isArrayImpl(value)) return value; + if (value instanceof FormData) { + null === formData && (formData = new FormData()); + var _data3 = formData; + key = nextPartId++; + var prefix = formFieldPrefix + "_" + key + "_"; + value.forEach(function (originalValue, originalKey) { + _data3.append(prefix + originalKey, originalValue); + }); + return "$K" + key.toString(16); + } + if (value instanceof Map) + return ( + (key = nextPartId++), + (parentReference = serializeModel(Array.from(value), key)), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$Q" + key.toString(16) + ); + if (value instanceof Set) + return ( + (key = nextPartId++), + (parentReference = serializeModel(Array.from(value), key)), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$W" + key.toString(16) + ); + if (value instanceof ArrayBuffer) + return ( + (key = new Blob([value])), + (parentReference = nextPartId++), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + parentReference, key), + "$A" + parentReference.toString(16) + ); + if (value instanceof Int8Array) + return serializeTypedArray("O", value); + if (value instanceof Uint8Array) + return serializeTypedArray("o", value); + if (value instanceof Uint8ClampedArray) + return serializeTypedArray("U", value); + if (value instanceof Int16Array) + return serializeTypedArray("S", value); + if (value instanceof Uint16Array) + return serializeTypedArray("s", value); + if (value instanceof Int32Array) + return serializeTypedArray("L", value); + if (value instanceof Uint32Array) + return serializeTypedArray("l", value); + if (value instanceof Float32Array) + return serializeTypedArray("G", value); + if (value instanceof Float64Array) + return serializeTypedArray("g", value); + if (value instanceof BigInt64Array) + return serializeTypedArray("M", value); + if (value instanceof BigUint64Array) + return serializeTypedArray("m", value); + if (value instanceof DataView) return serializeTypedArray("V", value); + if ("function" === typeof Blob && value instanceof Blob) + return ( + null === formData && (formData = new FormData()), + (key = nextPartId++), + formData.append(formFieldPrefix + key, value), + "$B" + key.toString(16) + ); + if ((parentReference = getIteratorFn(value))) + return ( + (parentReference = parentReference.call(value)), + parentReference === value + ? ((key = nextPartId++), + (parentReference = serializeModel( + Array.from(parentReference), + key + )), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$i" + key.toString(16)) + : Array.from(parentReference) + ); + if ( + "function" === typeof ReadableStream && + value instanceof ReadableStream + ) + return serializeReadableStream(value); + parentReference = value[ASYNC_ITERATOR]; + if ("function" === typeof parentReference) + return serializeAsyncIterable(value, parentReference.call(value)); + parentReference = getPrototypeOf(value); + if ( + parentReference !== ObjectPrototype$1 && + (null === parentReference || + null !== getPrototypeOf(parentReference)) + ) { + if (void 0 === temporaryReferences) + throw Error( + "Only plain objects, and a few built-ins, can be passed to Server Functions. Classes or null prototypes are not supported." + + describeObjectForErrorMessage(this, key) + ); + return "$T"; + } + value.$$typeof === REACT_CONTEXT_TYPE + ? console.error( + "React Context Providers cannot be passed to Server Functions from the Client.%s", + describeObjectForErrorMessage(this, key) + ) + : "Object" !== objectName(value) + ? console.error( + "Only plain objects can be passed to Server Functions from the Client. %s objects are not supported.%s", + objectName(value), + describeObjectForErrorMessage(this, key) + ) + : isSimpleObject(value) + ? Object.getOwnPropertySymbols && + ((parentReference = Object.getOwnPropertySymbols(value)), + 0 < parentReference.length && + console.error( + "Only plain objects can be passed to Server Functions from the Client. Objects with symbol properties like %s are not supported.%s", + parentReference[0].description, + describeObjectForErrorMessage(this, key) + )) + : console.error( + "Only plain objects can be passed to Server Functions from the Client. Classes or other objects with methods are not supported.%s", + describeObjectForErrorMessage(this, key) + ); + return value; + } + if ("string" === typeof value) { + if ("Z" === value[value.length - 1] && this[key] instanceof Date) + return "$D" + value; + key = "$" === value[0] ? "$" + value : value; + return key; + } + if ("boolean" === typeof value) return value; + if ("number" === typeof value) return serializeNumber(value); + if ("undefined" === typeof value) return "$undefined"; + if ("function" === typeof value) { + parentReference = knownServerReferences.get(value); + if (void 0 !== parentReference) { + key = writtenObjects.get(value); + if (void 0 !== key) return key; + key = JSON.stringify( + { id: parentReference.id, bound: parentReference.bound }, + resolveToJSON + ); + null === formData && (formData = new FormData()); + parentReference = nextPartId++; + formData.set(formFieldPrefix + parentReference, key); + key = "$h" + parentReference.toString(16); + writtenObjects.set(value, key); + return key; + } + if ( + void 0 !== temporaryReferences && + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference) + ) + return ( + temporaryReferences.set(parentReference + ":" + key, value), "$T" + ); + throw Error( + "Client Functions cannot be passed directly to Server Functions. Only Functions passed from the Server can be passed back again." + ); + } + if ("symbol" === typeof value) { + if ( + void 0 !== temporaryReferences && + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference) + ) + return ( + temporaryReferences.set(parentReference + ":" + key, value), "$T" + ); + throw Error( + "Symbols cannot be passed to a Server Function without a temporary reference set. Pass a TemporaryReferenceSet to the options." + + describeObjectForErrorMessage(this, key) + ); + } + if ("bigint" === typeof value) return "$n" + value.toString(10); + throw Error( + "Type " + + typeof value + + " is not supported as an argument to a Server Function." + ); + } + function serializeModel(model, id) { + "object" === typeof model && + null !== model && + ((id = "$" + id.toString(16)), + writtenObjects.set(model, id), + void 0 !== temporaryReferences && temporaryReferences.set(id, model)); + modelRoot = model; + return JSON.stringify(model, resolveToJSON); + } + var nextPartId = 1, + pendingParts = 0, + formData = null, + writtenObjects = new WeakMap(), + modelRoot = root; + checkEvalAvailabilityOnceDev(); + var json = serializeModel(root, 0); + null === formData + ? resolve(json) + : (formData.set(formFieldPrefix + "0", json), + 0 === pendingParts && resolve(formData)); + return function () { + 0 < pendingParts && + ((pendingParts = 0), + null === formData ? resolve(json) : resolve(formData)); + }; + } + function encodeFormData(reference) { + var resolve, + reject, + thenable = new Promise(function (res, rej) { + resolve = res; + reject = rej; + }); + processReply( + reference, + "", + void 0, + function (body) { + if ("string" === typeof body) { + var data = new FormData(); + data.append("0", body); + body = data; + } + thenable.status = "fulfilled"; + thenable.value = body; + resolve(body); + }, + function (e) { + thenable.status = "rejected"; + thenable.reason = e; + reject(e); + } + ); + return thenable; + } + function defaultEncodeFormAction(identifierPrefix) { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + var data = null; + if (null !== referenceClosure.bound) { + data = boundCache.get(referenceClosure); + data || + ((data = encodeFormData({ + id: referenceClosure.id, + bound: referenceClosure.bound + })), + boundCache.set(referenceClosure, data)); + if ("rejected" === data.status) throw data.reason; + if ("fulfilled" !== data.status) throw data; + referenceClosure = data.value; + var prefixedData = new FormData(); + referenceClosure.forEach(function (value, key) { + prefixedData.append("$ACTION_" + identifierPrefix + ":" + key, value); + }); + data = prefixedData; + referenceClosure = "$ACTION_REF_" + identifierPrefix; + } else referenceClosure = "$ACTION_ID_" + referenceClosure.id; + return { + name: referenceClosure, + method: "POST", + encType: "multipart/form-data", + data: data + }; + } + function isSignatureEqual(referenceId, numberOfBoundArgs) { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + if (referenceClosure.id !== referenceId) return !1; + var boundPromise = referenceClosure.bound; + if (null === boundPromise) return 0 === numberOfBoundArgs; + switch (boundPromise.status) { + case "fulfilled": + return boundPromise.value.length === numberOfBoundArgs; + case "pending": + throw boundPromise; + case "rejected": + throw boundPromise.reason; + default: + throw ( + ("string" !== typeof boundPromise.status && + ((boundPromise.status = "pending"), + boundPromise.then( + function (boundArgs) { + boundPromise.status = "fulfilled"; + boundPromise.value = boundArgs; + }, + function (error) { + boundPromise.status = "rejected"; + boundPromise.reason = error; + } + )), + boundPromise) + ); + } + } + function createFakeServerFunction( + name, + filename, + sourceMap, + line, + col, + environmentName, + innerFunction + ) { + name || (name = ""); + var encodedName = JSON.stringify(name); + 1 >= line + ? ((line = encodedName.length + 7), + (col = + "s=>({" + + encodedName + + " ".repeat(col < line ? 0 : col - line) + + ":(...args) => s(...args)})\n/* This module is a proxy to a Server Action. Turn on Source Maps to see the server source. */")) + : (col = + "/* This module is a proxy to a Server Action. Turn on Source Maps to see the server source. */" + + "\n".repeat(line - 2) + + "server=>({" + + encodedName + + ":\n" + + " ".repeat(1 > col ? 0 : col - 1) + + "(...args) => server(...args)})"); + filename.startsWith("/") && (filename = "file://" + filename); + sourceMap + ? ((col += + "\n//# sourceURL=about://React/" + + encodeURIComponent(environmentName) + + "/" + + encodeURI(filename) + + "?s" + + fakeServerFunctionIdx++), + (col += "\n//# sourceMappingURL=" + sourceMap)) + : filename && (col += "\n//# sourceURL=" + filename); + try { + return (0, eval)(col)(innerFunction)[name]; + } catch (x) { + return innerFunction; + } + } + function registerBoundServerReference( + reference, + id, + bound, + encodeFormAction + ) { + knownServerReferences.has(reference) || + (knownServerReferences.set(reference, { + id: id, + originalBind: reference.bind, + bound: bound + }), + Object.defineProperties(reference, { + $$FORM_ACTION: { + value: + void 0 === encodeFormAction + ? defaultEncodeFormAction + : function () { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + var boundPromise = referenceClosure.bound; + null === boundPromise && + (boundPromise = Promise.resolve([])); + return encodeFormAction(referenceClosure.id, boundPromise); + } + }, + $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, + bind: { value: bind } + })); + } + function bind() { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) return FunctionBind.apply(this, arguments); + var newFn = referenceClosure.originalBind.apply(this, arguments); + null != arguments[0] && + console.error( + 'Cannot bind "this" of a Server Action. Pass null or undefined as the first argument to .bind().' + ); + var args = ArraySlice.call(arguments, 1), + boundPromise = null; + boundPromise = + null !== referenceClosure.bound + ? Promise.resolve(referenceClosure.bound).then(function (boundArgs) { + return boundArgs.concat(args); + }) + : Promise.resolve(args); + knownServerReferences.set(newFn, { + id: referenceClosure.id, + originalBind: newFn.bind, + bound: boundPromise + }); + Object.defineProperties(newFn, { + $$FORM_ACTION: { value: this.$$FORM_ACTION }, + $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, + bind: { value: bind } + }); + return newFn; + } + function createBoundServerReference( + metaData, + callServer, + encodeFormAction, + findSourceMapURL + ) { + function action() { + var args = Array.prototype.slice.call(arguments); + return bound + ? "fulfilled" === bound.status + ? callServer(id, bound.value.concat(args)) + : Promise.resolve(bound).then(function (boundArgs) { + return callServer(id, boundArgs.concat(args)); + }) + : callServer(id, args); + } + var id = metaData.id, + bound = metaData.bound, + location = metaData.location; + if (location) { + var functionName = metaData.name || "", + filename = location[1], + line = location[2]; + location = location[3]; + metaData = metaData.env || "Server"; + findSourceMapURL = + null == findSourceMapURL + ? null + : findSourceMapURL(filename, metaData); + action = createFakeServerFunction( + functionName, + filename, + findSourceMapURL, + line, + location, + metaData, + action + ); + } + registerBoundServerReference(action, id, bound, encodeFormAction); + return action; + } + function parseStackLocation(error) { + error = error.stack; + error.startsWith("Error: react-stack-top-frame\n") && + (error = error.slice(29)); + var endOfFirst = error.indexOf("\n"); + if (-1 !== endOfFirst) { + var endOfSecond = error.indexOf("\n", endOfFirst + 1); + endOfFirst = + -1 === endOfSecond + ? error.slice(endOfFirst + 1) + : error.slice(endOfFirst + 1, endOfSecond); + } else endOfFirst = error; + error = v8FrameRegExp.exec(endOfFirst); + if ( + !error && + ((error = jscSpiderMonkeyFrameRegExp.exec(endOfFirst)), !error) + ) + return null; + endOfFirst = error[1] || ""; + "" === endOfFirst && (endOfFirst = ""); + endOfSecond = error[2] || error[5] || ""; + "" === endOfSecond && (endOfSecond = ""); + return [ + endOfFirst, + endOfSecond, + +(error[3] || error[6]), + +(error[4] || error[7]) + ]; + } + function createServerReference$1( + id, + callServer, + encodeFormAction, + findSourceMapURL, + functionName + ) { + function action() { + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + } + var location = parseStackLocation(Error("react-stack-top-frame")); + if (null !== location) { + var filename = location[1], + line = location[2]; + location = location[3]; + findSourceMapURL = + null == findSourceMapURL + ? null + : findSourceMapURL(filename, "Client"); + action = createFakeServerFunction( + functionName || "", + filename, + findSourceMapURL, + line, + location, + "Client", + action + ); + } + registerBoundServerReference(action, id, null, encodeFormAction); + return action; + } + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE + ? null + : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch ( + ("number" === typeof type.tag && + console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), + type.$$typeof) + ) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || + ((type = innerType.displayName || innerType.name || ""), + (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); + return type; + case REACT_MEMO_TYPE: + return ( + (innerType = type.displayName || null), + null !== innerType + ? innerType + : getComponentNameFromType(type.type) || "Memo" + ); + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) {} + } + return null; + } + function getArrayKind(array) { + for (var kind = 0, i = 0; i < array.length && 100 > i; i++) { + var value = array[i]; + if ("object" === typeof value && null !== value) + if ( + isArrayImpl(value) && + 2 === value.length && + "string" === typeof value[0] + ) { + if (0 !== kind && 3 !== kind) return 1; + kind = 3; + } else return 1; + else { + if ( + "function" === typeof value || + ("string" === typeof value && 50 < value.length) || + (0 !== kind && 2 !== kind) || + "bigint" === typeof value + ) + return 1; + kind = 2; + } + } + return kind; + } + function addObjectToProperties(object, properties, indent, prefix) { + if (!ArrayBuffer.isView(object)) { + var addedProperties = 0, + key; + for (key in object) + if ( + hasOwnProperty.call(object, key) && + "_" !== key[0] && + (addedProperties++, + addValueToProperties(key, object[key], properties, indent, prefix), + 100 <= addedProperties) + ) { + properties.push([ + prefix + + "\u00a0\u00a0".repeat(indent) + + "Only 100 properties are shown. React will not log more properties of this object.", + "" + ]); + break; + } + } + } + function addValueToProperties( + propertyName, + value, + properties, + indent, + prefix + ) { + switch (typeof value) { + case "object": + if (null === value) { + value = "null"; + break; + } else { + if ( + ("$$typeof" in value && hasOwnProperty.call(value, "$$typeof") + ? value.$$typeof + : void 0) === REACT_ELEMENT_TYPE + ) { + var typeName = getComponentNameFromType(value.type) || "\u2026", + key = value.key; + value = value.props; + var propsKeys = Object.keys(value), + propsLength = propsKeys.length; + if (null == key && 0 === propsLength) { + value = "<" + typeName + " />"; + break; + } + if ( + 3 > indent || + (1 === propsLength && + "children" === propsKeys[0] && + null == key) + ) { + value = "<" + typeName + " \u2026 />"; + break; + } + properties.push([ + prefix + "\u00a0\u00a0".repeat(indent) + propertyName, + "<" + typeName + ]); + null !== key && + addValueToProperties( + "key", + key, + properties, + indent + 1, + prefix + ); + propertyName = !1; + key = 0; + for (var propKey in value) + if ( + (key++, + "children" === propKey + ? null != value.children && + (!isArrayImpl(value.children) || + 0 < value.children.length) && + (propertyName = !0) + : hasOwnProperty.call(value, propKey) && + "_" !== propKey[0] && + addValueToProperties( + propKey, + value[propKey], + properties, + indent + 1, + prefix + ), + 100 <= key) + ) + break; + properties.push([ + "", + propertyName ? ">\u2026" : "/>" + ]); + return; + } + typeName = Object.prototype.toString.call(value); + typeName = typeName.slice(8, typeName.length - 1); + if (ArrayBuffer.isView(value)) { + value = value.length; + value = + "number" === typeof value + ? typeName + "(" + value + ")" + : typeName; + break; + } + if ("Array" === typeName) + if ( + ((propKey = 100 < value.length), + (key = getArrayKind(value)), + 2 === key || 0 === key) + ) { + value = JSON.stringify( + propKey ? value.slice(0, 100).concat("\u2026") : value + ); + break; + } else if (3 === key) { + properties.push([ + prefix + "\u00a0\u00a0".repeat(indent) + propertyName, + "" + ]); + for ( + propertyName = 0; + propertyName < value.length && 100 > propertyName; + propertyName++ + ) + (typeName = value[propertyName]), + addValueToProperties( + typeName[0], + typeName[1], + properties, + indent + 1, + prefix + ); + propKey && + addValueToProperties( + (100).toString(), + "\u2026", + properties, + indent + 1, + prefix + ); + return; + } + if ("Promise" === typeName) { + if ("fulfilled" === value.status) { + if ( + ((typeName = properties.length), + addValueToProperties( + propertyName, + value.value, + properties, + indent, + prefix + ), + properties.length > typeName) + ) { + properties = properties[typeName]; + properties[1] = + "Promise<" + (properties[1] || "Object") + ">"; + return; + } + } else if ( + "rejected" === value.status && + ((typeName = properties.length), + addValueToProperties( + propertyName, + value.reason, + properties, + indent, + prefix + ), + properties.length > typeName) + ) { + properties = properties[typeName]; + properties[1] = "Rejected Promise<" + properties[1] + ">"; + return; + } + properties.push([ + "\u00a0\u00a0".repeat(indent) + propertyName, + "Promise" + ]); + return; + } + "Object" === typeName && + (propKey = Object.getPrototypeOf(value)) && + "function" === typeof propKey.constructor && + (typeName = propKey.constructor.name); + properties.push([ + prefix + "\u00a0\u00a0".repeat(indent) + propertyName, + "Object" === typeName ? (3 > indent ? "" : "\u2026") : typeName + ]); + 3 > indent && + addObjectToProperties(value, properties, indent + 1, prefix); + return; + } + case "function": + value = value.name; + value = + "" === value || "string" !== typeof value + ? "() => {}" + : value + "() {}"; + break; + case "string": + value = + "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects." === + value + ? "\u2026" + : JSON.stringify( + 1024 <= value.length ? value.slice(0, 1023) + "\u2026" : value + ); + break; + case "undefined": + value = "undefined"; + break; + case "boolean": + value = value ? "true" : "false"; + break; + default: + value = String(value); + } + properties.push([ + prefix + "\u00a0\u00a0".repeat(indent) + propertyName, + value + ]); + } + function getIODescription(value) { + try { + switch (typeof value) { + case "function": + return value.name || ""; + case "object": + if (null === value) return ""; + if (value instanceof Error) return String(value.message); + if ("string" === typeof value.url) return value.url; + if ("string" === typeof value.href) return value.href; + if ("string" === typeof value.src) return value.src; + if ("string" === typeof value.currentSrc) return value.currentSrc; + if ("string" === typeof value.command) return value.command; + if ( + "object" === typeof value.request && + null !== value.request && + "string" === typeof value.request.url + ) + return value.request.url; + if ( + "object" === typeof value.response && + null !== value.response && + "string" === typeof value.response.url + ) + return value.response.url; + if ( + "string" === typeof value.id || + "number" === typeof value.id || + "bigint" === typeof value.id + ) + return String(value.id); + if ("string" === typeof value.name) return value.name; + var str = value.toString(); + return str.startsWith("[object ") || + 5 > str.length || + 500 < str.length + ? "" + : str; + case "string": + return 5 > value.length || 500 < value.length ? "" : value; + case "number": + case "bigint": + return String(value); + default: + return ""; + } + } catch (x) { + return ""; + } + } + function markAllTracksInOrder() { + supportsUserTiming && + (console.timeStamp( + "Server Requests Track", + 0.001, + 0.001, + "Server Requests \u269b", + void 0, + "primary-light" + ), + console.timeStamp( + "Server Components Track", + 0.001, + 0.001, + "Primary", + "Server Components \u269b", + "primary-light" + )); + } + function getIOColor(functionName) { + switch (functionName.charCodeAt(0) % 3) { + case 0: + return "tertiary-light"; + case 1: + return "tertiary"; + default: + return "tertiary-dark"; + } + } + function getIOLongName(ioInfo, description, env, rootEnv) { + ioInfo = ioInfo.name; + description = + "" === description ? ioInfo : ioInfo + " (" + description + ")"; + return env === rootEnv || void 0 === env + ? description + : description + " [" + env + "]"; + } + function getIOShortName(ioInfo, description, env, rootEnv) { + ioInfo = ioInfo.name; + env = env === rootEnv || void 0 === env ? "" : " [" + env + "]"; + var desc = ""; + rootEnv = 30 - ioInfo.length - env.length; + if (1 < rootEnv) { + var l = description.length; + if (0 < l && l <= rootEnv) desc = " (" + description + ")"; + else if ( + description.startsWith("http://") || + description.startsWith("https://") || + description.startsWith("/") + ) { + var queryIdx = description.indexOf("?"); + -1 === queryIdx && (queryIdx = description.length); + 47 === description.charCodeAt(queryIdx - 1) && queryIdx--; + desc = description.lastIndexOf("/", queryIdx - 1); + queryIdx - desc < rootEnv + ? (desc = " (\u2026" + description.slice(desc, queryIdx) + ")") + : ((l = description.slice(desc, desc + rootEnv / 2)), + (description = description.slice( + queryIdx - rootEnv / 2, + queryIdx + )), + (desc = + " (" + + (0 < desc ? "\u2026" : "") + + l + + "\u2026" + + description + + ")")); + } + } + return ioInfo + desc + env; + } + function logComponentAwait( + asyncInfo, + trackIdx, + startTime, + endTime, + rootEnv, + value + ) { + if (supportsUserTiming && 0 < endTime) { + var description = getIODescription(value), + name = getIOShortName( + asyncInfo.awaited, + description, + asyncInfo.env, + rootEnv + ), + entryName = "await " + name; + name = getIOColor(name); + var debugTask = asyncInfo.debugTask || asyncInfo.awaited.debugTask; + if (debugTask) { + var properties = []; + "object" === typeof value && null !== value + ? addObjectToProperties(value, properties, 0, "") + : void 0 !== value && + addValueToProperties("awaited value", value, properties, 0, ""); + asyncInfo = getIOLongName( + asyncInfo.awaited, + description, + asyncInfo.env, + rootEnv + ); + debugTask.run( + performance.measure.bind(performance, entryName, { + start: 0 > startTime ? 0 : startTime, + end: endTime, + detail: { + devtools: { + color: name, + track: trackNames[trackIdx], + trackGroup: "Server Components \u269b", + properties: properties, + tooltipText: asyncInfo + } + } + }) + ); + performance.clearMeasures(entryName); + } else + console.timeStamp( + entryName, + 0 > startTime ? 0 : startTime, + endTime, + trackNames[trackIdx], + "Server Components \u269b", + name + ); + } + } + function logIOInfoErrored(ioInfo, rootEnv, error) { + var startTime = ioInfo.start, + endTime = ioInfo.end; + if (supportsUserTiming && 0 <= endTime) { + var description = getIODescription(error), + entryName = getIOShortName(ioInfo, description, ioInfo.env, rootEnv), + debugTask = ioInfo.debugTask; + entryName = "\u200b" + entryName; + debugTask + ? ((error = [ + [ + "rejected with", + "object" === typeof error && + null !== error && + "string" === typeof error.message + ? String(error.message) + : String(error) + ] + ]), + (ioInfo = + getIOLongName(ioInfo, description, ioInfo.env, rootEnv) + + " Rejected"), + debugTask.run( + performance.measure.bind(performance, entryName, { + start: 0 > startTime ? 0 : startTime, + end: endTime, + detail: { + devtools: { + color: "error", + track: "Server Requests \u269b", + properties: error, + tooltipText: ioInfo + } + } + }) + ), + performance.clearMeasures(entryName)) + : console.timeStamp( + entryName, + 0 > startTime ? 0 : startTime, + endTime, + "Server Requests \u269b", + void 0, + "error" + ); + } + } + function logIOInfo(ioInfo, rootEnv, value) { + var startTime = ioInfo.start, + endTime = ioInfo.end; + if (supportsUserTiming && 0 <= endTime) { + var description = getIODescription(value), + entryName = getIOShortName(ioInfo, description, ioInfo.env, rootEnv), + color = getIOColor(entryName), + debugTask = ioInfo.debugTask; + entryName = "\u200b" + entryName; + if (debugTask) { + var properties = []; + "object" === typeof value && null !== value + ? addObjectToProperties(value, properties, 0, "") + : void 0 !== value && + addValueToProperties("Resolved", value, properties, 0, ""); + ioInfo = getIOLongName(ioInfo, description, ioInfo.env, rootEnv); + debugTask.run( + performance.measure.bind(performance, entryName, { + start: 0 > startTime ? 0 : startTime, + end: endTime, + detail: { + devtools: { + color: color, + track: "Server Requests \u269b", + properties: properties, + tooltipText: ioInfo + } + } + }) + ); + performance.clearMeasures(entryName); + } else + console.timeStamp( + entryName, + 0 > startTime ? 0 : startTime, + endTime, + "Server Requests \u269b", + void 0, + color + ); + } + } + function prepareStackTrace(error, structuredStackTrace) { + error = (error.name || "Error") + ": " + (error.message || ""); + for (var i = 0; i < structuredStackTrace.length; i++) + error += "\n at " + structuredStackTrace[i].toString(); + return error; + } + function ReactPromise(status, value, reason) { + this.status = status; + this.value = value; + this.reason = reason; + this._children = []; + this._debugChunk = null; + this._debugInfo = []; + } + function hasGCedResponse(weakResponse) { + return void 0 === weakResponse.weak.deref(); + } + function unwrapWeakResponse(weakResponse) { + weakResponse = weakResponse.weak.deref(); + if (void 0 === weakResponse) + throw Error( + "We did not expect to receive new data after GC:ing the response." + ); + return weakResponse; + } + function closeDebugChannel(debugChannel) { + debugChannel.callback && debugChannel.callback(""); + } + function readChunk(chunk) { + switch (chunk.status) { + case "resolved_model": + initializeModelChunk(chunk); + break; + case "resolved_module": + initializeModuleChunk(chunk); + } + switch (chunk.status) { + case "fulfilled": + return chunk.value; + case "pending": + case "pending_weak": + case "blocked": + case "halted": + throw chunk; + default: + throw chunk.reason; + } + } + function getRoot(weakResponse) { + weakResponse = unwrapWeakResponse(weakResponse); + return getChunk(weakResponse, 0); + } + function createPendingChunk(response) { + 0 === response._pendingChunks++ && + ((response._weakResponse.response = response), + null !== response._pendingInitialRender && + (clearTimeout(response._pendingInitialRender), + (response._pendingInitialRender = null))); + return new ReactPromise("pending", null, null); + } + function releasePendingChunk(response, chunk) { + "pending" === chunk.status && + 0 === --response._pendingChunks && + ((response._weakResponse.response = null), + (response._pendingInitialRender = setTimeout( + flushInitialRenderPerformance.bind(null, response), + 100 + ))); + } + function haltChunk(response, chunk) { + releasePendingChunk(response, chunk); + chunk.status = "halted"; + chunk.value = null; + chunk.reason = null; + } + function filterDebugInfo(response, value) { + if (null !== response._debugEndTime) { + response = response._debugEndTime - performance.timeOrigin; + for (var debugInfo = [], i = 0; i < value._debugInfo.length; i++) { + var info = value._debugInfo[i]; + if ("number" === typeof info.time && info.time > response) break; + debugInfo.push(info); + } + value._debugInfo = debugInfo; + } + } + function moveDebugInfoFromChunkToInnerValue(chunk, value) { + value = resolveLazy(value); + "object" !== typeof value || + null === value || + (!isArrayImpl(value) && + "function" !== typeof value[ASYNC_ITERATOR] && + value.$$typeof !== REACT_ELEMENT_TYPE && + value.$$typeof !== REACT_LAZY_TYPE) || + ((chunk = chunk._debugInfo.splice(0)), + isArrayImpl(value._debugInfo) + ? value._debugInfo.unshift.apply(value._debugInfo, chunk) + : Object.isFrozen(value) || + Object.defineProperty(value, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: chunk + })); + } + function wakeChunk(response, listeners, value, chunk) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk); + } + filterDebugInfo(response, chunk); + moveDebugInfoFromChunkToInnerValue(chunk, value); + } + function rejectChunk(response, listeners, error) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(error) + : rejectReference(response, listener.handler, error); + } + } + function resolveBlockedCycle(resolvedChunk, reference) { + var referencedChunk = reference.handler.chunk; + if (null === referencedChunk) return null; + if (referencedChunk === resolvedChunk) return reference.handler; + reference = referencedChunk.value; + if (null !== reference) + for ( + referencedChunk = 0; + referencedChunk < reference.length; + referencedChunk++ + ) { + var listener = reference[referencedChunk]; + if ( + "function" !== typeof listener && + ((listener = resolveBlockedCycle(resolvedChunk, listener)), + null !== listener) + ) + return listener; + } + return null; + } + function wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + ) { + switch (chunk.status) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + break; + case "blocked": + for (var i = 0; i < resolveListeners.length; i++) { + var listener = resolveListeners[i]; + if ("function" !== typeof listener) { + var cyclicHandler = resolveBlockedCycle(chunk, listener); + if (null !== cyclicHandler) + switch ( + (fulfillReference( + response, + listener, + cyclicHandler.value, + chunk + ), + resolveListeners.splice(i, 1), + i--, + null !== rejectListeners && + ((listener = rejectListeners.indexOf(listener)), + -1 !== listener && rejectListeners.splice(listener, 1)), + chunk.status) + ) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + return; + case "rejected": + null !== rejectListeners && + rejectChunk(response, rejectListeners, chunk.reason); + return; + } + } + } + case "pending": + if (chunk.value) + for (response = 0; response < resolveListeners.length; response++) + chunk.value.push(resolveListeners[response]); + else chunk.value = resolveListeners; + if (chunk.reason) { + if (rejectListeners) + for ( + resolveListeners = 0; + resolveListeners < rejectListeners.length; + resolveListeners++ + ) + chunk.reason.push(rejectListeners[resolveListeners]); + } else chunk.reason = rejectListeners; + break; + case "rejected": + rejectListeners && + rejectChunk(response, rejectListeners, chunk.reason); + } + } + function triggerErrorOnChunk(response, chunk, error) { + if ( + "pending" !== chunk.status && + "pending_weak" !== chunk.status && + "blocked" !== chunk.status + ) + chunk.reason.error(error); + else { + releasePendingChunk(response, chunk); + var listeners = chunk.reason; + if ( + ("pending" === chunk.status || "pending_weak" === chunk.status) && + null != chunk._debugChunk + ) { + var prevHandler = initializingHandler, + prevChunk = initializingChunk; + initializingHandler = null; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + initializingChunk = chunk; + try { + initializeDebugChunk(response, chunk); + } finally { + (initializingHandler = prevHandler), + (initializingChunk = prevChunk); + } + } + chunk.status = "rejected"; + chunk.reason = error; + a: if (null !== response._debugEndTime) + for ( + prevHandler = response._debugEndTime - performance.timeOrigin, + chunk = chunk._debugInfo, + prevChunk = 0; + prevChunk < chunk.length; + prevChunk++ + ) { + var info = chunk[prevChunk]; + if ("number" === typeof info.time && info.time > prevHandler) { + chunk.length = prevChunk; + break a; + } + } + null !== listeners && rejectChunk(response, listeners, error); + } + } + function createResolvedModelChunk(response, value) { + return new ReactPromise("resolved_model", value, response); + } + function createResolvedIteratorResultChunk(response, value, done) { + return new ReactPromise( + "resolved_model", + (done ? '{"done":true,"value":' : '{"done":false,"value":') + + value + + "}", + response + ); + } + function resolveIteratorResultChunk(response, chunk, value, done) { + resolveModelChunk( + response, + chunk, + (done ? '{"done":true,"value":' : '{"done":false,"value":') + + value + + "}" + ); + } + function resolveModelChunk(response, chunk, value) { + if ("pending" !== chunk.status && "pending_weak" !== chunk.status) + chunk.reason.enqueueModel(value); + else { + releasePendingChunk(response, chunk); + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_model"; + chunk.value = value; + chunk.reason = response; + null !== resolveListeners && + (initializeModelChunk(chunk), + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + )); + } + } + function resolveModuleChunk(response, chunk, value) { + if ( + "pending" === chunk.status || + "pending_weak" === chunk.status || + "blocked" === chunk.status + ) { + releasePendingChunk(response, chunk); + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_module"; + chunk.value = value; + chunk.reason = null; + value = []; + null !== value && chunk._debugInfo.push.apply(chunk._debugInfo, value); + null !== resolveListeners && + (initializeModuleChunk(chunk), + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + )); + } + } + function initializeDebugChunk(response, chunk) { + var debugChunk = chunk._debugChunk; + if (null !== debugChunk) { + var debugInfo = chunk._debugInfo, + prevIsInitializingDebugInfo = isInitializingDebugInfo; + isInitializingDebugInfo = !0; + try { + if ("resolved_model" === debugChunk.status) { + for ( + var idx = debugInfo.length, c = debugChunk._debugChunk; + null !== c; + + ) + "fulfilled" !== c.status && idx++, (c = c._debugChunk); + initializeModelChunk(debugChunk); + switch (debugChunk.status) { + case "fulfilled": + debugInfo[idx] = initializeDebugInfo( + response, + debugChunk.value + ); + break; + case "blocked": + case "pending": + case "pending_weak": + waitForReference( + debugChunk, + debugInfo, + "" + idx, + response, + initializeDebugInfo, + [""], + !0 + ); + break; + default: + throw debugChunk.reason; + } + } else + switch (debugChunk.status) { + case "fulfilled": + break; + case "blocked": + case "pending": + case "pending_weak": + waitForReference( + debugChunk, + {}, + "debug", + response, + initializeDebugInfo, + [""], + !0 + ); + break; + default: + throw debugChunk.reason; + } + } catch (error) { + triggerErrorOnChunk(response, chunk, error); + } finally { + isInitializingDebugInfo = prevIsInitializingDebugInfo; + } + } + } + function initializeModelChunk(chunk) { + var prevHandler = initializingHandler, + prevChunk = initializingChunk; + initializingHandler = null; + var resolvedModel = chunk.value, + response = chunk.reason; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + initializingChunk = chunk; + initializeDebugChunk(response, chunk); + try { + var value = parseModel(response, resolvedModel), + resolveListeners = chunk.value; + if (null !== resolveListeners) + for ( + chunk.value = null, chunk.reason = null, resolvedModel = 0; + resolvedModel < resolveListeners.length; + resolvedModel++ + ) { + var listener = resolveListeners[resolvedModel]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk); + } + if (null !== initializingHandler) { + if (initializingHandler.errored) throw initializingHandler.reason; + if (0 < initializingHandler.deps) { + initializingHandler.value = value; + initializingHandler.chunk = chunk; + return; + } + } + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = null; + filterDebugInfo(response, chunk); + moveDebugInfoFromChunkToInnerValue(chunk, value); + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } finally { + (initializingHandler = prevHandler), (initializingChunk = prevChunk); + } + } + function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = null; + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } + } + function reportGlobalError(weakResponse, error) { + if (!hasGCedResponse(weakResponse)) { + var response = unwrapWeakResponse(weakResponse); + response._closed = !0; + response._closedReason = error; + response._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? triggerErrorOnChunk(response, chunk, error) + : "fulfilled" === chunk.status && + null !== chunk.reason && + chunk.reason.error(error); + }); + weakResponse = response._debugChannel; + void 0 !== weakResponse && + (closeDebugChannel(weakResponse), + (response._debugChannel = void 0), + null !== debugChannelRegistry && + debugChannelRegistry.unregister(response)); + } + } + function nullRefGetter() { + return null; + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ("function" === typeof type) return '"use client"'; + if ( + "object" === typeof type && + null !== type && + type.$$typeof === REACT_LAZY_TYPE + ) + return type._payload instanceof ReactPromise ? '"use client"' : "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function initializeElement(response, element, lazyNode) { + var stack = element._debugStack, + owner = element._owner; + null === owner && (element._owner = response._debugRootOwner); + var env = response._rootEnvironmentName; + null !== owner && null != owner.env && (env = owner.env); + var normalizedStackTrace = null; + null === owner && null != response._debugRootStack + ? (normalizedStackTrace = response._debugRootStack) + : null !== stack && + (normalizedStackTrace = createFakeJSXCallStackInDEV( + response, + stack, + env + )); + element._debugStack = normalizedStackTrace; + normalizedStackTrace = null; + supportsCreateTask && + null !== stack && + ((normalizedStackTrace = console.createTask.bind( + console, + getTaskName(element.type) + )), + (stack = buildFakeCallStack( + response, + stack, + env, + !1, + normalizedStackTrace + )), + (env = null === owner ? null : initializeFakeTask(response, owner)), + null === env + ? ((env = response._debugRootTask), + (normalizedStackTrace = null != env ? env.run(stack) : stack())) + : (normalizedStackTrace = env.run(stack))); + element._debugTask = normalizedStackTrace; + null !== owner && initializeFakeStack(response, owner); + null !== lazyNode && + "fulfilled" === lazyNode._payload.status && + lazyNode._debugInfo && + ((response = lazyNode._debugInfo.splice(0)), + element._debugInfo + ? element._debugInfo.unshift.apply(element._debugInfo, response) + : Object.defineProperty(element, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: response + })); + Object.freeze(element.props); + } + function readChunkAndTransferValidation(store, payload) { + payload = readChunk(payload); + if (store.validated && "object" === typeof payload && null !== payload) { + var $$typeof = payload.$$typeof; + ($$typeof !== REACT_ELEMENT_TYPE && $$typeof !== REACT_LAZY_TYPE) || + !($$typeof = payload._store) || + $$typeof.validated || + ($$typeof.validated = store.validated); + } + return payload; + } + function createLazyChunkWrapper(chunk, validated) { + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: chunk, + _init: readChunk + }; + lazyType._debugInfo = chunk._debugInfo; + chunk = { validated: validated }; + lazyType._store = chunk; + lazyType._init = readChunkAndTransferValidation.bind(null, chunk); + return lazyType; + } + function getChunk(response, id) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk || + ((chunk = response._closed + ? response._allowPartialStream + ? new ReactPromise("halted", null, null) + : new ReactPromise("rejected", null, response._closedReason) + : createPendingChunk(response)), + chunks.set(id, chunk)); + return chunk; + } + function fulfillReference(response, reference, value, fulfilledChunk) { + var handler = reference.handler, + parentObject = reference.parentObject, + key = reference.key, + map = reference.map, + path = reference.path; + try { + for (var i = 1; i < path.length; i++) { + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + var referencedChunk = value._payload; + if (referencedChunk === handler.chunk) value = handler.value; + else { + switch (referencedChunk.status) { + case "resolved_model": + initializeModelChunk(referencedChunk); + break; + case "resolved_module": + initializeModuleChunk(referencedChunk); + } + switch (referencedChunk.status) { + case "fulfilled": + value = referencedChunk.value; + continue; + case "blocked": + var cyclicHandler = resolveBlockedCycle( + referencedChunk, + reference + ); + if (null !== cyclicHandler) { + value = cyclicHandler.value; + continue; + } + case "pending": + case "pending_weak": + path.splice(0, i - 1); + null === referencedChunk.value + ? (referencedChunk.value = [reference]) + : referencedChunk.value.push(reference); + null === referencedChunk.reason + ? (referencedChunk.reason = [reference]) + : referencedChunk.reason.push(reference); + return; + case "halted": + return; + default: + rejectReference( + response, + reference.handler, + referencedChunk.reason + ); + return; + } + } + } + var name = path[i]; + if ( + "object" === typeof value && + null !== value && + hasOwnProperty.call(value, name) + ) + value = value[name]; + else throw Error("Invalid reference."); + } + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + var _referencedChunk = value._payload; + if (_referencedChunk === handler.chunk) value = handler.value; + else { + switch (_referencedChunk.status) { + case "resolved_model": + initializeModelChunk(_referencedChunk); + break; + case "resolved_module": + initializeModuleChunk(_referencedChunk); + } + switch (_referencedChunk.status) { + case "fulfilled": + value = _referencedChunk.value; + continue; + } + break; + } + } + var mappedValue = map(response, value, parentObject, key); + "__proto__" !== key && (parentObject[key] = mappedValue); + "" === key && null === handler.value && (handler.value = mappedValue); + if ( + parentObject[0] === REACT_ELEMENT_TYPE && + "object" === typeof handler.value && + null !== handler.value && + handler.value.$$typeof === REACT_ELEMENT_TYPE + ) { + var element = handler.value; + switch (key) { + case "3": + transferReferencedDebugInfo(handler.chunk, fulfilledChunk); + element.props = mappedValue; + break; + case "4": + element._owner = mappedValue; + break; + case "5": + element._debugStack = mappedValue; + break; + default: + transferReferencedDebugInfo(handler.chunk, fulfilledChunk); + } + } else + reference.isDebug || + transferReferencedDebugInfo(handler.chunk, fulfilledChunk); + } catch (error) { + rejectReference(response, reference.handler, error); + return; + } + handler.deps--; + 0 === handler.deps && + ((reference = handler.chunk), + null !== reference && + "blocked" === reference.status && + ((value = reference.value), + (reference.status = "fulfilled"), + (reference.value = handler.value), + (reference.reason = handler.reason), + null !== value + ? wakeChunk(response, value, handler.value, reference) + : ((handler = handler.value), + filterDebugInfo(response, reference), + moveDebugInfoFromChunkToInnerValue(reference, handler)))); + } + function rejectReference(response, handler, error) { + if (!handler.errored) { + var blockedValue = handler.value; + handler.errored = !0; + handler.value = null; + handler.reason = error; + handler = handler.chunk; + if (null !== handler && "blocked" === handler.status) { + if ( + "object" === typeof blockedValue && + null !== blockedValue && + blockedValue.$$typeof === REACT_ELEMENT_TYPE + ) { + var erroredComponent = { + name: getComponentNameFromType(blockedValue.type) || "", + owner: blockedValue._owner + }; + erroredComponent.debugStack = blockedValue._debugStack; + supportsCreateTask && + (erroredComponent.debugTask = blockedValue._debugTask); + handler._debugInfo.push(erroredComponent); + } + triggerErrorOnChunk(response, handler, error); + } + } + } + function waitForReference( + referencedChunk, + parentObject, + key, + response, + map, + path, + isAwaitingDebugInfo + ) { + if ( + !( + (void 0 !== response._debugChannel && + response._debugChannel.hasReadable) || + "pending" !== referencedChunk.status || + parentObject[0] !== REACT_ELEMENT_TYPE || + ("4" !== key && "5" !== key) + ) + ) + return null; + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (response = initializingHandler = + { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }); + parentObject = { + handler: response, + parentObject: parentObject, + key: key, + map: map, + path: path + }; + parentObject.isDebug = isAwaitingDebugInfo; + null === referencedChunk.value + ? (referencedChunk.value = [parentObject]) + : referencedChunk.value.push(parentObject); + null === referencedChunk.reason + ? (referencedChunk.reason = [parentObject]) + : referencedChunk.reason.push(parentObject); + return null; + } + function loadServerReference(response, metaData, parentObject, key) { + if (!response._serverReferenceConfig) + return createBoundServerReference( + metaData, + response._callServer, + response._encodeFormAction, + response._debugFindSourceMapURL + ); + var serverReference = resolveServerReference( + response._serverReferenceConfig, + metaData.id + ), + promise = preloadModule(serverReference); + if (promise) + metaData.bound && (promise = Promise.all([promise, metaData.bound])); + else if (metaData.bound) promise = Promise.resolve(metaData.bound); + else + return ( + (promise = requireModule(serverReference)), + registerBoundServerReference( + promise, + metaData.id, + metaData.bound, + response._encodeFormAction + ), + promise + ); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + promise.then( + function () { + var resolvedValue = requireModule(serverReference); + if (metaData.bound) { + var boundArgs = metaData.bound.value.slice(0); + boundArgs.unshift(null); + resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs); + } + registerBoundServerReference( + resolvedValue, + metaData.id, + metaData.bound, + response._encodeFormAction + ); + "__proto__" !== key && (parentObject[key] = resolvedValue); + "" === key && + null === handler.value && + (handler.value = resolvedValue); + if ( + parentObject[0] === REACT_ELEMENT_TYPE && + "object" === typeof handler.value && + null !== handler.value && + handler.value.$$typeof === REACT_ELEMENT_TYPE + ) + switch (((boundArgs = handler.value), key)) { + case "3": + boundArgs.props = resolvedValue; + break; + case "4": + boundArgs._owner = resolvedValue; + } + handler.deps--; + 0 === handler.deps && + ((resolvedValue = handler.chunk), + null !== resolvedValue && + "blocked" === resolvedValue.status && + ((boundArgs = resolvedValue.value), + (resolvedValue.status = "fulfilled"), + (resolvedValue.value = handler.value), + (resolvedValue.reason = null), + null !== boundArgs + ? wakeChunk(response, boundArgs, handler.value, resolvedValue) + : ((boundArgs = handler.value), + filterDebugInfo(response, resolvedValue), + moveDebugInfoFromChunkToInnerValue( + resolvedValue, + boundArgs + )))); + }, + function (error) { + if (!handler.errored) { + var blockedValue = handler.value; + handler.errored = !0; + handler.value = null; + handler.reason = error; + var chunk = handler.chunk; + if (null !== chunk && "blocked" === chunk.status) { + if ( + "object" === typeof blockedValue && + null !== blockedValue && + blockedValue.$$typeof === REACT_ELEMENT_TYPE + ) { + var erroredComponent = { + name: getComponentNameFromType(blockedValue.type) || "", + owner: blockedValue._owner + }; + erroredComponent.debugStack = blockedValue._debugStack; + supportsCreateTask && + (erroredComponent.debugTask = blockedValue._debugTask); + chunk._debugInfo.push(erroredComponent); + } + triggerErrorOnChunk(response, chunk, error); + } + } + } + ); + return null; + } + function resolveLazy(value) { + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + var payload = value._payload; + if ("fulfilled" === payload.status) value = payload.value; + else break; + } + return value; + } + function transferReferencedDebugInfo(parentChunk, referencedChunk) { + if (null !== parentChunk) { + referencedChunk = referencedChunk._debugInfo; + parentChunk = parentChunk._debugInfo; + for (var i = 0; i < referencedChunk.length; ++i) { + var debugInfoEntry = referencedChunk[i]; + null == debugInfoEntry.name && parentChunk.push(debugInfoEntry); + } + } + } + function getOutlinedModel(response, reference, parentObject, key, map) { + var path = reference.split(":"); + reference = parseInt(path[0], 16); + reference = getChunk(response, reference); + null !== initializingChunk && + isArrayImpl(initializingChunk._children) && + initializingChunk._children.push(reference); + switch (reference.status) { + case "resolved_model": + initializeModelChunk(reference); + break; + case "resolved_module": + initializeModuleChunk(reference); + } + switch (reference.status) { + case "fulfilled": + for (var value = reference.value, i = 1; i < path.length; i++) { + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + value = value._payload; + switch (value.status) { + case "resolved_model": + initializeModelChunk(value); + break; + case "resolved_module": + initializeModuleChunk(value); + } + switch (value.status) { + case "fulfilled": + value = value.value; + break; + case "blocked": + case "pending": + case "pending_weak": + return waitForReference( + value, + parentObject, + key, + response, + map, + path.slice(i - 1), + isInitializingDebugInfo + ); + case "halted": + return ( + initializingHandler + ? ((parentObject = initializingHandler), + parentObject.deps++) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }), + null + ); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = value.reason)) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: value.reason, + deps: 0, + errored: !0 + }), + null + ); + } + } + var name = path[i]; + if ( + "object" !== typeof value || + null === value || + (getPrototypeOf(value) !== ObjectPrototype && + getPrototypeOf(value) !== ArrayPrototype) || + !hasOwnProperty.call(value, name) + ) + throw Error("Invalid reference."); + value = value[name]; + } + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + path = value._payload; + switch (path.status) { + case "resolved_model": + initializeModelChunk(path); + break; + case "resolved_module": + initializeModuleChunk(path); + } + switch (path.status) { + case "fulfilled": + value = path.value; + continue; + } + break; + } + response = map(response, value, parentObject, key); + if ( + parentObject[0] !== REACT_ELEMENT_TYPE || + ("4" !== key && "5" !== key) + ) + isInitializingDebugInfo || + transferReferencedDebugInfo(initializingChunk, reference); + return response; + case "pending": + case "pending_weak": + case "blocked": + return waitForReference( + reference, + parentObject, + key, + response, + map, + path, + isInitializingDebugInfo + ); + case "halted": + return ( + initializingHandler + ? ((parentObject = initializingHandler), parentObject.deps++) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }), + null + ); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = reference.reason)) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: reference.reason, + deps: 0, + errored: !0 + }), + null + ); + } + } + function createMap(response, model) { + return new Map(model); + } + function createSet(response, model) { + return new Set(model); + } + function createBlob(response, model) { + return new Blob(model.slice(1), { type: model[0] }); + } + function createFormData(response, model) { + response = new FormData(); + for (var i = 0; i < model.length; i++) + response.append(model[i][0], model[i][1]); + return response; + } + function applyConstructor(response, model, parentObject) { + Object.setPrototypeOf(parentObject, model.prototype); + } + function defineLazyGetter(response, chunk, parentObject, key) { + "__proto__" !== key && + Object.defineProperty(parentObject, key, { + get: function () { + "resolved_model" === chunk.status && initializeModelChunk(chunk); + switch (chunk.status) { + case "fulfilled": + return chunk.value; + case "rejected": + throw chunk.reason; + } + return "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects."; + }, + set: function () {}, + enumerable: !0, + configurable: !1 + }); + return null; + } + function extractIterator(response, model) { + return model[Symbol.iterator](); + } + function createModel(response, model) { + return model; + } + function getInferredFunctionApproximate(code) { + code = code.startsWith("Object.defineProperty(") + ? code.slice(22) + : code.startsWith("(") + ? code.slice(1) + : code; + if (code.startsWith("async function")) { + var idx = code.indexOf("(", 14); + if (-1 !== idx) + return ( + (code = code.slice(14, idx).trim()), + (0, eval)("({" + JSON.stringify(code) + ":async function(){}})")[ + code + ] + ); + } else if (code.startsWith("function")) { + if (((idx = code.indexOf("(", 8)), -1 !== idx)) + return ( + (code = code.slice(8, idx).trim()), + (0, eval)("({" + JSON.stringify(code) + ":function(){}})")[code] + ); + } else if ( + code.startsWith("class") && + ((idx = code.indexOf("{", 5)), -1 !== idx) + ) + return ( + (code = code.slice(5, idx).trim()), + (0, eval)("({" + JSON.stringify(code) + ":class{}})")[code] + ); + return function () {}; + } + function parseModelString(response, parentObject, key, value) { + if ("$" === value[0]) { + if ("$" === value) + return ( + null !== initializingHandler && + "0" === key && + (initializingHandler = { + parent: initializingHandler, + chunk: null, + value: null, + reason: null, + deps: 0, + errored: !1 + }), + REACT_ELEMENT_TYPE + ); + switch (value[1]) { + case "$": + return value.slice(1); + case "L": + return ( + (parentObject = parseInt(value.slice(2), 16)), + (response = getChunk(response, parentObject)), + null !== initializingChunk && + isArrayImpl(initializingChunk._children) && + initializingChunk._children.push(response), + createLazyChunkWrapper(response, 0) + ); + case "@": + return ( + (parentObject = parseInt(value.slice(2), 16)), + (response = getChunk(response, parentObject)), + null !== initializingChunk && + isArrayImpl(initializingChunk._children) && + initializingChunk._children.push(response), + response + ); + case "w": + return; + case "S": + return Symbol.for(value.slice(2)); + case "h": + var ref = value.slice(2); + return getOutlinedModel( + response, + ref, + parentObject, + key, + loadServerReference + ); + case "T": + parentObject = "$" + value.slice(2); + response = response._tempRefs; + if (null == response) + throw Error( + "Missing a temporary reference set but the RSC response returned a temporary reference. Pass a temporaryReference option with the set that was used with the reply." + ); + return response.get(parentObject); + case "Q": + return ( + (ref = value.slice(2)), + getOutlinedModel(response, ref, parentObject, key, createMap) + ); + case "W": + return ( + (ref = value.slice(2)), + getOutlinedModel(response, ref, parentObject, key, createSet) + ); + case "B": + return ( + (ref = value.slice(2)), + getOutlinedModel(response, ref, parentObject, key, createBlob) + ); + case "K": + return ( + (ref = value.slice(2)), + getOutlinedModel(response, ref, parentObject, key, createFormData) + ); + case "Z": + return ( + (ref = value.slice(2)), + getOutlinedModel( + response, + ref, + parentObject, + key, + resolveErrorDev + ) + ); + case "i": + return ( + (ref = value.slice(2)), + getOutlinedModel( + response, + ref, + parentObject, + key, + extractIterator + ) + ); + case "I": + return Infinity; + case "-": + return "$-0" === value ? -0 : -Infinity; + case "N": + return NaN; + case "u": + return; + case "D": + return new Date(Date.parse(value.slice(2))); + case "n": + return BigInt(value.slice(2)); + case "P": + return ( + (ref = value.slice(2)), + getOutlinedModel( + response, + ref, + parentObject, + key, + applyConstructor + ) + ); + case "E": + response = value.slice(2); + try { + if (!mightHaveStaticConstructor.test(response)) + return (0, eval)(response); + } catch (x) {} + try { + if ( + ((ref = getInferredFunctionApproximate(response)), + response.startsWith("Object.defineProperty(")) + ) { + var idx = response.lastIndexOf(',"name",{value:"'); + if (-1 !== idx) { + var name = JSON.parse( + response.slice(idx + 16 - 1, response.length - 2) + ); + Object.defineProperty(ref, "name", { value: name }); + } + } + } catch (_) { + ref = function () {}; + } + return ref; + case "Y": + if ( + 2 < value.length && + (ref = response._debugChannel && response._debugChannel.callback) + ) { + if ("@" === value[2]) + return ( + (parentObject = value.slice(3)), + (key = parseInt(parentObject, 16)), + response._chunks.has(key) || ref("P:" + parentObject), + getChunk(response, key) + ); + value = value.slice(2); + idx = parseInt(value, 16); + response._chunks.has(idx) || ref("Q:" + value); + ref = getChunk(response, idx); + return "fulfilled" === ref.status + ? ref.value + : defineLazyGetter(response, ref, parentObject, key); + } + "__proto__" !== key && + Object.defineProperty(parentObject, key, { + get: function () { + return "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects."; + }, + set: function () {}, + enumerable: !0, + configurable: !1 + }); + return null; + default: + return ( + (ref = value.slice(1)), + getOutlinedModel(response, ref, parentObject, key, createModel) + ); + } + } + return value; + } + function missingCall() { + throw Error( + 'Trying to call a function from "use server" but the callServer option was not implemented in your router runtime.' + ); + } + function markIOStarted() { + this._debugIOStarted = !0; + } + function ResponseInstance( + bundlerConfig, + serverReferenceConfig, + moduleLoading, + callServer, + encodeFormAction, + nonce, + temporaryReferences, + allowPartialStream, + findSourceMapURL, + replayConsole, + environmentName, + debugStartTime, + debugEndTime, + debugChannel + ) { + var chunks = new Map(); + this._bundlerConfig = bundlerConfig; + this._serverReferenceConfig = serverReferenceConfig; + this._moduleLoading = moduleLoading; + this._callServer = void 0 !== callServer ? callServer : missingCall; + this._encodeFormAction = encodeFormAction; + this._nonce = nonce; + this._chunks = chunks; + this._stringDecoder = new util.TextDecoder(); + this._closed = !1; + this._closedReason = null; + this._allowPartialStream = allowPartialStream; + this._tempRefs = temporaryReferences; + this._timeOrigin = 0; + this._pendingInitialRender = null; + this._pendingChunks = 0; + this._weakResponse = { weak: new WeakRef(this), response: this }; + this._debugRootOwner = bundlerConfig = + void 0 === ReactSharedInteralsServer || + null === ReactSharedInteralsServer.A + ? null + : ReactSharedInteralsServer.A.getOwner(); + this._debugRootStack = + null !== bundlerConfig ? Error("react-stack-top-frame") : null; + environmentName = void 0 === environmentName ? "Server" : environmentName; + supportsCreateTask && + (this._debugRootTask = console.createTask( + '"use ' + environmentName.toLowerCase() + '"' + )); + this._debugStartTime = + null == debugStartTime ? performance.now() : debugStartTime; + this._debugIOStarted = !1; + setTimeout(markIOStarted.bind(this), 0); + this._debugEndTime = void 0 === debugEndTime ? null : debugEndTime; + this._debugFindSourceMapURL = findSourceMapURL; + this._debugChannel = debugChannel; + this._blockedConsole = null; + this._replayConsole = replayConsole; + this._rootEnvironmentName = environmentName; + debugChannel && + (null === debugChannelRegistry + ? (closeDebugChannel(debugChannel), (this._debugChannel = void 0)) + : debugChannelRegistry.register(this, debugChannel, this)); + replayConsole && markAllTracksInOrder(); + } + function createResponse( + bundlerConfig, + serverReferenceConfig, + moduleLoading, + callServer, + encodeFormAction, + nonce, + temporaryReferences, + allowPartialStream, + findSourceMapURL, + replayConsole, + environmentName, + debugStartTime, + debugEndTime, + debugChannel + ) { + checkEvalAvailabilityOnceDev(); + bundlerConfig = new ResponseInstance( + bundlerConfig, + serverReferenceConfig, + moduleLoading, + callServer, + encodeFormAction, + nonce, + temporaryReferences, + allowPartialStream, + findSourceMapURL, + replayConsole, + environmentName, + debugStartTime, + debugEndTime, + debugChannel + )._weakResponse; + return bundlerConfig; + } + function createStreamState(weakResponse, streamDebugValue) { + var streamState = { + _rowState: 0, + _rowID: 0, + _rowTag: 0, + _rowLength: 0, + _buffer: [] + }; + weakResponse = unwrapWeakResponse(weakResponse); + var debugValuePromise = Promise.resolve(streamDebugValue); + debugValuePromise.status = "fulfilled"; + debugValuePromise.value = streamDebugValue; + streamState._debugInfo = { + name: "rsc stream", + start: weakResponse._debugStartTime, + end: weakResponse._debugStartTime, + byteSize: 0, + value: debugValuePromise, + owner: weakResponse._debugRootOwner, + debugStack: weakResponse._debugRootStack, + debugTask: weakResponse._debugRootTask + }; + streamState._debugTargetChunkSize = MIN_CHUNK_SIZE; + return streamState; + } + function incrementChunkDebugInfo(streamState, chunkLength) { + var debugInfo = streamState._debugInfo, + endTime = performance.now(), + previousEndTime = debugInfo.end; + chunkLength = debugInfo.byteSize + chunkLength; + chunkLength > streamState._debugTargetChunkSize || + endTime > previousEndTime + 10 + ? ((streamState._debugInfo = { + name: debugInfo.name, + start: debugInfo.start, + end: endTime, + byteSize: chunkLength, + value: debugInfo.value, + owner: debugInfo.owner, + debugStack: debugInfo.debugStack, + debugTask: debugInfo.debugTask + }), + (streamState._debugTargetChunkSize = chunkLength + MIN_CHUNK_SIZE)) + : ((debugInfo.end = endTime), (debugInfo.byteSize = chunkLength)); + } + function addAsyncInfo(chunk, asyncInfo) { + var value = resolveLazy(chunk.value); + "object" !== typeof value || + null === value || + (!isArrayImpl(value) && + "function" !== typeof value[ASYNC_ITERATOR] && + value.$$typeof !== REACT_ELEMENT_TYPE && + value.$$typeof !== REACT_LAZY_TYPE) + ? chunk._debugInfo.push(asyncInfo) + : isArrayImpl(value._debugInfo) + ? value._debugInfo.push(asyncInfo) + : Object.isFrozen(value) || + Object.defineProperty(value, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: [asyncInfo] + }); + } + function resolveChunkDebugInfo(response, streamState, chunk) { + response._debugIOStarted && + ((response = { awaited: streamState._debugInfo }), + "pending" === chunk.status || "blocked" === chunk.status + ? ((response = addAsyncInfo.bind(null, chunk, response)), + chunk.then(response, response)) + : addAsyncInfo(chunk, response)); + } + function resolveBuffer(response, id, buffer, streamState) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk && "pending" !== chunk.status + ? chunk.reason.enqueueValue(buffer) + : (chunk && releasePendingChunk(response, chunk), + (buffer = new ReactPromise("fulfilled", buffer, null)), + resolveChunkDebugInfo(response, streamState, buffer), + chunks.set(id, buffer)); + } + function resolveModule(response, id, model, streamState) { + var chunks = response._chunks, + chunk = chunks.get(id); + model = parseModel(response, model); + var clientReference = resolveClientReference( + response._bundlerConfig, + model + ); + prepareDestinationWithChunks( + response._moduleLoading, + model[1], + response._nonce + ); + if ((model = preloadModule(clientReference))) { + if (chunk) { + releasePendingChunk(response, chunk); + var blockedChunk = chunk; + blockedChunk.status = "blocked"; + } else + (blockedChunk = new ReactPromise("blocked", null, null)), + chunks.set(id, blockedChunk); + resolveChunkDebugInfo(response, streamState, blockedChunk); + model.then( + function () { + return resolveModuleChunk(response, blockedChunk, clientReference); + }, + function (error) { + return triggerErrorOnChunk(response, blockedChunk, error); + } + ); + } else + chunk + ? (resolveChunkDebugInfo(response, streamState, chunk), + resolveModuleChunk(response, chunk, clientReference)) + : ((chunk = new ReactPromise( + "resolved_module", + clientReference, + null + )), + resolveChunkDebugInfo(response, streamState, chunk), + chunks.set(id, chunk)); + } + function resolveStream(response, id, stream, controller, streamState) { + var chunks = response._chunks, + chunk = chunks.get(id); + if (chunk) { + if ( + (resolveChunkDebugInfo(response, streamState, chunk), + "pending" === chunk.status) + ) { + id = chunk.value; + if (null != chunk._debugChunk) { + streamState = initializingHandler; + chunks = initializingChunk; + initializingHandler = null; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + initializingChunk = chunk; + try { + if ( + (initializeDebugChunk(response, chunk), + null !== initializingHandler && + !initializingHandler.errored && + 0 < initializingHandler.deps) + ) { + initializingHandler.value = stream; + initializingHandler.reason = controller; + initializingHandler.chunk = chunk; + return; + } + } finally { + (initializingHandler = streamState), (initializingChunk = chunks); + } + } + chunk.status = "fulfilled"; + chunk.value = stream; + chunk.reason = controller; + null !== id + ? wakeChunk(response, id, chunk.value, chunk) + : (filterDebugInfo(response, chunk), + moveDebugInfoFromChunkToInnerValue(chunk, stream)); + } + } else + 0 === response._pendingChunks++ && + (response._weakResponse.response = response), + (stream = new ReactPromise("fulfilled", stream, controller)), + resolveChunkDebugInfo(response, streamState, stream), + chunks.set(id, stream); + } + function startReadableStream(response, id, type, streamState) { + var controller = null, + closed = !1; + type = new ReadableStream({ + type: type, + start: function (c) { + controller = c; + } + }); + var previousBlockedChunk = null; + resolveStream( + response, + id, + type, + { + enqueueValue: function (value) { + null === previousBlockedChunk + ? controller.enqueue(value) + : previousBlockedChunk.then(function () { + controller.enqueue(value); + }); + }, + enqueueModel: function (json) { + if (null === previousBlockedChunk) { + var chunk = createResolvedModelChunk(response, json); + initializeModelChunk(chunk); + "fulfilled" === chunk.status + ? controller.enqueue(chunk.value) + : (chunk.then( + function (v) { + return controller.enqueue(v); + }, + function (e) { + return controller.error(e); + } + ), + (previousBlockedChunk = chunk)); + } else { + chunk = previousBlockedChunk; + var _chunk4 = createPendingChunk(response); + _chunk4.then( + function (v) { + return controller.enqueue(v); + }, + function (e) { + return controller.error(e); + } + ); + previousBlockedChunk = _chunk4; + chunk.then(function () { + previousBlockedChunk === _chunk4 && + (previousBlockedChunk = null); + resolveModelChunk(response, _chunk4, json); + }); + } + }, + close: function () { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.close(); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.close(); + }); + } + }, + error: function (error) { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.error(error); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.error(error); + }); + } + } + }, + streamState + ); + } + function asyncIterator() { + return this; + } + function createIterator(next) { + next = { next: next }; + next[ASYNC_ITERATOR] = asyncIterator; + return next; + } + function startAsyncIterable(response, id, iterator, streamState) { + var buffer = [], + closed = !1, + nextWriteIndex = 0, + iterable = {}; + iterable[ASYNC_ITERATOR] = function () { + var nextReadIndex = 0; + return createIterator(function (arg) { + if (void 0 !== arg) + throw Error( + "Values cannot be passed to next() of AsyncIterables passed to Client Components." + ); + if (nextReadIndex === buffer.length) { + if (closed) + return new ReactPromise( + "fulfilled", + { done: !0, value: void 0 }, + null + ); + buffer[nextReadIndex] = createPendingChunk(response); + } + return buffer[nextReadIndex++]; + }); + }; + resolveStream( + response, + id, + iterator ? iterable[ASYNC_ITERATOR]() : iterable, + { + enqueueValue: function (value) { + if (nextWriteIndex === buffer.length) + buffer[nextWriteIndex] = new ReactPromise( + "fulfilled", + { done: !1, value: value }, + null + ); + else { + var chunk = buffer[nextWriteIndex], + resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "fulfilled"; + chunk.value = { done: !1, value: value }; + chunk.reason = null; + null !== resolveListeners && + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + ); + } + nextWriteIndex++; + }, + enqueueModel: function (value) { + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !1 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !1 + ); + nextWriteIndex++; + }, + close: function (value) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = + createResolvedIteratorResultChunk(response, value, !0)) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !0 + ), + nextWriteIndex++; + nextWriteIndex < buffer.length; + + ) + resolveIteratorResultChunk( + response, + buffer[nextWriteIndex++], + '"$undefined"', + !0 + ); + }, + error: function (error) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length && + (buffer[nextWriteIndex] = createPendingChunk(response)); + nextWriteIndex < buffer.length; + + ) + triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); + } + }, + streamState + ); + } + function resolveErrorDev(response, errorInfo) { + var name = errorInfo.name, + message = errorInfo.message, + stack = errorInfo.stack, + env = errorInfo.env, + errorOptions = + "cause" in errorInfo + ? { + cause: reviveModel( + response, + errorInfo.cause, + errorInfo, + "cause" + ) + } + : void 0, + isAggregateError = + "undefined" !== typeof AggregateError && "errors" in errorInfo, + revivedErrors = isAggregateError + ? reviveModel(response, errorInfo.errors, errorInfo, "errors") + : null; + message = buildFakeCallStack( + response, + stack, + env, + !1, + isAggregateError + ? AggregateError.bind( + null, + revivedErrors, + message || + "An error occurred in the Server Components render but no message was provided", + errorOptions + ) + : Error.bind( + null, + message || + "An error occurred in the Server Components render but no message was provided", + errorOptions + ) + ); + stack = null; + null != errorInfo.owner && + ((errorInfo = errorInfo.owner.slice(1)), + (errorInfo = getOutlinedModel( + response, + errorInfo, + {}, + "", + createModel + )), + null !== errorInfo && + (stack = initializeFakeTask(response, errorInfo))); + null === stack + ? ((response = getRootTask(response, env)), + (response = null != response ? response.run(message) : message())) + : (response = stack.run(message)); + response.name = name; + response.environmentName = env; + return response; + } + function createFakeFunction( + name, + filename, + sourceMap, + line, + col, + enclosingLine, + enclosingCol, + environmentName + ) { + name || (name = ""); + var encodedName = JSON.stringify(name); + 1 > enclosingLine ? (enclosingLine = 0) : enclosingLine--; + 1 > enclosingCol ? (enclosingCol = 0) : enclosingCol--; + 1 > line ? (line = 0) : line--; + 1 > col ? (col = 0) : col--; + if ( + line < enclosingLine || + (line === enclosingLine && col < enclosingCol) + ) + enclosingCol = enclosingLine = 0; + 1 > line + ? ((line = encodedName.length + 3), + (enclosingCol -= line), + 0 > enclosingCol && (enclosingCol = 0), + (col = col - enclosingCol - line - 3), + 0 > col && (col = 0), + (encodedName = + "({" + + encodedName + + ":" + + " ".repeat(enclosingCol) + + "_=>" + + " ".repeat(col) + + "_()})")) + : 1 > enclosingLine + ? ((enclosingCol -= encodedName.length + 3), + 0 > enclosingCol && (enclosingCol = 0), + (encodedName = + "({" + + encodedName + + ":" + + " ".repeat(enclosingCol) + + "_=>" + + "\n".repeat(line - enclosingLine) + + " ".repeat(col) + + "_()})")) + : enclosingLine === line + ? ((col = col - enclosingCol - 3), + 0 > col && (col = 0), + (encodedName = + "\n".repeat(enclosingLine - 1) + + "({" + + encodedName + + ":\n" + + " ".repeat(enclosingCol) + + "_=>" + + " ".repeat(col) + + "_()})")) + : (encodedName = + "\n".repeat(enclosingLine - 1) + + "({" + + encodedName + + ":\n" + + " ".repeat(enclosingCol) + + "_=>" + + "\n".repeat(line - enclosingLine) + + " ".repeat(col) + + "_()})"); + encodedName = + 1 > enclosingLine + ? encodedName + + "\n/* This module was rendered by a Server Component. Turn on Source Maps to see the server source. */" + : "/* This module was rendered by a Server Component. Turn on Source Maps to see the server source. */" + + encodedName; + filename.startsWith("/") && (filename = "file://" + filename); + sourceMap + ? ((encodedName += + "\n//# sourceURL=about://React/" + + encodeURIComponent(environmentName) + + "/" + + encodeURI(filename) + + "?" + + fakeFunctionIdx++), + (encodedName += "\n//# sourceMappingURL=" + sourceMap)) + : (encodedName = filename + ? encodedName + ("\n//# sourceURL=" + encodeURI(filename)) + : encodedName + "\n//# sourceURL="); + try { + var fn = (0, eval)(encodedName)[name]; + } catch (x) { + (fn = function (_) { + return _(); + }), + Object.defineProperty(fn, "name", { value: name }); + } + return fn; + } + function buildFakeCallStack( + response, + stack, + environmentName, + useEnclosingLine, + innerCall + ) { + for (var i = 0; i < stack.length; i++) { + var frame = stack[i], + frameKey = + frame.join("-") + + "-" + + environmentName + + (useEnclosingLine ? "-e" : "-n"), + fn = fakeFunctionCache.get(frameKey); + if (void 0 === fn) { + fn = frame[0]; + var filename = frame[1], + line = frame[2], + col = frame[3], + enclosingLine = frame[4]; + frame = frame[5]; + var findSourceMapURL = response._debugFindSourceMapURL; + findSourceMapURL = findSourceMapURL + ? findSourceMapURL(filename, environmentName) + : null; + fn = createFakeFunction( + fn, + filename, + findSourceMapURL, + line, + col, + useEnclosingLine ? line : enclosingLine, + useEnclosingLine ? col : frame, + environmentName + ); + fakeFunctionCache.set(frameKey, fn); + } + innerCall = fn.bind(null, innerCall); + } + return innerCall; + } + function getRootTask(response, childEnvironmentName) { + var rootTask = response._debugRootTask; + return rootTask + ? response._rootEnvironmentName !== childEnvironmentName + ? ((response = console.createTask.bind( + console, + '"use ' + childEnvironmentName.toLowerCase() + '"' + )), + rootTask.run(response)) + : rootTask + : null; + } + function initializeFakeTask(response, debugInfo) { + if (!supportsCreateTask || null == debugInfo.stack) return null; + var cachedEntry = debugInfo.debugTask; + if (void 0 !== cachedEntry) return cachedEntry; + var useEnclosingLine = void 0 === debugInfo.key, + stack = debugInfo.stack, + env = + null == debugInfo.env ? response._rootEnvironmentName : debugInfo.env; + cachedEntry = + null == debugInfo.owner || null == debugInfo.owner.env + ? response._rootEnvironmentName + : debugInfo.owner.env; + var ownerTask = + null == debugInfo.owner + ? null + : initializeFakeTask(response, debugInfo.owner); + env = + env !== cachedEntry + ? '"use ' + env.toLowerCase() + '"' + : void 0 !== debugInfo.key + ? "<" + (debugInfo.name || "...") + ">" + : void 0 !== debugInfo.name + ? debugInfo.name || "unknown" + : "await " + (debugInfo.awaited.name || "unknown"); + env = console.createTask.bind(console, env); + useEnclosingLine = buildFakeCallStack( + response, + stack, + cachedEntry, + useEnclosingLine, + env + ); + null === ownerTask + ? ((response = getRootTask(response, cachedEntry)), + (response = + null != response + ? response.run(useEnclosingLine) + : useEnclosingLine())) + : (response = ownerTask.run(useEnclosingLine)); + return (debugInfo.debugTask = response); + } + function fakeJSXCallSite() { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = ownerStackTraceLimit; + var error = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + return error; + } + function initializeFakeStack(response, debugInfo) { + if (void 0 === debugInfo.debugStack) { + null != debugInfo.stack && + (debugInfo.debugStack = createFakeJSXCallStackInDEV( + response, + debugInfo.stack, + null == debugInfo.env ? "" : debugInfo.env + )); + var owner = debugInfo.owner; + null != owner && + (initializeFakeStack(response, owner), + void 0 === owner.debugLocation && + null != debugInfo.debugStack && + (owner.debugLocation = debugInfo.debugStack)); + } + } + function initializeDebugInfo(response, debugInfo) { + void 0 !== debugInfo.stack && initializeFakeTask(response, debugInfo); + if (null == debugInfo.owner && null != response._debugRootOwner) { + var _componentInfoOrAsyncInfo = debugInfo; + _componentInfoOrAsyncInfo.owner = response._debugRootOwner; + _componentInfoOrAsyncInfo.stack = null; + _componentInfoOrAsyncInfo.debugStack = response._debugRootStack; + _componentInfoOrAsyncInfo.debugTask = response._debugRootTask; + } else + void 0 !== debugInfo.stack && initializeFakeStack(response, debugInfo); + "number" === typeof debugInfo.time && + (debugInfo = { time: debugInfo.time + response._timeOrigin }); + return debugInfo; + } + function getCurrentStackInDEV() { + var owner = currentOwnerInDEV; + if (null === owner) return ""; + try { + var info = ""; + if (owner.owner || "string" !== typeof owner.name) { + for (; owner; ) { + var ownerStack = owner.debugStack; + if (null != ownerStack) { + if ((owner = owner.owner)) { + var JSCompiler_temp_const = info; + var error = ownerStack, + prevPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = prepareStackTrace; + var stack = error.stack; + Error.prepareStackTrace = prevPrepareStackTrace; + stack.startsWith("Error: react-stack-top-frame\n") && + (stack = stack.slice(29)); + var idx = stack.indexOf("\n"); + -1 !== idx && (stack = stack.slice(idx + 1)); + idx = stack.indexOf("react_stack_bottom_frame"); + -1 !== idx && (idx = stack.lastIndexOf("\n", idx)); + var JSCompiler_inline_result = + -1 !== idx ? (stack = stack.slice(0, idx)) : ""; + info = + JSCompiler_temp_const + ("\n" + JSCompiler_inline_result); + } + } else break; + } + var JSCompiler_inline_result$jscomp$0 = info; + } else { + JSCompiler_temp_const = owner.name; + if (void 0 === prefix) + try { + throw Error(); + } catch (x) { + (prefix = + ((error = x.stack.trim().match(/\n( *(at )?)/)) && error[1]) || + ""), + (suffix = + -1 < x.stack.indexOf("\n at") + ? " ()" + : -1 < x.stack.indexOf("@") + ? "@unknown:0:0" + : ""); + } + JSCompiler_inline_result$jscomp$0 = + "\n" + prefix + JSCompiler_temp_const + suffix; + } + } catch (x) { + JSCompiler_inline_result$jscomp$0 = + "\nError generating stack: " + x.message + "\n" + x.stack; + } + return JSCompiler_inline_result$jscomp$0; + } + function resolveConsoleEntry(response, json) { + if (response._replayConsole) { + var blockedChunk = response._blockedConsole; + if (null == blockedChunk) + (blockedChunk = createResolvedModelChunk(response, json)), + initializeModelChunk(blockedChunk), + "fulfilled" === blockedChunk.status + ? replayConsoleWithCallStackInDEV(response, blockedChunk.value) + : (blockedChunk.then( + function (v) { + return replayConsoleWithCallStackInDEV(response, v); + }, + function () {} + ), + (response._blockedConsole = blockedChunk)); + else { + var _chunk5 = createPendingChunk(response); + _chunk5.then( + function (v) { + return replayConsoleWithCallStackInDEV(response, v); + }, + function () {} + ); + response._blockedConsole = _chunk5; + var unblock = function () { + response._blockedConsole === _chunk5 && + (response._blockedConsole = null); + resolveModelChunk(response, _chunk5, json); + }; + blockedChunk.then(unblock, unblock); + } + } + } + function initializeIOInfo(response, ioInfo) { + void 0 !== ioInfo.stack && + (initializeFakeTask(response, ioInfo), + initializeFakeStack(response, ioInfo)); + ioInfo.start += response._timeOrigin; + ioInfo.end += response._timeOrigin; + if (response._replayConsole) { + response = response._rootEnvironmentName; + var promise = ioInfo.value; + if (promise) + switch (promise.status) { + case "fulfilled": + logIOInfo(ioInfo, response, promise.value); + break; + case "rejected": + logIOInfoErrored(ioInfo, response, promise.reason); + break; + default: + promise.then( + logIOInfo.bind(null, ioInfo, response), + logIOInfoErrored.bind(null, ioInfo, response) + ); + } + else logIOInfo(ioInfo, response, void 0); + } + } + function resolveIOInfo(response, id, model) { + var chunks = response._chunks, + chunk = chunks.get(id), + prevIsInitializingDebugInfo = isInitializingDebugInfo; + isInitializingDebugInfo = !0; + try { + chunk + ? (resolveModelChunk(response, chunk, model), + "resolved_model" === chunk.status && initializeModelChunk(chunk)) + : ((chunk = createResolvedModelChunk(response, model)), + chunks.set(id, chunk), + initializeModelChunk(chunk)); + } finally { + isInitializingDebugInfo = prevIsInitializingDebugInfo; + } + "fulfilled" === chunk.status + ? initializeIOInfo(response, chunk.value) + : chunk.then( + function (v) { + initializeIOInfo(response, v); + }, + function () {} + ); + } + function mergeBuffer(buffer, lastChunk) { + for ( + var l = buffer.length, byteLength = lastChunk.length, i = 0; + i < l; + i++ + ) + byteLength += buffer[i].byteLength; + byteLength = new Uint8Array(byteLength); + for (var _i3 = (i = 0); _i3 < l; _i3++) { + var chunk = buffer[_i3]; + byteLength.set(chunk, i); + i += chunk.byteLength; + } + byteLength.set(lastChunk, i); + return byteLength; + } + function resolveTypedArray( + response, + id, + buffer, + lastChunk, + constructor, + bytesPerElement, + streamState + ) { + buffer = + 0 === buffer.length && 0 === lastChunk.byteOffset % bytesPerElement + ? lastChunk + : mergeBuffer(buffer, lastChunk); + constructor = new constructor( + buffer.buffer, + buffer.byteOffset, + buffer.byteLength / bytesPerElement + ); + resolveBuffer(response, id, constructor, streamState); + } + function flushComponentPerformance( + response$jscomp$0, + root, + trackIdx$jscomp$6, + trackTime, + parentEndTime + ) { + if (!isArrayImpl(root._children)) { + var previousResult = root._children, + previousEndTime = previousResult.endTime; + if ( + -Infinity < parentEndTime && + parentEndTime < previousEndTime && + null !== previousResult.component + ) { + var componentInfo = previousResult.component, + trackIdx = trackIdx$jscomp$6, + startTime = parentEndTime; + if (supportsUserTiming && 0 <= previousEndTime && 10 > trackIdx) { + var color = + componentInfo.env === response$jscomp$0._rootEnvironmentName + ? "primary-light" + : "secondary-light", + entryName = componentInfo.name + " [deduped]", + debugTask = componentInfo.debugTask; + debugTask + ? debugTask.run( + console.timeStamp.bind( + console, + entryName, + 0 > startTime ? 0 : startTime, + previousEndTime, + trackNames[trackIdx], + "Server Components \u269b", + color + ) + ) + : console.timeStamp( + entryName, + 0 > startTime ? 0 : startTime, + previousEndTime, + trackNames[trackIdx], + "Server Components \u269b", + color + ); + } + } + previousResult.track = trackIdx$jscomp$6; + return previousResult; + } + var children = root._children; + var debugInfo = root._debugInfo; + if (0 === debugInfo.length && "fulfilled" === root.status) { + var resolvedValue = resolveLazy(root.value); + "object" === typeof resolvedValue && + null !== resolvedValue && + (isArrayImpl(resolvedValue) || + "function" === typeof resolvedValue[ASYNC_ITERATOR] || + resolvedValue.$$typeof === REACT_ELEMENT_TYPE || + resolvedValue.$$typeof === REACT_LAZY_TYPE) && + isArrayImpl(resolvedValue._debugInfo) && + (debugInfo = resolvedValue._debugInfo); + } + if (debugInfo) { + for (var startTime$jscomp$0 = 0, i = 0; i < debugInfo.length; i++) { + var info = debugInfo[i]; + "number" === typeof info.time && (startTime$jscomp$0 = info.time); + if ("string" === typeof info.name) { + startTime$jscomp$0 < trackTime && trackIdx$jscomp$6++; + trackTime = startTime$jscomp$0; + break; + } + } + for (var _i4 = debugInfo.length - 1; 0 <= _i4; _i4--) { + var _info = debugInfo[_i4]; + if ("number" === typeof _info.time && _info.time > parentEndTime) { + parentEndTime = _info.time; + break; + } + } + } + var result = { + track: trackIdx$jscomp$6, + endTime: -Infinity, + component: null + }; + root._children = result; + for ( + var childrenEndTime = -Infinity, + childTrackIdx = trackIdx$jscomp$6, + childTrackTime = trackTime, + _i5 = 0; + _i5 < children.length; + _i5++ + ) { + var childResult = flushComponentPerformance( + response$jscomp$0, + children[_i5], + childTrackIdx, + childTrackTime, + parentEndTime + ); + null !== childResult.component && + (result.component = childResult.component); + childTrackIdx = childResult.track; + var childEndTime = childResult.endTime; + childEndTime > childTrackTime && (childTrackTime = childEndTime); + childEndTime > childrenEndTime && (childrenEndTime = childEndTime); + } + if (debugInfo) + for ( + var componentEndTime = 0, + isLastComponent = !0, + endTime = -1, + endTimeIdx = -1, + _i6 = debugInfo.length - 1; + 0 <= _i6; + _i6-- + ) { + var _info2 = debugInfo[_i6]; + if ("number" === typeof _info2.time) { + 0 === componentEndTime && (componentEndTime = _info2.time); + var time = _info2.time; + if (-1 < endTimeIdx) + for (var j = endTimeIdx - 1; j > _i6; j--) { + var candidateInfo = debugInfo[j]; + if ("string" === typeof candidateInfo.name) { + componentEndTime > childrenEndTime && + (childrenEndTime = componentEndTime); + var componentInfo$jscomp$0 = candidateInfo, + response = response$jscomp$0, + componentInfo$jscomp$1 = componentInfo$jscomp$0, + trackIdx$jscomp$0 = trackIdx$jscomp$6, + startTime$jscomp$1 = time, + componentEndTime$jscomp$0 = componentEndTime, + childrenEndTime$jscomp$0 = childrenEndTime; + if ( + isLastComponent && + "rejected" === root.status && + root.reason !== response._closedReason + ) { + var componentInfo$jscomp$2 = componentInfo$jscomp$1, + trackIdx$jscomp$1 = trackIdx$jscomp$0, + startTime$jscomp$2 = startTime$jscomp$1, + childrenEndTime$jscomp$1 = childrenEndTime$jscomp$0, + error = root.reason; + if (supportsUserTiming) { + var env = componentInfo$jscomp$2.env, + name = componentInfo$jscomp$2.name, + entryName$jscomp$0 = + env === response._rootEnvironmentName || + void 0 === env + ? name + : name + " [" + env + "]", + measureName = "\u200b" + entryName$jscomp$0, + properties = [ + [ + "Error", + "object" === typeof error && + null !== error && + "string" === typeof error.message + ? String(error.message) + : String(error) + ] + ]; + null != componentInfo$jscomp$2.key && + addValueToProperties( + "key", + componentInfo$jscomp$2.key, + properties, + 0, + "" + ); + null != componentInfo$jscomp$2.props && + addObjectToProperties( + componentInfo$jscomp$2.props, + properties, + 0, + "" + ); + performance.measure(measureName, { + start: 0 > startTime$jscomp$2 ? 0 : startTime$jscomp$2, + end: childrenEndTime$jscomp$1, + detail: { + devtools: { + color: "error", + track: trackNames[trackIdx$jscomp$1], + trackGroup: "Server Components \u269b", + tooltipText: entryName$jscomp$0 + " Errored", + properties: properties + } + } + }); + performance.clearMeasures(measureName); + } + } else { + var componentInfo$jscomp$3 = componentInfo$jscomp$1, + trackIdx$jscomp$2 = trackIdx$jscomp$0, + startTime$jscomp$3 = startTime$jscomp$1, + childrenEndTime$jscomp$2 = childrenEndTime$jscomp$0; + if ( + supportsUserTiming && + 0 <= childrenEndTime$jscomp$2 && + 10 > trackIdx$jscomp$2 + ) { + var env$jscomp$0 = componentInfo$jscomp$3.env, + name$jscomp$0 = componentInfo$jscomp$3.name, + isPrimaryEnv = + env$jscomp$0 === response._rootEnvironmentName, + selfTime = + componentEndTime$jscomp$0 - startTime$jscomp$3, + color$jscomp$0 = + 0.5 > selfTime + ? isPrimaryEnv + ? "primary-light" + : "secondary-light" + : 50 > selfTime + ? isPrimaryEnv + ? "primary" + : "secondary" + : 500 > selfTime + ? isPrimaryEnv + ? "primary-dark" + : "secondary-dark" + : "error", + debugTask$jscomp$0 = componentInfo$jscomp$3.debugTask, + measureName$jscomp$0 = + "\u200b" + + (isPrimaryEnv || void 0 === env$jscomp$0 + ? name$jscomp$0 + : name$jscomp$0 + " [" + env$jscomp$0 + "]"); + if (debugTask$jscomp$0) { + var properties$jscomp$0 = []; + null != componentInfo$jscomp$3.key && + addValueToProperties( + "key", + componentInfo$jscomp$3.key, + properties$jscomp$0, + 0, + "" + ); + null != componentInfo$jscomp$3.props && + addObjectToProperties( + componentInfo$jscomp$3.props, + properties$jscomp$0, + 0, + "" + ); + debugTask$jscomp$0.run( + performance.measure.bind( + performance, + measureName$jscomp$0, + { + start: + 0 > startTime$jscomp$3 ? 0 : startTime$jscomp$3, + end: childrenEndTime$jscomp$2, + detail: { + devtools: { + color: color$jscomp$0, + track: trackNames[trackIdx$jscomp$2], + trackGroup: "Server Components \u269b", + properties: properties$jscomp$0 + } + } + } + ) + ); + performance.clearMeasures(measureName$jscomp$0); + } else + console.timeStamp( + measureName$jscomp$0, + 0 > startTime$jscomp$3 ? 0 : startTime$jscomp$3, + childrenEndTime$jscomp$2, + trackNames[trackIdx$jscomp$2], + "Server Components \u269b", + color$jscomp$0 + ); + } + } + componentEndTime = time; + result.component = componentInfo$jscomp$0; + isLastComponent = !1; + } else if ( + candidateInfo.awaited && + null != candidateInfo.awaited.env + ) { + endTime > childrenEndTime && (childrenEndTime = endTime); + var asyncInfo = candidateInfo, + env$jscomp$1 = response$jscomp$0._rootEnvironmentName, + promise = asyncInfo.awaited.value; + if (promise) { + var thenable = promise; + switch (thenable.status) { + case "fulfilled": + logComponentAwait( + asyncInfo, + trackIdx$jscomp$6, + time, + endTime, + env$jscomp$1, + thenable.value + ); + break; + case "rejected": + var asyncInfo$jscomp$0 = asyncInfo, + trackIdx$jscomp$3 = trackIdx$jscomp$6, + startTime$jscomp$4 = time, + endTime$jscomp$0 = endTime, + rootEnv = env$jscomp$1, + error$jscomp$0 = thenable.reason; + if (supportsUserTiming && 0 < endTime$jscomp$0) { + var description = getIODescription(error$jscomp$0), + entryName$jscomp$1 = + "await " + + getIOShortName( + asyncInfo$jscomp$0.awaited, + description, + asyncInfo$jscomp$0.env, + rootEnv + ), + debugTask$jscomp$1 = + asyncInfo$jscomp$0.debugTask || + asyncInfo$jscomp$0.awaited.debugTask; + if (debugTask$jscomp$1) { + var properties$jscomp$1 = [ + [ + "Rejected", + "object" === typeof error$jscomp$0 && + null !== error$jscomp$0 && + "string" === typeof error$jscomp$0.message + ? String(error$jscomp$0.message) + : String(error$jscomp$0) + ] + ], + tooltipText = + getIOLongName( + asyncInfo$jscomp$0.awaited, + description, + asyncInfo$jscomp$0.env, + rootEnv + ) + " Rejected"; + debugTask$jscomp$1.run( + performance.measure.bind( + performance, + entryName$jscomp$1, + { + start: + 0 > startTime$jscomp$4 + ? 0 + : startTime$jscomp$4, + end: endTime$jscomp$0, + detail: { + devtools: { + color: "error", + track: trackNames[trackIdx$jscomp$3], + trackGroup: "Server Components \u269b", + properties: properties$jscomp$1, + tooltipText: tooltipText + } + } + } + ) + ); + performance.clearMeasures(entryName$jscomp$1); + } else + console.timeStamp( + entryName$jscomp$1, + 0 > startTime$jscomp$4 ? 0 : startTime$jscomp$4, + endTime$jscomp$0, + trackNames[trackIdx$jscomp$3], + "Server Components \u269b", + "error" + ); + } + break; + default: + logComponentAwait( + asyncInfo, + trackIdx$jscomp$6, + time, + endTime, + env$jscomp$1, + void 0 + ); + } + } else + logComponentAwait( + asyncInfo, + trackIdx$jscomp$6, + time, + endTime, + env$jscomp$1, + void 0 + ); + } + } + else { + endTime = time; + for (var _j = debugInfo.length - 1; _j > _i6; _j--) { + var _candidateInfo = debugInfo[_j]; + if ("string" === typeof _candidateInfo.name) { + componentEndTime > childrenEndTime && + (childrenEndTime = componentEndTime); + var _componentInfo = _candidateInfo, + _env = response$jscomp$0._rootEnvironmentName, + componentInfo$jscomp$4 = _componentInfo, + trackIdx$jscomp$4 = trackIdx$jscomp$6, + startTime$jscomp$5 = time, + childrenEndTime$jscomp$3 = childrenEndTime; + if (supportsUserTiming) { + var env$jscomp$2 = componentInfo$jscomp$4.env, + name$jscomp$1 = componentInfo$jscomp$4.name, + entryName$jscomp$2 = + env$jscomp$2 === _env || void 0 === env$jscomp$2 + ? name$jscomp$1 + : name$jscomp$1 + " [" + env$jscomp$2 + "]", + measureName$jscomp$1 = "\u200b" + entryName$jscomp$2, + properties$jscomp$2 = [ + [ + "Aborted", + "The stream was aborted before this Component finished rendering." + ] + ]; + null != componentInfo$jscomp$4.key && + addValueToProperties( + "key", + componentInfo$jscomp$4.key, + properties$jscomp$2, + 0, + "" + ); + null != componentInfo$jscomp$4.props && + addObjectToProperties( + componentInfo$jscomp$4.props, + properties$jscomp$2, + 0, + "" + ); + performance.measure(measureName$jscomp$1, { + start: 0 > startTime$jscomp$5 ? 0 : startTime$jscomp$5, + end: childrenEndTime$jscomp$3, + detail: { + devtools: { + color: "warning", + track: trackNames[trackIdx$jscomp$4], + trackGroup: "Server Components \u269b", + tooltipText: entryName$jscomp$2 + " Aborted", + properties: properties$jscomp$2 + } + } + }); + performance.clearMeasures(measureName$jscomp$1); + } + componentEndTime = time; + result.component = _componentInfo; + isLastComponent = !1; + } else if ( + _candidateInfo.awaited && + null != _candidateInfo.awaited.env + ) { + var _asyncInfo = _candidateInfo, + _env2 = response$jscomp$0._rootEnvironmentName; + _asyncInfo.awaited.end > endTime && + (endTime = _asyncInfo.awaited.end); + endTime > childrenEndTime && (childrenEndTime = endTime); + var asyncInfo$jscomp$1 = _asyncInfo, + trackIdx$jscomp$5 = trackIdx$jscomp$6, + startTime$jscomp$6 = time, + endTime$jscomp$1 = endTime, + rootEnv$jscomp$0 = _env2; + if (supportsUserTiming && 0 < endTime$jscomp$1) { + var entryName$jscomp$3 = + "await " + + getIOShortName( + asyncInfo$jscomp$1.awaited, + "", + asyncInfo$jscomp$1.env, + rootEnv$jscomp$0 + ), + debugTask$jscomp$2 = + asyncInfo$jscomp$1.debugTask || + asyncInfo$jscomp$1.awaited.debugTask; + if (debugTask$jscomp$2) { + var tooltipText$jscomp$0 = + getIOLongName( + asyncInfo$jscomp$1.awaited, + "", + asyncInfo$jscomp$1.env, + rootEnv$jscomp$0 + ) + " Aborted"; + debugTask$jscomp$2.run( + performance.measure.bind( + performance, + entryName$jscomp$3, + { + start: + 0 > startTime$jscomp$6 ? 0 : startTime$jscomp$6, + end: endTime$jscomp$1, + detail: { + devtools: { + color: "warning", + track: trackNames[trackIdx$jscomp$5], + trackGroup: "Server Components \u269b", + properties: [ + [ + "Aborted", + "The stream was aborted before this Promise resolved." + ] + ], + tooltipText: tooltipText$jscomp$0 + } + } + } + ) + ); + performance.clearMeasures(entryName$jscomp$3); + } else + console.timeStamp( + entryName$jscomp$3, + 0 > startTime$jscomp$6 ? 0 : startTime$jscomp$6, + endTime$jscomp$1, + trackNames[trackIdx$jscomp$5], + "Server Components \u269b", + "warning" + ); + } + } + } + } + endTime = time; + endTimeIdx = _i6; + } + } + result.endTime = childrenEndTime; + return result; + } + function flushInitialRenderPerformance(response) { + if (response._replayConsole) { + var rootChunk = getChunk(response, 0); + isArrayImpl(rootChunk._children) && + (markAllTracksInOrder(), + flushComponentPerformance( + response, + rootChunk, + 0, + -Infinity, + -Infinity + )); + } + } + function processFullBinaryRow( + response, + streamState, + id, + tag, + buffer, + chunk + ) { + switch (tag) { + case 65: + resolveBuffer( + response, + id, + mergeBuffer(buffer, chunk).buffer, + streamState + ); + return; + case 79: + resolveTypedArray( + response, + id, + buffer, + chunk, + Int8Array, + 1, + streamState + ); + return; + case 111: + resolveBuffer( + response, + id, + 0 === buffer.length ? chunk : mergeBuffer(buffer, chunk), + streamState + ); + return; + case 85: + resolveTypedArray( + response, + id, + buffer, + chunk, + Uint8ClampedArray, + 1, + streamState + ); + return; + case 83: + resolveTypedArray( + response, + id, + buffer, + chunk, + Int16Array, + 2, + streamState + ); + return; + case 115: + resolveTypedArray( + response, + id, + buffer, + chunk, + Uint16Array, + 2, + streamState + ); + return; + case 76: + resolveTypedArray( + response, + id, + buffer, + chunk, + Int32Array, + 4, + streamState + ); + return; + case 108: + resolveTypedArray( + response, + id, + buffer, + chunk, + Uint32Array, + 4, + streamState + ); + return; + case 71: + resolveTypedArray( + response, + id, + buffer, + chunk, + Float32Array, + 4, + streamState + ); + return; + case 103: + resolveTypedArray( + response, + id, + buffer, + chunk, + Float64Array, + 8, + streamState + ); + return; + case 77: + resolveTypedArray( + response, + id, + buffer, + chunk, + BigInt64Array, + 8, + streamState + ); + return; + case 109: + resolveTypedArray( + response, + id, + buffer, + chunk, + BigUint64Array, + 8, + streamState + ); + return; + case 86: + resolveTypedArray( + response, + id, + buffer, + chunk, + DataView, + 1, + streamState + ); + return; + } + for ( + var stringDecoder = response._stringDecoder, row = "", i = 0; + i < buffer.length; + i++ + ) + row += stringDecoder.decode(buffer[i], decoderOptions); + row += stringDecoder.decode(chunk); + processFullStringRow(response, streamState, id, tag, row); + } + function processFullStringRow(response, streamState, id, tag, row) { + switch (tag) { + case 73: + resolveModule(response, id, row, streamState); + break; + case 72: + id = row[0]; + streamState = row.slice(1); + response = parseModel(response, streamState); + streamState = ReactDOMSharedInternals.d; + switch (id) { + case "D": + streamState.D(response); + break; + case "C": + "string" === typeof response + ? streamState.C(response) + : streamState.C(response[0], response[1]); + break; + case "L": + id = response[0]; + row = response[1]; + 3 === response.length + ? streamState.L(id, row, response[2]) + : streamState.L(id, row); + break; + case "m": + "string" === typeof response + ? streamState.m(response) + : streamState.m(response[0], response[1]); + break; + case "X": + "string" === typeof response + ? streamState.X(response) + : streamState.X(response[0], response[1]); + break; + case "S": + "string" === typeof response + ? streamState.S(response) + : streamState.S( + response[0], + 0 === response[1] ? void 0 : response[1], + 3 === response.length ? response[2] : void 0 + ); + break; + case "M": + "string" === typeof response + ? streamState.M(response) + : streamState.M(response[0], response[1]); + } + break; + case 69: + tag = response._chunks; + var chunk = tag.get(id); + row = JSON.parse(row); + var error = resolveErrorDev(response, row); + error.digest = row.digest; + chunk + ? (resolveChunkDebugInfo(response, streamState, chunk), + triggerErrorOnChunk(response, chunk, error)) + : ((row = new ReactPromise("rejected", null, error)), + resolveChunkDebugInfo(response, streamState, row), + tag.set(id, row)); + break; + case 84: + tag = response._chunks; + (chunk = tag.get(id)) && "pending" !== chunk.status + ? chunk.reason.enqueueValue(row) + : (chunk && releasePendingChunk(response, chunk), + (row = new ReactPromise("fulfilled", row, null)), + resolveChunkDebugInfo(response, streamState, row), + tag.set(id, row)); + break; + case 78: + response._timeOrigin = +row - performance.timeOrigin; + break; + case 68: + id = getChunk(response, id); + "fulfilled" !== id.status && + "rejected" !== id.status && + "halted" !== id.status && + "blocked" !== id.status && + "resolved_module" !== id.status && + ((streamState = id._debugChunk), + (tag = createResolvedModelChunk(response, row)), + (tag._debugChunk = streamState), + (id._debugChunk = tag), + initializeDebugChunk(response, id), + "blocked" !== tag.status || + (void 0 !== response._debugChannel && + response._debugChannel.hasReadable) || + '"' !== row[0] || + "$" !== row[1] || + ((streamState = row.slice(2, row.length - 1).split(":")), + (streamState = parseInt(streamState[0], 16)), + "pending" === getChunk(response, streamState).status && + (id._debugChunk = null))); + break; + case 74: + resolveIOInfo(response, id, row); + break; + case 87: + resolveConsoleEntry(response, row); + break; + case 82: + startReadableStream(response, id, void 0, streamState); + break; + case 114: + startReadableStream(response, id, "bytes", streamState); + break; + case 88: + startAsyncIterable(response, id, !1, streamState); + break; + case 120: + startAsyncIterable(response, id, !0, streamState); + break; + case 67: + (id = response._chunks.get(id)) && + "fulfilled" === id.status && + (0 === --response._pendingChunks && + (response._weakResponse.response = null), + id.reason.close("" === row ? '"$undefined"' : row)); + break; + default: + "" === row + ? ((streamState = response._chunks), + (row = streamState.get(id)) || + streamState.set(id, (row = createPendingChunk(response))), + ("pending" !== row.status && + "pending_weak" !== row.status && + "blocked" !== row.status) || + haltChunk(response, row)) + : ((tag = response._chunks), + (chunk = tag.get(id)) + ? (resolveChunkDebugInfo(response, streamState, chunk), + resolveModelChunk(response, chunk, row)) + : ((row = createResolvedModelChunk(response, row)), + resolveChunkDebugInfo(response, streamState, row), + tag.set(id, row))); + } + } + function processBinaryChunk(weakResponse, streamState, chunk) { + if (!hasGCedResponse(weakResponse)) { + weakResponse = unwrapWeakResponse(weakResponse); + var i = 0, + rowState = streamState._rowState, + rowID = streamState._rowID, + rowTag = streamState._rowTag, + rowLength = streamState._rowLength, + buffer = streamState._buffer, + chunkLength = chunk.length; + for ( + incrementChunkDebugInfo(streamState, chunkLength); + i < chunkLength; + + ) { + var lastIdx = -1; + switch (rowState) { + case 0: + lastIdx = chunk[i++]; + 58 === lastIdx + ? (rowState = 1) + : (rowID = + (rowID << 4) | + (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 1: + rowState = chunk[i]; + 84 === rowState || + 65 === rowState || + 79 === rowState || + 111 === rowState || + 98 === rowState || + 85 === rowState || + 83 === rowState || + 115 === rowState || + 76 === rowState || + 108 === rowState || + 71 === rowState || + 103 === rowState || + 77 === rowState || + 109 === rowState || + 86 === rowState + ? ((rowTag = rowState), (rowState = 2), i++) + : (64 < rowState && 91 > rowState) || + 35 === rowState || + 114 === rowState || + 120 === rowState + ? ((rowTag = rowState), (rowState = 3), i++) + : ((rowTag = 0), (rowState = 3)); + continue; + case 2: + lastIdx = chunk[i++]; + 44 === lastIdx + ? (rowState = 4) + : (rowLength = + (rowLength << 4) | + (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 3: + lastIdx = chunk.indexOf(10, i); + break; + case 4: + (lastIdx = i + rowLength), + lastIdx > chunk.length && (lastIdx = -1); + } + var offset = chunk.byteOffset + i; + if (-1 < lastIdx) + (rowLength = new Uint8Array(chunk.buffer, offset, lastIdx - i)), + 98 === rowTag + ? resolveBuffer( + weakResponse, + rowID, + lastIdx === chunkLength ? rowLength : rowLength.slice(), + streamState + ) + : processFullBinaryRow( + weakResponse, + streamState, + rowID, + rowTag, + buffer, + rowLength + ), + (i = lastIdx), + 3 === rowState && i++, + (rowLength = rowID = rowTag = rowState = 0), + (buffer.length = 0); + else { + chunk = new Uint8Array(chunk.buffer, offset, chunk.byteLength - i); + 98 === rowTag + ? ((rowLength -= chunk.byteLength), + resolveBuffer(weakResponse, rowID, chunk, streamState)) + : (buffer.push(chunk), (rowLength -= chunk.byteLength)); + break; + } + } + streamState._rowState = rowState; + streamState._rowID = rowID; + streamState._rowTag = rowTag; + streamState._rowLength = rowLength; + } + } + function parseModel(response, json) { + json = JSON.parse(json); + return reviveModel(response, json, { "": json }, ""); + } + function reviveModel(response, value, parentObject, key) { + if ("string" === typeof value) + return "$" === value[0] + ? parseModelString(response, parentObject, key, value) + : value; + if ("object" !== typeof value || null === value) return value; + if (isArrayImpl(value)) { + for (var i = 0; i < value.length; i++) + value[i] = reviveModel(response, value[i], value, "" + i); + if (value[0] === REACT_ELEMENT_TYPE) { + if (value[0] === REACT_ELEMENT_TYPE) + b: { + key = value[4]; + parentObject = value[5]; + i = value[6]; + value = { + $$typeof: REACT_ELEMENT_TYPE, + type: value[1], + key: value[2], + props: value[3], + _owner: void 0 === key ? null : key + }; + Object.defineProperty(value, "ref", { + enumerable: !1, + get: nullRefGetter + }); + value._store = {}; + Object.defineProperty(value._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: i + }); + Object.defineProperty(value, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + Object.defineProperty(value, "_debugStack", { + configurable: !1, + enumerable: !1, + writable: !0, + value: void 0 === parentObject ? null : parentObject + }); + Object.defineProperty(value, "_debugTask", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + if (null !== initializingHandler) { + key = initializingHandler; + initializingHandler = key.parent; + if (key.errored) { + parentObject = new ReactPromise("rejected", null, key.reason); + initializeElement(response, value, null); + response = { + name: getComponentNameFromType(value.type) || "", + owner: value._owner + }; + response.debugStack = value._debugStack; + supportsCreateTask && (response.debugTask = value._debugTask); + parentObject._debugInfo = [response]; + response = createLazyChunkWrapper(parentObject, i); + break b; + } + if (0 < key.deps) { + parentObject = new ReactPromise("blocked", null, null); + key.value = value; + key.chunk = parentObject; + i = createLazyChunkWrapper(parentObject, i); + response = initializeElement.bind(null, response, value, i); + parentObject.then(response, response); + response = i; + break b; + } + } + initializeElement(response, value, null); + response = value; + } + else response = value; + return response; + } + return value; + } + for (i in value) + hasOwnProperty.call(value, i) && + ("__proto__" === i + ? delete value[i] + : ((parentObject = reviveModel(response, value[i], value, i)), + void 0 !== parentObject + ? (value[i] = parentObject) + : delete value[i])); + return value; + } + function close(weakResponse) { + if (!hasGCedResponse(weakResponse)) { + var response = unwrapWeakResponse(weakResponse); + response._allowPartialStream + ? ((response._closed = !0), + response._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? haltChunk(response, chunk) + : "fulfilled" === chunk.status && + null !== chunk.reason && + chunk.reason.close('"$undefined"'); + }), + (weakResponse = response._debugChannel), + void 0 !== weakResponse && + (closeDebugChannel(weakResponse), + (response._debugChannel = void 0), + null !== debugChannelRegistry && + debugChannelRegistry.unregister(response))) + : reportGlobalError(weakResponse, Error("Connection closed.")); + } + } + function noServerCall$1() { + throw Error( + "Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead." + ); + } + function createResponseFromOptions(options) { + return createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverConsumerModuleMap, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + noServerCall$1, + options.encodeFormAction, + "string" === typeof options.nonce ? options.nonce : void 0, + options && options.temporaryReferences + ? options.temporaryReferences + : void 0, + options && options.unstable_allowPartialStream + ? options.unstable_allowPartialStream + : !1, + options && options.findSourceMapURL ? options.findSourceMapURL : void 0, + options ? !0 === options.replayConsoleLogs : !1, + options && options.environmentName ? options.environmentName : void 0, + options && null != options.startTime ? options.startTime : void 0, + options && null != options.endTime ? options.endTime : void 0, + options && void 0 !== options.debugChannel + ? { + hasReadable: void 0 !== options.debugChannel.readable, + callback: null + } + : void 0 + ); + } + function startReadingFromStream$1(response, stream, onDone, debugValue) { + function progress(_ref) { + var value = _ref.value; + if (_ref.done) return onDone(); + processBinaryChunk(response, streamState, value); + return reader.read().then(progress).catch(error); + } + function error(e) { + reportGlobalError(response, e); + } + var streamState = createStreamState(response, debugValue), + reader = stream.getReader(); + reader.read().then(progress).catch(error); + } + function noServerCall() { + throw Error( + "Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead." + ); + } + function startReadingFromStream(response$jscomp$0, stream, onEnd) { + var streamState = createStreamState(response$jscomp$0, stream); + stream.on("data", function (chunk) { + if ("string" === typeof chunk) { + if (!hasGCedResponse(response$jscomp$0)) { + var response = unwrapWeakResponse(response$jscomp$0), + i = 0, + rowState = streamState._rowState, + rowID = streamState._rowID, + rowTag = streamState._rowTag, + rowLength = streamState._rowLength, + buffer = streamState._buffer, + chunkLength = chunk.length; + for ( + incrementChunkDebugInfo(streamState, chunkLength); + i < chunkLength; + + ) { + var lastIdx = -1; + switch (rowState) { + case 0: + lastIdx = chunk.charCodeAt(i++); + 58 === lastIdx + ? (rowState = 1) + : (rowID = + (rowID << 4) | + (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 1: + rowState = chunk.charCodeAt(i); + 84 === rowState || + 65 === rowState || + 79 === rowState || + 111 === rowState || + 85 === rowState || + 83 === rowState || + 115 === rowState || + 76 === rowState || + 108 === rowState || + 71 === rowState || + 103 === rowState || + 77 === rowState || + 109 === rowState || + 86 === rowState + ? ((rowTag = rowState), (rowState = 2), i++) + : (64 < rowState && 91 > rowState) || + 114 === rowState || + 120 === rowState + ? ((rowTag = rowState), (rowState = 3), i++) + : ((rowTag = 0), (rowState = 3)); + continue; + case 2: + lastIdx = chunk.charCodeAt(i++); + 44 === lastIdx + ? (rowState = 4) + : (rowLength = + (rowLength << 4) | + (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 3: + lastIdx = chunk.indexOf("\n", i); + break; + case 4: + if (84 !== rowTag) + throw Error( + "Binary RSC chunks cannot be encoded as strings. This is a bug in the wiring of the React streams." + ); + if (rowLength < chunk.length || chunk.length > 3 * rowLength) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + lastIdx = chunk.length; + } + if (-1 < lastIdx) { + if (0 < buffer.length) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + i = chunk.slice(i, lastIdx); + processFullStringRow(response, streamState, rowID, rowTag, i); + i = lastIdx; + 3 === rowState && i++; + rowLength = rowID = rowTag = rowState = 0; + buffer.length = 0; + } else if (chunk.length !== i) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + } + streamState._rowState = rowState; + streamState._rowID = rowID; + streamState._rowTag = rowTag; + streamState._rowLength = rowLength; + } + } else processBinaryChunk(response$jscomp$0, streamState, chunk); + }); + stream.on("error", function (error) { + reportGlobalError(response$jscomp$0, error); + }); + stream.on("end", onEnd); + } + var util = __webpack_require__("util"), + ReactDOM = __webpack_require__("./node_modules/react-dom/index.js"), + React = __webpack_require__("./node_modules/react/index.js"), + decoderOptions = { stream: !0 }, + bind$1 = Function.prototype.bind, + hasConfirmedEval = !1, + hasOwnProperty = Object.prototype.hasOwnProperty, + chunkCache = new Map(), + ReactDOMSharedInternals = + ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator, + ASYNC_ITERATOR = Symbol.asyncIterator, + isArrayImpl = Array.isArray, + getPrototypeOf = Object.getPrototypeOf, + jsxPropsParents = new WeakMap(), + jsxChildrenParents = new WeakMap(), + CLIENT_REFERENCE_TAG = Symbol.for("react.client.reference"), + ObjectPrototype$1 = Object.prototype, + knownServerReferences = new WeakMap(), + boundCache = new WeakMap(), + fakeServerFunctionIdx = 0, + FunctionBind = Function.prototype.bind, + ArraySlice = Array.prototype.slice, + v8FrameRegExp = + /^ {3} at (?:(.+) \((.+):(\d+):(\d+)\)|(?:async )?(.+):(\d+):(\d+))$/, + jscSpiderMonkeyFrameRegExp = /(?:(.*)@)?(.*):(\d+):(\d+)/, + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), + supportsUserTiming = + "undefined" !== typeof console && + "function" === typeof console.timeStamp && + "undefined" !== typeof performance && + "function" === typeof performance.measure, + trackNames = + "Primary Parallel Parallel\u200b Parallel\u200b\u200b Parallel\u200b\u200b\u200b Parallel\u200b\u200b\u200b\u200b Parallel\u200b\u200b\u200b\u200b\u200b Parallel\u200b\u200b\u200b\u200b\u200b\u200b Parallel\u200b\u200b\u200b\u200b\u200b\u200b\u200b Parallel\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b".split( + " " + ), + prefix, + suffix; + new ("function" === typeof WeakMap ? WeakMap : Map)(); + var ReactSharedInteralsServer = + React.__SERVER_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + ReactSharedInternals = + React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE || + ReactSharedInteralsServer, + ObjectPrototype = Object.prototype, + ArrayPrototype = Array.prototype; + ReactPromise.prototype = Object.create(Promise.prototype); + Object.defineProperty(ReactPromise.prototype, "then", { + writable: !0, + enumerable: !0, + configurable: !0, + value: function (resolve, reject) { + var _this = this; + switch (this.status) { + case "resolved_model": + initializeModelChunk(this); + break; + case "resolved_module": + initializeModuleChunk(this); + } + var resolveCallback = resolve, + rejectCallback = reject, + wrapperPromise = new Promise(function (res, rej) { + resolve = function (value) { + wrapperPromise._debugInfo = _this._debugInfo; + res(value); + }; + reject = function (reason) { + wrapperPromise._debugInfo = _this._debugInfo; + rej(reason); + }; + }); + wrapperPromise.then(resolveCallback, rejectCallback); + switch (this.status) { + case "fulfilled": + "function" === typeof resolve && resolve(this.value); + break; + case "pending": + case "pending_weak": + case "blocked": + "function" === typeof resolve && + (null === this.value && (this.value = []), + this.value.push(resolve)); + "function" === typeof reject && + (null === this.reason && (this.reason = []), + this.reason.push(reject)); + break; + case "halted": + break; + default: + "function" === typeof reject && reject(this.reason); + } + } + }); + var debugChannelRegistry = + "function" === typeof FinalizationRegistry + ? new FinalizationRegistry(closeDebugChannel) + : null, + initializingHandler = null, + initializingChunk = null, + isInitializingDebugInfo = !1, + mightHaveStaticConstructor = /\bclass\b.*\bstatic\b/, + MIN_CHUNK_SIZE = 65536, + supportsCreateTask = !!console.createTask, + fakeFunctionCache = new Map(), + fakeFunctionIdx = 0, + createFakeJSXCallStack = { + react_stack_bottom_frame: function (response, stack, environmentName) { + return buildFakeCallStack( + response, + stack, + environmentName, + !1, + fakeJSXCallSite + )(); + } + }, + createFakeJSXCallStackInDEV = + createFakeJSXCallStack.react_stack_bottom_frame.bind( + createFakeJSXCallStack + ), + ownerStackTraceLimit = 10, + currentOwnerInDEV = null, + replayConsoleWithCallStack = { + react_stack_bottom_frame: function (response, payload) { + var methodName = payload[0], + stackTrace = payload[1], + owner = payload[2], + env = payload[3]; + payload = payload.slice(4); + var prevStack = ReactSharedInternals.getCurrentStack; + ReactSharedInternals.getCurrentStack = getCurrentStackInDEV; + currentOwnerInDEV = null === owner ? response._debugRootOwner : owner; + try { + a: { + var offset = 0; + switch (methodName) { + case "dir": + case "dirxml": + case "groupEnd": + case "table": + var JSCompiler_inline_result = bind$1.apply( + console[methodName], + [console].concat(payload) + ); + break a; + case "assert": + offset = 1; + } + var newArgs = payload.slice(0); + "string" === typeof newArgs[offset] + ? newArgs.splice( + offset, + 1, + "\u001b[0m\u001b[7m%c%s\u001b[0m%c " + newArgs[offset], + "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px", + " " + env + " ", + "" + ) + : newArgs.splice( + offset, + 0, + "\u001b[0m\u001b[7m%c%s\u001b[0m%c", + "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px", + " " + env + " ", + "" + ); + newArgs.unshift(console); + JSCompiler_inline_result = bind$1.apply( + console[methodName], + newArgs + ); + } + var callStack = buildFakeCallStack( + response, + stackTrace, + env, + !1, + JSCompiler_inline_result + ); + if (null != owner) { + var task = initializeFakeTask(response, owner); + initializeFakeStack(response, owner); + if (null !== task) { + task.run(callStack); + return; + } + } + var rootTask = getRootTask(response, env); + null != rootTask ? rootTask.run(callStack) : callStack(); + } finally { + (currentOwnerInDEV = null), + (ReactSharedInternals.getCurrentStack = prevStack); + } + } + }, + replayConsoleWithCallStackInDEV = + replayConsoleWithCallStack.react_stack_bottom_frame.bind( + replayConsoleWithCallStack + ); + __rspack_unused_export = function (promiseForResponse) { + var options = + 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + response = createResponseFromOptions(options); + promiseForResponse.then( + function (r) { + if ( + options && + options.debugChannel && + options.debugChannel.readable + ) { + var streamDoneCount = 0, + handleDone = function () { + 2 === ++streamDoneCount && close(response); + }; + startReadingFromStream$1( + response, + options.debugChannel.readable, + handleDone + ); + startReadingFromStream$1(response, r.body, handleDone, r); + } else + startReadingFromStream$1( + response, + r.body, + close.bind(null, response), + r + ); + }, + function (e) { + reportGlobalError(response, e); + } + ); + return getRoot(response); + }; + __rspack_unused_export = function (stream, options) { + var response = createResponse( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverConsumerModuleMap, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + noServerCall, + options ? options.encodeFormAction : void 0, + options && "string" === typeof options.nonce ? options.nonce : void 0, + void 0, + options && options.unstable_allowPartialStream + ? options.unstable_allowPartialStream + : !1, + options && options.findSourceMapURL ? options.findSourceMapURL : void 0, + options ? !0 === options.replayConsoleLogs : !1, + options && options.environmentName ? options.environmentName : void 0, + options && null != options.startTime ? options.startTime : void 0, + options && null != options.endTime ? options.endTime : void 0, + options && void 0 !== options.debugChannel + ? { hasReadable: !0, callback: null } + : void 0 + ); + if (options && options.debugChannel) { + var streamEndedCount = 0, + handleEnd = function () { + 2 === ++streamEndedCount && close(response); + }; + startReadingFromStream(response, options.debugChannel, handleEnd); + startReadingFromStream(response, stream, handleEnd); + } else + startReadingFromStream(response, stream, close.bind(null, response)); + return getRoot(response); + }; + exports.createFromReadableStream = function (stream) { + var options = + 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, + response = createResponseFromOptions(options); + if (options && options.debugChannel && options.debugChannel.readable) { + var streamDoneCount = 0, + handleDone = function () { + 2 === ++streamDoneCount && close(response); + }; + startReadingFromStream$1( + response, + options.debugChannel.readable, + handleDone + ); + startReadingFromStream$1(response, stream, handleDone, stream); + } else + startReadingFromStream$1( + response, + stream, + close.bind(null, response), + stream + ); + return getRoot(response); + }; + __rspack_unused_export = function (id) { + return createServerReference$1(id, noServerCall$1); + }; + __rspack_unused_export = function () { + return new Map(); + }; + __rspack_unused_export = function (value, options) { + return new Promise(function (resolve, reject) { + var abort = processReply( + value, + "", + options && options.temporaryReferences + ? options.temporaryReferences + : void 0, + resolve, + reject + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(signal.reason); + else { + var listener = function () { + abort(signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + }); + }; + __rspack_unused_export = function ( + reference, + id, + encodeFormAction + ) { + registerBoundServerReference(reference, id, null, encodeFormAction); + return reference; + }; + })(); + + +}, +"./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; +/** + * @license React + * react-server-dom-rspack-client.node.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var util = __webpack_require__("util"), + ReactDOM = __webpack_require__("./node_modules/react-dom/index.js"), + decoderOptions = { stream: !0 }, + hasOwnProperty = Object.prototype.hasOwnProperty; +function resolveClientReference(bundlerConfig, metadata) { + if (bundlerConfig) { + var moduleExports = bundlerConfig[metadata[0]]; + if ((bundlerConfig = moduleExports && moduleExports[metadata[2]])) + moduleExports = bundlerConfig.name; + else { + bundlerConfig = moduleExports && moduleExports["*"]; + if (!bundlerConfig) + throw Error( + 'Could not find the module "' + + metadata[0] + + '" in the React Server Consumer Manifest. This is probably a bug in the React Server Components bundler.' + ); + moduleExports = metadata[2]; + } + return 4 === metadata.length + ? [bundlerConfig.id, bundlerConfig.chunks, moduleExports, 1] + : [bundlerConfig.id, bundlerConfig.chunks, moduleExports]; + } + return metadata; +} +function resolveServerReference(bundlerConfig, id) { + var name = "", + resolvedModuleData = bundlerConfig[id]; + if (resolvedModuleData) name = resolvedModuleData.name; + else { + var idx = id.lastIndexOf("#"); + -1 !== idx && + ((name = id.slice(idx + 1)), + (resolvedModuleData = bundlerConfig[id.slice(0, idx)])); + if (!resolvedModuleData) + throw Error( + 'Could not find the module "' + + id + + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.' + ); + } + return resolvedModuleData.async + ? [resolvedModuleData.id, resolvedModuleData.chunks, name, 1] + : [resolvedModuleData.id, resolvedModuleData.chunks, name]; +} +var chunkCache = new Map(); +function requireAsyncModule(id) { + var promise = __webpack_require__(id); + if ("function" !== typeof promise.then || "fulfilled" === promise.status) + return null; + promise.then( + function (value) { + promise.status = "fulfilled"; + promise.value = value; + }, + function (reason) { + promise.status = "rejected"; + promise.reason = reason; + } + ); + return promise; +} +function ignoreReject() {} +function preloadModule(metadata) { + for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) { + var chunkId = chunks[i++]; + chunks[i++]; + var entry = chunkCache.get(chunkId); + if (void 0 === entry) { + entry = __webpack_require__.e(chunkId); + promises.push(entry); + var resolve = chunkCache.set.bind(chunkCache, chunkId, null); + entry.then(resolve, ignoreReject); + chunkCache.set(chunkId, entry); + } else null !== entry && promises.push(entry); + } + return 4 === metadata.length + ? 0 === promises.length + ? requireAsyncModule(metadata[0]) + : Promise.all(promises).then(function () { + return requireAsyncModule(metadata[0]); + }) + : 0 < promises.length + ? Promise.all(promises) + : null; +} +function requireModule(metadata) { + var moduleExports = __webpack_require__(metadata[0]); + if (4 === metadata.length && "function" === typeof moduleExports.then) + if ("fulfilled" === moduleExports.status) + moduleExports = moduleExports.value; + else throw moduleExports.reason; + if ("*" === metadata[2]) return moduleExports; + if ("" === metadata[2]) + return moduleExports.__esModule ? moduleExports.default : moduleExports; + if (hasOwnProperty.call(moduleExports, metadata[2])) + return moduleExports[metadata[2]]; +} +function prepareDestinationWithChunks(moduleLoading, chunks, nonce$jscomp$0) { + if (null !== moduleLoading) + for (var i = 1; i < chunks.length; i += 2) { + var nonce = nonce$jscomp$0, + JSCompiler_temp_const = ReactDOMSharedInternals.d, + JSCompiler_temp_const$jscomp$0 = JSCompiler_temp_const.X, + JSCompiler_temp_const$jscomp$1 = moduleLoading.prefix + chunks[i]; + var JSCompiler_inline_result = moduleLoading.crossOrigin; + JSCompiler_inline_result = + "string" === typeof JSCompiler_inline_result + ? "use-credentials" === JSCompiler_inline_result + ? JSCompiler_inline_result + : "" + : void 0; + JSCompiler_temp_const$jscomp$0.call( + JSCompiler_temp_const, + JSCompiler_temp_const$jscomp$1, + { + crossOrigin: JSCompiler_inline_result, + integrity: void 0, + fetchPriority: void 0, + nonce: nonce + } + ); + } +} +var ReactDOMSharedInternals = + ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; +} +var ASYNC_ITERATOR = Symbol.asyncIterator, + isArrayImpl = Array.isArray, + getPrototypeOf = Object.getPrototypeOf, + ObjectPrototype$1 = Object.prototype, + knownServerReferences = new WeakMap(); +function serializeNumber(number) { + return Number.isFinite(number) + ? 0 === number && -Infinity === 1 / number + ? "$-0" + : number + : Infinity === number + ? "$Infinity" + : -Infinity === number + ? "$-Infinity" + : "$NaN"; +} +function processReply( + root, + formFieldPrefix, + temporaryReferences, + resolve, + reject +) { + function serializeTypedArray(tag, typedArray) { + typedArray = new Blob([ + new Uint8Array( + typedArray.buffer, + typedArray.byteOffset, + typedArray.byteLength + ) + ]); + var blobId = nextPartId++; + null === formData && (formData = new FormData()); + formData.append(formFieldPrefix + blobId, typedArray); + return "$" + tag + blobId.toString(16); + } + function serializeBinaryReader(reader) { + function progress(entry) { + entry.done + ? ((entry = nextPartId++), + data.append(formFieldPrefix + entry, new Blob(buffer)), + data.append( + formFieldPrefix + streamId, + '"$o' + entry.toString(16) + '"' + ), + data.append(formFieldPrefix + streamId, "C"), + pendingParts--, + 0 === pendingParts && resolve(data)) + : (buffer.push(entry.value), + reader.read(new Uint8Array(1024)).then(progress, reject)); + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++, + buffer = []; + reader.read(new Uint8Array(1024)).then(progress, reject); + return "$r" + streamId.toString(16); + } + function serializeReader(reader) { + function progress(entry) { + if (entry.done) + data.append(formFieldPrefix + streamId, "C"), + pendingParts--, + 0 === pendingParts && resolve(data); + else + try { + var partJSON = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, partJSON); + reader.read().then(progress, reject); + } catch (x) { + reject(x); + } + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++; + reader.read().then(progress, reject); + return "$R" + streamId.toString(16); + } + function serializeReadableStream(stream) { + try { + var binaryReader = stream.getReader({ mode: "byob" }); + } catch (x) { + return serializeReader(stream.getReader()); + } + return serializeBinaryReader(binaryReader); + } + function serializeAsyncIterable(iterable, iterator) { + function progress(entry) { + if (entry.done) { + if (void 0 === entry.value) + data.append(formFieldPrefix + streamId, "C"); + else + try { + var partJSON = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, "C" + partJSON); + } catch (x) { + reject(x); + return; + } + pendingParts--; + 0 === pendingParts && resolve(data); + } else + try { + var partJSON$21 = JSON.stringify(entry.value, resolveToJSON); + data.append(formFieldPrefix + streamId, partJSON$21); + iterator.next().then(progress, reject); + } catch (x$22) { + reject(x$22); + } + } + null === formData && (formData = new FormData()); + var data = formData; + pendingParts++; + var streamId = nextPartId++; + iterable = iterable === iterator; + iterator.next().then(progress, reject); + return "$" + (iterable ? "x" : "X") + streamId.toString(16); + } + function resolveToJSON(key, value) { + if (null === value) return null; + if ("object" === typeof value) { + switch (value.$$typeof) { + case REACT_ELEMENT_TYPE: + if (void 0 !== temporaryReferences && -1 === key.indexOf(":")) { + var parentReference = writtenObjects.get(this); + if (void 0 !== parentReference) + return ( + temporaryReferences.set(parentReference + ":" + key, value), + "$T" + ); + } + if (void 0 !== temporaryReferences && modelRoot === value) + return (modelRoot = null), "$T"; + throw Error( + "React Element cannot be passed to Server Functions from the Client without a temporary reference set. Pass a TemporaryReferenceSet to the options." + ); + case REACT_LAZY_TYPE: + parentReference = value._payload; + var init = value._init; + null === formData && (formData = new FormData()); + pendingParts++; + try { + var resolvedModel = init(parentReference), + lazyId = nextPartId++, + partJSON = serializeModel(resolvedModel, lazyId); + formData.append(formFieldPrefix + lazyId, partJSON); + return "$" + lazyId.toString(16); + } catch (x) { + if ( + "object" === typeof x && + null !== x && + "function" === typeof x.then + ) { + pendingParts++; + var lazyId$23 = nextPartId++; + parentReference = function () { + try { + var partJSON$24 = serializeModel(value, lazyId$23), + data$25 = formData; + data$25.append(formFieldPrefix + lazyId$23, partJSON$24); + pendingParts--; + 0 === pendingParts && resolve(data$25); + } catch (reason) { + reject(reason); + } + }; + x.then(parentReference, parentReference); + return "$" + lazyId$23.toString(16); + } + reject(x); + return null; + } finally { + pendingParts--; + } + } + parentReference = writtenObjects.get(value); + if ("function" === typeof value.then) { + if (void 0 !== parentReference) + if (modelRoot === value) modelRoot = null; + else return parentReference; + null === formData && (formData = new FormData()); + pendingParts++; + var promiseId = nextPartId++; + key = "$@" + promiseId.toString(16); + writtenObjects.set(value, key); + value.then(function (partValue) { + try { + var previousReference = writtenObjects.get(partValue); + var partJSON$27 = + void 0 !== previousReference + ? JSON.stringify(previousReference) + : serializeModel(partValue, promiseId); + partValue = formData; + partValue.append(formFieldPrefix + promiseId, partJSON$27); + pendingParts--; + 0 === pendingParts && resolve(partValue); + } catch (reason) { + reject(reason); + } + }, reject); + return key; + } + if (void 0 !== parentReference) + if (modelRoot === value) modelRoot = null; + else return parentReference; + else + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference && + ((key = parentReference + ":" + key), + writtenObjects.set(value, key), + void 0 !== temporaryReferences && + temporaryReferences.set(key, value))); + if (isArrayImpl(value)) return value; + if (value instanceof FormData) { + null === formData && (formData = new FormData()); + var data$31 = formData; + key = nextPartId++; + var prefix = formFieldPrefix + "_" + key + "_"; + value.forEach(function (originalValue, originalKey) { + data$31.append(prefix + originalKey, originalValue); + }); + return "$K" + key.toString(16); + } + if (value instanceof Map) + return ( + (key = nextPartId++), + (parentReference = serializeModel(Array.from(value), key)), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$Q" + key.toString(16) + ); + if (value instanceof Set) + return ( + (key = nextPartId++), + (parentReference = serializeModel(Array.from(value), key)), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$W" + key.toString(16) + ); + if (value instanceof ArrayBuffer) + return ( + (key = new Blob([value])), + (parentReference = nextPartId++), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + parentReference, key), + "$A" + parentReference.toString(16) + ); + if (value instanceof Int8Array) return serializeTypedArray("O", value); + if (value instanceof Uint8Array) return serializeTypedArray("o", value); + if (value instanceof Uint8ClampedArray) + return serializeTypedArray("U", value); + if (value instanceof Int16Array) return serializeTypedArray("S", value); + if (value instanceof Uint16Array) return serializeTypedArray("s", value); + if (value instanceof Int32Array) return serializeTypedArray("L", value); + if (value instanceof Uint32Array) return serializeTypedArray("l", value); + if (value instanceof Float32Array) return serializeTypedArray("G", value); + if (value instanceof Float64Array) return serializeTypedArray("g", value); + if (value instanceof BigInt64Array) + return serializeTypedArray("M", value); + if (value instanceof BigUint64Array) + return serializeTypedArray("m", value); + if (value instanceof DataView) return serializeTypedArray("V", value); + if ("function" === typeof Blob && value instanceof Blob) + return ( + null === formData && (formData = new FormData()), + (key = nextPartId++), + formData.append(formFieldPrefix + key, value), + "$B" + key.toString(16) + ); + if ((key = getIteratorFn(value))) + return ( + (parentReference = key.call(value)), + parentReference === value + ? ((key = nextPartId++), + (parentReference = serializeModel( + Array.from(parentReference), + key + )), + null === formData && (formData = new FormData()), + formData.append(formFieldPrefix + key, parentReference), + "$i" + key.toString(16)) + : Array.from(parentReference) + ); + if ( + "function" === typeof ReadableStream && + value instanceof ReadableStream + ) + return serializeReadableStream(value); + key = value[ASYNC_ITERATOR]; + if ("function" === typeof key) + return serializeAsyncIterable(value, key.call(value)); + key = getPrototypeOf(value); + if ( + key !== ObjectPrototype$1 && + (null === key || null !== getPrototypeOf(key)) + ) { + if (void 0 === temporaryReferences) + throw Error( + "Only plain objects, and a few built-ins, can be passed to Server Functions. Classes or null prototypes are not supported." + ); + return "$T"; + } + return value; + } + if ("string" === typeof value) { + if ("Z" === value[value.length - 1] && this[key] instanceof Date) + return "$D" + value; + key = "$" === value[0] ? "$" + value : value; + return key; + } + if ("boolean" === typeof value) return value; + if ("number" === typeof value) return serializeNumber(value); + if ("undefined" === typeof value) return "$undefined"; + if ("function" === typeof value) { + parentReference = knownServerReferences.get(value); + if (void 0 !== parentReference) { + key = writtenObjects.get(value); + if (void 0 !== key) return key; + key = JSON.stringify( + { id: parentReference.id, bound: parentReference.bound }, + resolveToJSON + ); + null === formData && (formData = new FormData()); + parentReference = nextPartId++; + formData.set(formFieldPrefix + parentReference, key); + key = "$h" + parentReference.toString(16); + writtenObjects.set(value, key); + return key; + } + if ( + void 0 !== temporaryReferences && + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference) + ) + return ( + temporaryReferences.set(parentReference + ":" + key, value), "$T" + ); + throw Error( + "Client Functions cannot be passed directly to Server Functions. Only Functions passed from the Server can be passed back again." + ); + } + if ("symbol" === typeof value) { + if ( + void 0 !== temporaryReferences && + -1 === key.indexOf(":") && + ((parentReference = writtenObjects.get(this)), + void 0 !== parentReference) + ) + return ( + temporaryReferences.set(parentReference + ":" + key, value), "$T" + ); + throw Error( + "Symbols cannot be passed to a Server Function without a temporary reference set. Pass a TemporaryReferenceSet to the options." + ); + } + if ("bigint" === typeof value) return "$n" + value.toString(10); + throw Error( + "Type " + + typeof value + + " is not supported as an argument to a Server Function." + ); + } + function serializeModel(model, id) { + "object" === typeof model && + null !== model && + ((id = "$" + id.toString(16)), + writtenObjects.set(model, id), + void 0 !== temporaryReferences && temporaryReferences.set(id, model)); + modelRoot = model; + return JSON.stringify(model, resolveToJSON); + } + var nextPartId = 1, + pendingParts = 0, + formData = null, + writtenObjects = new WeakMap(), + modelRoot = root, + json = serializeModel(root, 0); + null === formData + ? resolve(json) + : (formData.set(formFieldPrefix + "0", json), + 0 === pendingParts && resolve(formData)); + return function () { + 0 < pendingParts && + ((pendingParts = 0), + null === formData ? resolve(json) : resolve(formData)); + }; +} +var boundCache = new WeakMap(); +function encodeFormData(reference) { + var resolve, + reject, + thenable = new Promise(function (res, rej) { + resolve = res; + reject = rej; + }); + processReply( + reference, + "", + void 0, + function (body) { + if ("string" === typeof body) { + var data = new FormData(); + data.append("0", body); + body = data; + } + thenable.status = "fulfilled"; + thenable.value = body; + resolve(body); + }, + function (e) { + thenable.status = "rejected"; + thenable.reason = e; + reject(e); + } + ); + return thenable; +} +function defaultEncodeFormAction(identifierPrefix) { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + var data = null; + if (null !== referenceClosure.bound) { + data = boundCache.get(referenceClosure); + data || + ((data = encodeFormData({ + id: referenceClosure.id, + bound: referenceClosure.bound + })), + boundCache.set(referenceClosure, data)); + if ("rejected" === data.status) throw data.reason; + if ("fulfilled" !== data.status) throw data; + referenceClosure = data.value; + var prefixedData = new FormData(); + referenceClosure.forEach(function (value, key) { + prefixedData.append("$ACTION_" + identifierPrefix + ":" + key, value); + }); + data = prefixedData; + referenceClosure = "$ACTION_REF_" + identifierPrefix; + } else referenceClosure = "$ACTION_ID_" + referenceClosure.id; + return { + name: referenceClosure, + method: "POST", + encType: "multipart/form-data", + data: data + }; +} +function isSignatureEqual(referenceId, numberOfBoundArgs) { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + if (referenceClosure.id !== referenceId) return !1; + var boundPromise = referenceClosure.bound; + if (null === boundPromise) return 0 === numberOfBoundArgs; + switch (boundPromise.status) { + case "fulfilled": + return boundPromise.value.length === numberOfBoundArgs; + case "pending": + throw boundPromise; + case "rejected": + throw boundPromise.reason; + default: + throw ( + ("string" !== typeof boundPromise.status && + ((boundPromise.status = "pending"), + boundPromise.then( + function (boundArgs) { + boundPromise.status = "fulfilled"; + boundPromise.value = boundArgs; + }, + function (error) { + boundPromise.status = "rejected"; + boundPromise.reason = error; + } + )), + boundPromise) + ); + } +} +function registerBoundServerReference(reference, id, bound, encodeFormAction) { + knownServerReferences.has(reference) || + (knownServerReferences.set(reference, { + id: id, + originalBind: reference.bind, + bound: bound + }), + Object.defineProperties(reference, { + $$FORM_ACTION: { + value: + void 0 === encodeFormAction + ? defaultEncodeFormAction + : function () { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) + throw Error( + "Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React." + ); + var boundPromise = referenceClosure.bound; + null === boundPromise && (boundPromise = Promise.resolve([])); + return encodeFormAction(referenceClosure.id, boundPromise); + } + }, + $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, + bind: { value: bind } + })); +} +var FunctionBind = Function.prototype.bind, + ArraySlice = Array.prototype.slice; +function bind() { + var referenceClosure = knownServerReferences.get(this); + if (!referenceClosure) return FunctionBind.apply(this, arguments); + var newFn = referenceClosure.originalBind.apply(this, arguments), + args = ArraySlice.call(arguments, 1), + boundPromise = null; + boundPromise = + null !== referenceClosure.bound + ? Promise.resolve(referenceClosure.bound).then(function (boundArgs) { + return boundArgs.concat(args); + }) + : Promise.resolve(args); + knownServerReferences.set(newFn, { + id: referenceClosure.id, + originalBind: newFn.bind, + bound: boundPromise + }); + Object.defineProperties(newFn, { + $$FORM_ACTION: { value: this.$$FORM_ACTION }, + $$IS_SIGNATURE_EQUAL: { value: isSignatureEqual }, + bind: { value: bind } + }); + return newFn; +} +function createBoundServerReference(metaData, callServer, encodeFormAction) { + function action() { + var args = Array.prototype.slice.call(arguments); + return bound + ? "fulfilled" === bound.status + ? callServer(id, bound.value.concat(args)) + : Promise.resolve(bound).then(function (boundArgs) { + return callServer(id, boundArgs.concat(args)); + }) + : callServer(id, args); + } + var id = metaData.id, + bound = metaData.bound; + registerBoundServerReference(action, id, bound, encodeFormAction); + return action; +} +function createServerReference$1(id, callServer, encodeFormAction) { + function action() { + var args = Array.prototype.slice.call(arguments); + return callServer(id, args); + } + registerBoundServerReference(action, id, null, encodeFormAction); + return action; +} +var ObjectPrototype = Object.prototype, + ArrayPrototype = Array.prototype; +function ReactPromise(status, value, reason) { + this.status = status; + this.value = value; + this.reason = reason; +} +ReactPromise.prototype = Object.create(Promise.prototype); +Object.defineProperty(ReactPromise.prototype, "then", { + writable: !0, + enumerable: !0, + configurable: !0, + value: function (resolve, reject) { + switch (this.status) { + case "resolved_model": + initializeModelChunk(this); + break; + case "resolved_module": + initializeModuleChunk(this); + } + switch (this.status) { + case "fulfilled": + "function" === typeof resolve && resolve(this.value); + break; + case "pending": + case "pending_weak": + case "blocked": + "function" === typeof resolve && + (null === this.value && (this.value = []), this.value.push(resolve)); + "function" === typeof reject && + (null === this.reason && (this.reason = []), + this.reason.push(reject)); + break; + case "halted": + break; + default: + "function" === typeof reject && reject(this.reason); + } + } +}); +function readChunk(chunk) { + switch (chunk.status) { + case "resolved_model": + initializeModelChunk(chunk); + break; + case "resolved_module": + initializeModuleChunk(chunk); + } + switch (chunk.status) { + case "fulfilled": + return chunk.value; + case "pending": + case "pending_weak": + case "blocked": + case "halted": + throw chunk; + default: + throw chunk.reason; + } +} +function wakeChunk(response, listeners, value, chunk) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk); + } +} +function rejectChunk(response, listeners, error) { + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + "function" === typeof listener + ? listener(error) + : rejectReference(response, listener.handler, error); + } +} +function resolveBlockedCycle(resolvedChunk, reference) { + var referencedChunk = reference.handler.chunk; + if (null === referencedChunk) return null; + if (referencedChunk === resolvedChunk) return reference.handler; + reference = referencedChunk.value; + if (null !== reference) + for ( + referencedChunk = 0; + referencedChunk < reference.length; + referencedChunk++ + ) { + var listener = reference[referencedChunk]; + if ( + "function" !== typeof listener && + ((listener = resolveBlockedCycle(resolvedChunk, listener)), + null !== listener) + ) + return listener; + } + return null; +} +function wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners +) { + switch (chunk.status) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + break; + case "blocked": + for (var i = 0; i < resolveListeners.length; i++) { + var listener = resolveListeners[i]; + if ("function" !== typeof listener) { + var cyclicHandler = resolveBlockedCycle(chunk, listener); + if (null !== cyclicHandler) + switch ( + (fulfillReference(response, listener, cyclicHandler.value, chunk), + resolveListeners.splice(i, 1), + i--, + null !== rejectListeners && + ((listener = rejectListeners.indexOf(listener)), + -1 !== listener && rejectListeners.splice(listener, 1)), + chunk.status) + ) { + case "fulfilled": + wakeChunk(response, resolveListeners, chunk.value, chunk); + return; + case "rejected": + null !== rejectListeners && + rejectChunk(response, rejectListeners, chunk.reason); + return; + } + } + } + case "pending": + if (chunk.value) + for (response = 0; response < resolveListeners.length; response++) + chunk.value.push(resolveListeners[response]); + else chunk.value = resolveListeners; + if (chunk.reason) { + if (rejectListeners) + for ( + resolveListeners = 0; + resolveListeners < rejectListeners.length; + resolveListeners++ + ) + chunk.reason.push(rejectListeners[resolveListeners]); + } else chunk.reason = rejectListeners; + break; + case "rejected": + rejectListeners && rejectChunk(response, rejectListeners, chunk.reason); + } +} +function triggerErrorOnChunk(response, chunk, error) { + if ( + "pending" !== chunk.status && + "pending_weak" !== chunk.status && + "blocked" !== chunk.status + ) + chunk.reason.error(error); + else { + var listeners = chunk.reason; + chunk.status = "rejected"; + chunk.reason = error; + null !== listeners && rejectChunk(response, listeners, error); + } +} +function createResolvedIteratorResultChunk(response, value, done) { + return new ReactPromise( + "resolved_model", + (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}", + response + ); +} +function resolveIteratorResultChunk(response, chunk, value, done) { + resolveModelChunk( + response, + chunk, + (done ? '{"done":true,"value":' : '{"done":false,"value":') + value + "}" + ); +} +function resolveModelChunk(response, chunk, value) { + if ("pending" !== chunk.status && "pending_weak" !== chunk.status) + chunk.reason.enqueueModel(value); + else { + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_model"; + chunk.value = value; + chunk.reason = response; + null !== resolveListeners && + (initializeModelChunk(chunk), + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + )); + } +} +function resolveModuleChunk(response, chunk, value) { + if ( + "pending" === chunk.status || + "pending_weak" === chunk.status || + "blocked" === chunk.status + ) { + var resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "resolved_module"; + chunk.value = value; + chunk.reason = null; + null !== resolveListeners && + (initializeModuleChunk(chunk), + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + )); + } +} +var initializingHandler = null; +function initializeModelChunk(chunk) { + var prevHandler = initializingHandler; + initializingHandler = null; + var resolvedModel = chunk.value, + response = chunk.reason; + chunk.status = "blocked"; + chunk.value = null; + chunk.reason = null; + try { + var value = parseModel(response, resolvedModel), + resolveListeners = chunk.value; + if (null !== resolveListeners) + for ( + chunk.value = null, chunk.reason = null, resolvedModel = 0; + resolvedModel < resolveListeners.length; + resolvedModel++ + ) { + var listener = resolveListeners[resolvedModel]; + "function" === typeof listener + ? listener(value) + : fulfillReference(response, listener, value, chunk); + } + if (null !== initializingHandler) { + if (initializingHandler.errored) throw initializingHandler.reason; + if (0 < initializingHandler.deps) { + initializingHandler.value = value; + initializingHandler.chunk = chunk; + return; + } + } + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = null; + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } finally { + initializingHandler = prevHandler; + } +} +function initializeModuleChunk(chunk) { + try { + var value = requireModule(chunk.value); + chunk.status = "fulfilled"; + chunk.value = value; + chunk.reason = null; + } catch (error) { + (chunk.status = "rejected"), (chunk.reason = error); + } +} +function reportGlobalError(weakResponse, error) { + weakResponse._closed = !0; + weakResponse._closedReason = error; + weakResponse._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? triggerErrorOnChunk(weakResponse, chunk, error) + : "fulfilled" === chunk.status && + null !== chunk.reason && + chunk.reason.error(error); + }); +} +function createLazyChunkWrapper(chunk) { + return { $$typeof: REACT_LAZY_TYPE, _payload: chunk, _init: readChunk }; +} +function getChunk(response, id) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk || + ((chunk = response._closed + ? response._allowPartialStream + ? new ReactPromise("halted", null, null) + : new ReactPromise("rejected", null, response._closedReason) + : new ReactPromise("pending", null, null)), + chunks.set(id, chunk)); + return chunk; +} +function fulfillReference(response, reference, value) { + var handler = reference.handler, + parentObject = reference.parentObject, + key = reference.key, + map = reference.map, + path = reference.path; + try { + for (var i = 1; i < path.length; i++) { + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + var referencedChunk = value._payload; + if (referencedChunk === handler.chunk) value = handler.value; + else { + switch (referencedChunk.status) { + case "resolved_model": + initializeModelChunk(referencedChunk); + break; + case "resolved_module": + initializeModuleChunk(referencedChunk); + } + switch (referencedChunk.status) { + case "fulfilled": + value = referencedChunk.value; + continue; + case "blocked": + var cyclicHandler = resolveBlockedCycle( + referencedChunk, + reference + ); + if (null !== cyclicHandler) { + value = cyclicHandler.value; + continue; + } + case "pending": + case "pending_weak": + path.splice(0, i - 1); + null === referencedChunk.value + ? (referencedChunk.value = [reference]) + : referencedChunk.value.push(reference); + null === referencedChunk.reason + ? (referencedChunk.reason = [reference]) + : referencedChunk.reason.push(reference); + return; + case "halted": + return; + default: + rejectReference( + response, + reference.handler, + referencedChunk.reason + ); + return; + } + } + } + var name = path[i]; + if ( + "object" === typeof value && + null !== value && + hasOwnProperty.call(value, name) + ) + value = value[name]; + else throw Error("Invalid reference."); + } + for ( + ; + "object" === typeof value && + null !== value && + value.$$typeof === REACT_LAZY_TYPE; + + ) { + var referencedChunk$44 = value._payload; + if (referencedChunk$44 === handler.chunk) value = handler.value; + else { + switch (referencedChunk$44.status) { + case "resolved_model": + initializeModelChunk(referencedChunk$44); + break; + case "resolved_module": + initializeModuleChunk(referencedChunk$44); + } + switch (referencedChunk$44.status) { + case "fulfilled": + value = referencedChunk$44.value; + continue; + } + break; + } + } + var mappedValue = map(response, value, parentObject, key); + "__proto__" !== key && (parentObject[key] = mappedValue); + "" === key && null === handler.value && (handler.value = mappedValue); + if ( + parentObject[0] === REACT_ELEMENT_TYPE && + "object" === typeof handler.value && + null !== handler.value && + handler.value.$$typeof === REACT_ELEMENT_TYPE + ) { + var element = handler.value; + switch (key) { + case "3": + element.props = mappedValue; + } + } + } catch (error) { + rejectReference(response, reference.handler, error); + return; + } + handler.deps--; + 0 === handler.deps && + ((reference = handler.chunk), + null !== reference && + "blocked" === reference.status && + ((value = reference.value), + (reference.status = "fulfilled"), + (reference.value = handler.value), + (reference.reason = handler.reason), + null !== value && wakeChunk(response, value, handler.value, reference))); +} +function rejectReference(response, handler, error) { + handler.errored || + ((handler.errored = !0), + (handler.value = null), + (handler.reason = error), + (handler = handler.chunk), + null !== handler && + "blocked" === handler.status && + triggerErrorOnChunk(response, handler, error)); +} +function waitForReference( + referencedChunk, + parentObject, + key, + response, + map, + path +) { + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (response = initializingHandler = + { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }); + parentObject = { + handler: response, + parentObject: parentObject, + key: key, + map: map, + path: path + }; + null === referencedChunk.value + ? (referencedChunk.value = [parentObject]) + : referencedChunk.value.push(parentObject); + null === referencedChunk.reason + ? (referencedChunk.reason = [parentObject]) + : referencedChunk.reason.push(parentObject); + return null; +} +function loadServerReference(response, metaData, parentObject, key) { + if (!response._serverReferenceConfig) + return createBoundServerReference( + metaData, + response._callServer, + response._encodeFormAction + ); + var serverReference = resolveServerReference( + response._serverReferenceConfig, + metaData.id + ), + promise = preloadModule(serverReference); + if (promise) + metaData.bound && (promise = Promise.all([promise, metaData.bound])); + else if (metaData.bound) promise = Promise.resolve(metaData.bound); + else + return ( + (promise = requireModule(serverReference)), + registerBoundServerReference( + promise, + metaData.id, + metaData.bound, + response._encodeFormAction + ), + promise + ); + if (initializingHandler) { + var handler = initializingHandler; + handler.deps++; + } else + handler = initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }; + promise.then( + function () { + var resolvedValue = requireModule(serverReference); + if (metaData.bound) { + var boundArgs = metaData.bound.value.slice(0); + boundArgs.unshift(null); + resolvedValue = resolvedValue.bind.apply(resolvedValue, boundArgs); + } + registerBoundServerReference( + resolvedValue, + metaData.id, + metaData.bound, + response._encodeFormAction + ); + "__proto__" !== key && (parentObject[key] = resolvedValue); + "" === key && null === handler.value && (handler.value = resolvedValue); + if ( + parentObject[0] === REACT_ELEMENT_TYPE && + "object" === typeof handler.value && + null !== handler.value && + handler.value.$$typeof === REACT_ELEMENT_TYPE + ) + switch (((boundArgs = handler.value), key)) { + case "3": + boundArgs.props = resolvedValue; + } + handler.deps--; + 0 === handler.deps && + ((resolvedValue = handler.chunk), + null !== resolvedValue && + "blocked" === resolvedValue.status && + ((boundArgs = resolvedValue.value), + (resolvedValue.status = "fulfilled"), + (resolvedValue.value = handler.value), + (resolvedValue.reason = null), + null !== boundArgs && + wakeChunk(response, boundArgs, handler.value, resolvedValue))); + }, + function (error) { + if (!handler.errored) { + handler.errored = !0; + handler.value = null; + handler.reason = error; + var chunk = handler.chunk; + null !== chunk && + "blocked" === chunk.status && + triggerErrorOnChunk(response, chunk, error); + } + } + ); + return null; +} +function getOutlinedModel(response, reference, parentObject, key, map) { + reference = reference.split(":"); + var id = parseInt(reference[0], 16); + id = getChunk(response, id); + switch (id.status) { + case "resolved_model": + initializeModelChunk(id); + break; + case "resolved_module": + initializeModuleChunk(id); + } + switch (id.status) { + case "fulfilled": + id = id.value; + for (var i = 1; i < reference.length; i++) { + for ( + ; + "object" === typeof id && + null !== id && + id.$$typeof === REACT_LAZY_TYPE; + + ) { + id = id._payload; + switch (id.status) { + case "resolved_model": + initializeModelChunk(id); + break; + case "resolved_module": + initializeModuleChunk(id); + } + switch (id.status) { + case "fulfilled": + id = id.value; + break; + case "blocked": + case "pending": + case "pending_weak": + return waitForReference( + id, + parentObject, + key, + response, + map, + reference.slice(i - 1) + ); + case "halted": + return ( + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }), + null + ); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = id.reason)) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: id.reason, + deps: 0, + errored: !0 + }), + null + ); + } + } + var name = reference[i]; + if ( + "object" !== typeof id || + null === id || + (getPrototypeOf(id) !== ObjectPrototype && + getPrototypeOf(id) !== ArrayPrototype) || + !hasOwnProperty.call(id, name) + ) + throw Error("Invalid reference."); + id = id[name]; + } + for ( + ; + "object" === typeof id && + null !== id && + id.$$typeof === REACT_LAZY_TYPE; + + ) { + reference = id._payload; + switch (reference.status) { + case "resolved_model": + initializeModelChunk(reference); + break; + case "resolved_module": + initializeModuleChunk(reference); + } + switch (reference.status) { + case "fulfilled": + id = reference.value; + continue; + } + break; + } + return map(response, id, parentObject, key); + case "pending": + case "pending_weak": + case "blocked": + return waitForReference(id, parentObject, key, response, map, reference); + case "halted": + return ( + initializingHandler + ? ((response = initializingHandler), response.deps++) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: null, + deps: 1, + errored: !1 + }), + null + ); + default: + return ( + initializingHandler + ? ((initializingHandler.errored = !0), + (initializingHandler.value = null), + (initializingHandler.reason = id.reason)) + : (initializingHandler = { + parent: null, + chunk: null, + value: null, + reason: id.reason, + deps: 0, + errored: !0 + }), + null + ); + } +} +function createMap(response, model) { + return new Map(model); +} +function createSet(response, model) { + return new Set(model); +} +function createBlob(response, model) { + return new Blob(model.slice(1), { type: model[0] }); +} +function createFormData(response, model) { + response = new FormData(); + for (var i = 0; i < model.length; i++) + response.append(model[i][0], model[i][1]); + return response; +} +function extractIterator(response, model) { + return model[Symbol.iterator](); +} +function createModel(response, model) { + return model; +} +function parseModelString(response, parentObject, key, value) { + if ("$" === value[0]) { + if ("$" === value) + return ( + null !== initializingHandler && + "0" === key && + (initializingHandler = { + parent: initializingHandler, + chunk: null, + value: null, + reason: null, + deps: 0, + errored: !1 + }), + REACT_ELEMENT_TYPE + ); + switch (value[1]) { + case "$": + return value.slice(1); + case "L": + return ( + (parentObject = parseInt(value.slice(2), 16)), + (response = getChunk(response, parentObject)), + createLazyChunkWrapper(response) + ); + case "@": + return ( + (parentObject = parseInt(value.slice(2), 16)), + getChunk(response, parentObject) + ); + case "w": + return; + case "S": + return Symbol.for(value.slice(2)); + case "h": + return ( + (value = value.slice(2)), + getOutlinedModel( + response, + value, + parentObject, + key, + loadServerReference + ) + ); + case "T": + parentObject = "$" + value.slice(2); + response = response._tempRefs; + if (null == response) + throw Error( + "Missing a temporary reference set but the RSC response returned a temporary reference. Pass a temporaryReference option with the set that was used with the reply." + ); + return response.get(parentObject); + case "Q": + return ( + (value = value.slice(2)), + getOutlinedModel(response, value, parentObject, key, createMap) + ); + case "W": + return ( + (value = value.slice(2)), + getOutlinedModel(response, value, parentObject, key, createSet) + ); + case "B": + return ( + (value = value.slice(2)), + getOutlinedModel(response, value, parentObject, key, createBlob) + ); + case "K": + return ( + (value = value.slice(2)), + getOutlinedModel(response, value, parentObject, key, createFormData) + ); + case "Z": + return resolveErrorProd(); + case "i": + return ( + (value = value.slice(2)), + getOutlinedModel(response, value, parentObject, key, extractIterator) + ); + case "I": + return Infinity; + case "-": + return "$-0" === value ? -0 : -Infinity; + case "N": + return NaN; + case "u": + return; + case "D": + return new Date(Date.parse(value.slice(2))); + case "n": + return BigInt(value.slice(2)); + default: + return ( + (value = value.slice(1)), + getOutlinedModel(response, value, parentObject, key, createModel) + ); + } + } + return value; +} +function missingCall() { + throw Error( + 'Trying to call a function from "use server" but the callServer option was not implemented in your router runtime.' + ); +} +function ResponseInstance( + bundlerConfig, + serverReferenceConfig, + moduleLoading, + callServer, + encodeFormAction, + nonce, + temporaryReferences, + allowPartialStream +) { + var chunks = new Map(); + this._bundlerConfig = bundlerConfig; + this._serverReferenceConfig = serverReferenceConfig; + this._moduleLoading = moduleLoading; + this._callServer = void 0 !== callServer ? callServer : missingCall; + this._encodeFormAction = encodeFormAction; + this._nonce = nonce; + this._chunks = chunks; + this._stringDecoder = new util.TextDecoder(); + this._closed = !1; + this._closedReason = null; + this._allowPartialStream = allowPartialStream; + this._tempRefs = temporaryReferences; +} +function createStreamState() { + return { _rowState: 0, _rowID: 0, _rowTag: 0, _rowLength: 0, _buffer: [] }; +} +function resolveBuffer(response, id, buffer) { + response = response._chunks; + var chunk = response.get(id); + chunk && "pending" !== chunk.status + ? chunk.reason.enqueueValue(buffer) + : ((buffer = new ReactPromise("fulfilled", buffer, null)), + response.set(id, buffer)); +} +function resolveModule(response, id, model) { + var chunks = response._chunks, + chunk = chunks.get(id); + model = parseModel(response, model); + var clientReference = resolveClientReference(response._bundlerConfig, model); + prepareDestinationWithChunks( + response._moduleLoading, + model[1], + response._nonce + ); + if ((model = preloadModule(clientReference))) { + if (chunk) { + var blockedChunk = chunk; + blockedChunk.status = "blocked"; + } else + (blockedChunk = new ReactPromise("blocked", null, null)), + chunks.set(id, blockedChunk); + model.then( + function () { + return resolveModuleChunk(response, blockedChunk, clientReference); + }, + function (error) { + return triggerErrorOnChunk(response, blockedChunk, error); + } + ); + } else + chunk + ? resolveModuleChunk(response, chunk, clientReference) + : ((chunk = new ReactPromise("resolved_module", clientReference, null)), + chunks.set(id, chunk)); +} +function resolveStream(response, id, stream, controller) { + var chunks = response._chunks, + chunk = chunks.get(id); + chunk + ? "pending" === chunk.status && + ((id = chunk.value), + (chunk.status = "fulfilled"), + (chunk.value = stream), + (chunk.reason = controller), + null !== id && wakeChunk(response, id, chunk.value, chunk)) + : ((response = new ReactPromise("fulfilled", stream, controller)), + chunks.set(id, response)); +} +function startReadableStream(response, id, type) { + var controller = null, + closed = !1; + type = new ReadableStream({ + type: type, + start: function (c) { + controller = c; + } + }); + var previousBlockedChunk = null; + resolveStream(response, id, type, { + enqueueValue: function (value) { + null === previousBlockedChunk + ? controller.enqueue(value) + : previousBlockedChunk.then(function () { + controller.enqueue(value); + }); + }, + enqueueModel: function (json) { + if (null === previousBlockedChunk) { + var chunk = new ReactPromise("resolved_model", json, response); + initializeModelChunk(chunk); + "fulfilled" === chunk.status + ? controller.enqueue(chunk.value) + : (chunk.then( + function (v) { + return controller.enqueue(v); + }, + function (e) { + return controller.error(e); + } + ), + (previousBlockedChunk = chunk)); + } else { + chunk = previousBlockedChunk; + var chunk$55 = new ReactPromise("pending", null, null); + chunk$55.then( + function (v) { + return controller.enqueue(v); + }, + function (e) { + return controller.error(e); + } + ); + previousBlockedChunk = chunk$55; + chunk.then(function () { + previousBlockedChunk === chunk$55 && (previousBlockedChunk = null); + resolveModelChunk(response, chunk$55, json); + }); + } + }, + close: function () { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) controller.close(); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.close(); + }); + } + }, + error: function (error) { + if (!closed) + if (((closed = !0), null === previousBlockedChunk)) + controller.error(error); + else { + var blockedChunk = previousBlockedChunk; + previousBlockedChunk = null; + blockedChunk.then(function () { + return controller.error(error); + }); + } + } + }); +} +function asyncIterator() { + return this; +} +function createIterator(next) { + next = { next: next }; + next[ASYNC_ITERATOR] = asyncIterator; + return next; +} +function startAsyncIterable(response, id, iterator) { + var buffer = [], + closed = !1, + nextWriteIndex = 0, + iterable = {}; + iterable[ASYNC_ITERATOR] = function () { + var nextReadIndex = 0; + return createIterator(function (arg) { + if (void 0 !== arg) + throw Error( + "Values cannot be passed to next() of AsyncIterables passed to Client Components." + ); + if (nextReadIndex === buffer.length) { + if (closed) + return new ReactPromise( + "fulfilled", + { done: !0, value: void 0 }, + null + ); + buffer[nextReadIndex] = new ReactPromise("pending", null, null); + } + return buffer[nextReadIndex++]; + }); + }; + resolveStream( + response, + id, + iterator ? iterable[ASYNC_ITERATOR]() : iterable, + { + enqueueValue: function (value) { + if (nextWriteIndex === buffer.length) + buffer[nextWriteIndex] = new ReactPromise( + "fulfilled", + { done: !1, value: value }, + null + ); + else { + var chunk = buffer[nextWriteIndex], + resolveListeners = chunk.value, + rejectListeners = chunk.reason; + chunk.status = "fulfilled"; + chunk.value = { done: !1, value: value }; + chunk.reason = null; + null !== resolveListeners && + wakeChunkIfInitialized( + response, + chunk, + resolveListeners, + rejectListeners + ); + } + nextWriteIndex++; + }, + enqueueModel: function (value) { + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !1 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !1 + ); + nextWriteIndex++; + }, + close: function (value) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length + ? (buffer[nextWriteIndex] = createResolvedIteratorResultChunk( + response, + value, + !0 + )) + : resolveIteratorResultChunk( + response, + buffer[nextWriteIndex], + value, + !0 + ), + nextWriteIndex++; + nextWriteIndex < buffer.length; + + ) + resolveIteratorResultChunk( + response, + buffer[nextWriteIndex++], + '"$undefined"', + !0 + ); + }, + error: function (error) { + if (!closed) + for ( + closed = !0, + nextWriteIndex === buffer.length && + (buffer[nextWriteIndex] = new ReactPromise( + "pending", + null, + null + )); + nextWriteIndex < buffer.length; + + ) + triggerErrorOnChunk(response, buffer[nextWriteIndex++], error); + } + } + ); +} +function resolveErrorProd() { + var error = Error( + "An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error." + ); + error.stack = "Error: " + error.message; + return error; +} +function mergeBuffer(buffer, lastChunk) { + for (var l = buffer.length, byteLength = lastChunk.length, i = 0; i < l; i++) + byteLength += buffer[i].byteLength; + byteLength = new Uint8Array(byteLength); + for (var i$56 = (i = 0); i$56 < l; i$56++) { + var chunk = buffer[i$56]; + byteLength.set(chunk, i); + i += chunk.byteLength; + } + byteLength.set(lastChunk, i); + return byteLength; +} +function resolveTypedArray( + response, + id, + buffer, + lastChunk, + constructor, + bytesPerElement +) { + buffer = + 0 === buffer.length && 0 === lastChunk.byteOffset % bytesPerElement + ? lastChunk + : mergeBuffer(buffer, lastChunk); + constructor = new constructor( + buffer.buffer, + buffer.byteOffset, + buffer.byteLength / bytesPerElement + ); + resolveBuffer(response, id, constructor); +} +function processFullBinaryRow(response, streamState, id, tag, buffer, chunk) { + switch (tag) { + case 65: + resolveBuffer(response, id, mergeBuffer(buffer, chunk).buffer); + return; + case 79: + resolveTypedArray(response, id, buffer, chunk, Int8Array, 1); + return; + case 111: + resolveBuffer( + response, + id, + 0 === buffer.length ? chunk : mergeBuffer(buffer, chunk) + ); + return; + case 85: + resolveTypedArray(response, id, buffer, chunk, Uint8ClampedArray, 1); + return; + case 83: + resolveTypedArray(response, id, buffer, chunk, Int16Array, 2); + return; + case 115: + resolveTypedArray(response, id, buffer, chunk, Uint16Array, 2); + return; + case 76: + resolveTypedArray(response, id, buffer, chunk, Int32Array, 4); + return; + case 108: + resolveTypedArray(response, id, buffer, chunk, Uint32Array, 4); + return; + case 71: + resolveTypedArray(response, id, buffer, chunk, Float32Array, 4); + return; + case 103: + resolveTypedArray(response, id, buffer, chunk, Float64Array, 8); + return; + case 77: + resolveTypedArray(response, id, buffer, chunk, BigInt64Array, 8); + return; + case 109: + resolveTypedArray(response, id, buffer, chunk, BigUint64Array, 8); + return; + case 86: + resolveTypedArray(response, id, buffer, chunk, DataView, 1); + return; + } + for ( + var stringDecoder = response._stringDecoder, row = "", i = 0; + i < buffer.length; + i++ + ) + row += stringDecoder.decode(buffer[i], decoderOptions); + row += stringDecoder.decode(chunk); + processFullStringRow(response, streamState, id, tag, row); +} +function processFullStringRow(response, streamState, id, tag, row) { + switch (tag) { + case 73: + resolveModule(response, id, row); + break; + case 72: + id = row[0]; + row = row.slice(1); + response = parseModel(response, row); + row = ReactDOMSharedInternals.d; + switch (id) { + case "D": + row.D(response); + break; + case "C": + "string" === typeof response + ? row.C(response) + : row.C(response[0], response[1]); + break; + case "L": + id = response[0]; + streamState = response[1]; + 3 === response.length + ? row.L(id, streamState, response[2]) + : row.L(id, streamState); + break; + case "m": + "string" === typeof response + ? row.m(response) + : row.m(response[0], response[1]); + break; + case "X": + "string" === typeof response + ? row.X(response) + : row.X(response[0], response[1]); + break; + case "S": + "string" === typeof response + ? row.S(response) + : row.S( + response[0], + 0 === response[1] ? void 0 : response[1], + 3 === response.length ? response[2] : void 0 + ); + break; + case "M": + "string" === typeof response + ? row.M(response) + : row.M(response[0], response[1]); + } + break; + case 69: + streamState = response._chunks; + tag = streamState.get(id); + row = JSON.parse(row); + var error = resolveErrorProd(); + error.digest = row.digest; + tag + ? triggerErrorOnChunk(response, tag, error) + : ((response = new ReactPromise("rejected", null, error)), + streamState.set(id, response)); + break; + case 84: + response = response._chunks; + (streamState = response.get(id)) && "pending" !== streamState.status + ? streamState.reason.enqueueValue(row) + : ((row = new ReactPromise("fulfilled", row, null)), + response.set(id, row)); + break; + case 78: + case 68: + case 74: + case 87: + throw Error( + "Failed to read a RSC payload created by a development version of React on the server while using a production version on the client. Always use matching versions on the server and the client." + ); + case 82: + startReadableStream(response, id, void 0); + break; + case 114: + startReadableStream(response, id, "bytes"); + break; + case 88: + startAsyncIterable(response, id, !1); + break; + case 120: + startAsyncIterable(response, id, !0); + break; + case 67: + (id = response._chunks.get(id)) && + "fulfilled" === id.status && + id.reason.close("" === row ? '"$undefined"' : row); + break; + default: + (streamState = response._chunks), + (tag = streamState.get(id)) + ? resolveModelChunk(response, tag, row) + : ((response = new ReactPromise("resolved_model", row, response)), + streamState.set(id, response)); + } +} +function processBinaryChunk(weakResponse, streamState, chunk) { + for ( + var i = 0, + rowState = streamState._rowState, + rowID = streamState._rowID, + rowTag = streamState._rowTag, + rowLength = streamState._rowLength, + buffer = streamState._buffer, + chunkLength = chunk.length; + i < chunkLength; + + ) { + var lastIdx = -1; + switch (rowState) { + case 0: + lastIdx = chunk[i++]; + 58 === lastIdx + ? (rowState = 1) + : (rowID = + (rowID << 4) | (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 1: + rowState = chunk[i]; + 84 === rowState || + 65 === rowState || + 79 === rowState || + 111 === rowState || + 98 === rowState || + 85 === rowState || + 83 === rowState || + 115 === rowState || + 76 === rowState || + 108 === rowState || + 71 === rowState || + 103 === rowState || + 77 === rowState || + 109 === rowState || + 86 === rowState + ? ((rowTag = rowState), (rowState = 2), i++) + : (64 < rowState && 91 > rowState) || + 35 === rowState || + 114 === rowState || + 120 === rowState + ? ((rowTag = rowState), (rowState = 3), i++) + : ((rowTag = 0), (rowState = 3)); + continue; + case 2: + lastIdx = chunk[i++]; + 44 === lastIdx + ? (rowState = 4) + : (rowLength = + (rowLength << 4) | (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 3: + lastIdx = chunk.indexOf(10, i); + break; + case 4: + (lastIdx = i + rowLength), lastIdx > chunk.length && (lastIdx = -1); + } + var offset = chunk.byteOffset + i; + if (-1 < lastIdx) + (rowLength = new Uint8Array(chunk.buffer, offset, lastIdx - i)), + 98 === rowTag + ? resolveBuffer( + weakResponse, + rowID, + lastIdx === chunkLength ? rowLength : rowLength.slice() + ) + : processFullBinaryRow( + weakResponse, + streamState, + rowID, + rowTag, + buffer, + rowLength + ), + (i = lastIdx), + 3 === rowState && i++, + (rowLength = rowID = rowTag = rowState = 0), + (buffer.length = 0); + else { + chunk = new Uint8Array(chunk.buffer, offset, chunk.byteLength - i); + 98 === rowTag + ? ((rowLength -= chunk.byteLength), + resolveBuffer(weakResponse, rowID, chunk)) + : (buffer.push(chunk), (rowLength -= chunk.byteLength)); + break; + } + } + streamState._rowState = rowState; + streamState._rowID = rowID; + streamState._rowTag = rowTag; + streamState._rowLength = rowLength; +} +function parseModel(response, json) { + json = JSON.parse(json); + return reviveModel(response, json, { "": json }, ""); +} +function reviveModel(response, value, parentObject, key) { + if ("string" === typeof value) + return "$" === value[0] + ? parseModelString(response, parentObject, key, value) + : value; + if ("object" !== typeof value || null === value) return value; + if (isArrayImpl(value)) { + for (var i = 0; i < value.length; i++) + value[i] = reviveModel(response, value[i], value, "" + i); + return value[0] === REACT_ELEMENT_TYPE + ? (value[0] === REACT_ELEMENT_TYPE + ? ((response = { + $$typeof: REACT_ELEMENT_TYPE, + type: value[1], + key: value[2], + ref: null, + props: value[3] + }), + null !== initializingHandler && + ((value = initializingHandler), + (initializingHandler = value.parent), + value.errored + ? ((response = new ReactPromise( + "rejected", + null, + value.reason + )), + (response = createLazyChunkWrapper(response))) + : 0 < value.deps && + ((i = new ReactPromise("blocked", null, null)), + (value.value = response), + (value.chunk = i), + (response = createLazyChunkWrapper(i))))) + : (response = value), + response) + : value; + } + for (i in value) + hasOwnProperty.call(value, i) && + ("__proto__" === i + ? delete value[i] + : ((parentObject = reviveModel(response, value[i], value, i)), + void 0 !== parentObject + ? (value[i] = parentObject) + : delete value[i])); + return value; +} +function close(weakResponse) { + weakResponse._allowPartialStream + ? ((weakResponse._closed = !0), + weakResponse._chunks.forEach(function (chunk) { + "pending" === chunk.status + ? ((chunk.status = "halted"), + (chunk.value = null), + (chunk.reason = null)) + : "fulfilled" === chunk.status && + null !== chunk.reason && + chunk.reason.close('"$undefined"'); + })) + : reportGlobalError(weakResponse, Error("Connection closed.")); +} +function noServerCall$1() { + throw Error( + "Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead." + ); +} +function createResponseFromOptions(options) { + return new ResponseInstance( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverConsumerModuleMap, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + noServerCall$1, + options.encodeFormAction, + "string" === typeof options.nonce ? options.nonce : void 0, + options && options.temporaryReferences + ? options.temporaryReferences + : void 0, + options && options.unstable_allowPartialStream + ? options.unstable_allowPartialStream + : !1 + ); +} +function startReadingFromStream$1(response, stream, onDone) { + function progress(_ref) { + var value = _ref.value; + if (_ref.done) return onDone(); + processBinaryChunk(response, streamState, value); + return reader.read().then(progress).catch(error); + } + function error(e) { + reportGlobalError(response, e); + } + var streamState = createStreamState(), + reader = stream.getReader(); + reader.read().then(progress).catch(error); +} +function noServerCall() { + throw Error( + "Server Functions cannot be called during initial render. This would create a fetch waterfall. Try to use a Server Component to pass data to Client Components instead." + ); +} +function startReadingFromStream(response, stream, onEnd) { + var streamState = createStreamState(); + stream.on("data", function (chunk) { + if ("string" === typeof chunk) { + for ( + var i = 0, + rowState = streamState._rowState, + rowID = streamState._rowID, + rowTag = streamState._rowTag, + rowLength = streamState._rowLength, + buffer = streamState._buffer, + chunkLength = chunk.length; + i < chunkLength; + + ) { + var lastIdx = -1; + switch (rowState) { + case 0: + lastIdx = chunk.charCodeAt(i++); + 58 === lastIdx + ? (rowState = 1) + : (rowID = + (rowID << 4) | (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 1: + rowState = chunk.charCodeAt(i); + 84 === rowState || + 65 === rowState || + 79 === rowState || + 111 === rowState || + 85 === rowState || + 83 === rowState || + 115 === rowState || + 76 === rowState || + 108 === rowState || + 71 === rowState || + 103 === rowState || + 77 === rowState || + 109 === rowState || + 86 === rowState + ? ((rowTag = rowState), (rowState = 2), i++) + : (64 < rowState && 91 > rowState) || + 114 === rowState || + 120 === rowState + ? ((rowTag = rowState), (rowState = 3), i++) + : ((rowTag = 0), (rowState = 3)); + continue; + case 2: + lastIdx = chunk.charCodeAt(i++); + 44 === lastIdx + ? (rowState = 4) + : (rowLength = + (rowLength << 4) | + (96 < lastIdx ? lastIdx - 87 : lastIdx - 48)); + continue; + case 3: + lastIdx = chunk.indexOf("\n", i); + break; + case 4: + if (84 !== rowTag) + throw Error( + "Binary RSC chunks cannot be encoded as strings. This is a bug in the wiring of the React streams." + ); + if (rowLength < chunk.length || chunk.length > 3 * rowLength) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + lastIdx = chunk.length; + } + if (-1 < lastIdx) { + if (0 < buffer.length) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + i = chunk.slice(i, lastIdx); + processFullStringRow(response, streamState, rowID, rowTag, i); + i = lastIdx; + 3 === rowState && i++; + rowLength = rowID = rowTag = rowState = 0; + buffer.length = 0; + } else if (chunk.length !== i) + throw Error( + "String chunks need to be passed in their original shape. Not split into smaller string chunks. This is a bug in the wiring of the React streams." + ); + } + streamState._rowState = rowState; + streamState._rowID = rowID; + streamState._rowTag = rowTag; + streamState._rowLength = rowLength; + } else processBinaryChunk(response, streamState, chunk); + }); + stream.on("error", function (error) { + reportGlobalError(response, error); + }); + stream.on("end", onEnd); +} +__rspack_unused_export = function (promiseForResponse) { + var response = createResponseFromOptions( + 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {} + ); + promiseForResponse.then( + function (r) { + startReadingFromStream$1(response, r.body, close.bind(null, response)); + }, + function (e) { + reportGlobalError(response, e); + } + ); + return getChunk(response, 0); +}; +__rspack_unused_export = function (stream, options) { + options = new ResponseInstance( + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverConsumerModuleMap, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.serverManifest, + {"clientManifest":{},"cssLinkProps":{},"entryCssFiles":{},"entryJsFiles":[],"moduleLoading":{"prefix":""},"serverConsumerModuleMap":{},"serverManifest":{}}.moduleLoading, + noServerCall, + options ? options.encodeFormAction : void 0, + options && "string" === typeof options.nonce ? options.nonce : void 0, + void 0, + options && options.unstable_allowPartialStream + ? options.unstable_allowPartialStream + : !1 + ); + startReadingFromStream(options, stream, close.bind(null, options)); + return getChunk(options, 0); +}; +exports.createFromReadableStream = function (stream) { + var response = createResponseFromOptions( + 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {} + ); + startReadingFromStream$1(response, stream, close.bind(null, response)); + return getChunk(response, 0); +}; +__rspack_unused_export = function (id) { + return createServerReference$1(id, noServerCall$1); +}; +__rspack_unused_export = function () { + return new Map(); +}; +__rspack_unused_export = function (value, options) { + return new Promise(function (resolve, reject) { + var abort = processReply( + value, + "", + options && options.temporaryReferences + ? options.temporaryReferences + : void 0, + resolve, + reject + ); + if (options && options.signal) { + var signal = options.signal; + if (signal.aborted) abort(signal.reason); + else { + var listener = function () { + abort(signal.reason); + signal.removeEventListener("abort", listener); + }; + signal.addEventListener("abort", listener); + } + } + }); +}; +__rspack_unused_export = function (reference, id, encodeFormAction) { + registerBoundServerReference(reference, id, null, encodeFormAction); + return reference; +}; + + +}, +"./node_modules/react-server-dom-rspack/client.node.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react-server-dom-rspack/cjs/react-server-dom-rspack-client.node.development.js"); +} + + +}, +"./node_modules/react/cjs/react-jsx-runtime.development.js"(__unused_rspack_module, exports, __webpack_require__) { +var __rspack_unused_export; +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE + ? null + : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch ( + ("number" === typeof type.tag && + console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), + type.$$typeof) + ) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || + ((type = innerType.displayName || innerType.name || ""), + (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); + return type; + case REACT_MEMO_TYPE: + return ( + (innerType = type.displayName || null), + null !== innerType + ? innerType + : getComponentNameFromType(type.type) || "Memo" + ); + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) {} + } + return null; + } + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = !1; + } catch (e) { + JSCompiler_inline_result = !0; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = + ("function" === typeof Symbol && + Symbol.toStringTag && + value[Symbol.toStringTag]) || + value.constructor.name || + "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ( + "object" === typeof type && + null !== type && + type.$$typeof === REACT_LAZY_TYPE + ) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternals.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return !1; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || + ((specialPropKeyWarningShown = !0), + console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = !0; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: !0 + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || + ((didWarnAboutElementRef[componentName] = !0), + console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + props: props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) + ? Object.defineProperty(type, "ref", { + enumerable: !1, + get: elementRefGetterWithDeprecationWarning + }) + : Object.defineProperty(type, "ref", { enumerable: !1, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function jsxDEVImpl( + type, + config, + maybeKey, + isStaticChildren, + debugStack, + debugTask + ) { + var children = config.children; + if (void 0 !== children) + if (isStaticChildren) + if (isArrayImpl(children)) { + for ( + isStaticChildren = 0; + isStaticChildren < children.length; + isStaticChildren++ + ) + validateChildKeys(children[isStaticChildren]); + Object.freeze && Object.freeze(children); + } else + console.error( + "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." + ); + else validateChildKeys(children); + if (hasOwnProperty.call(config, "key")) { + children = getComponentNameFromType(type); + var keys = Object.keys(config).filter(function (k) { + return "key" !== k; + }); + isStaticChildren = + 0 < keys.length + ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" + : "{key: someKey}"; + didWarnAboutKeySpread[children + isStaticChildren] || + ((keys = + 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}"), + console.error( + 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', + isStaticChildren, + children, + keys, + children + ), + (didWarnAboutKeySpread[children + isStaticChildren] = !0)); + } + children = null; + void 0 !== maybeKey && + (checkKeyStringCoercion(maybeKey), (children = "" + maybeKey)); + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (children = "" + config.key)); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + children && + defineKeyPropWarningGetter( + maybeKey, + "function" === typeof type + ? type.displayName || type.name || "Unknown" + : type + ); + return ReactElement( + type, + children, + maybeKey, + getOwner(), + debugStack, + debugTask + ); + } + function validateChildKeys(node) { + isValidElement(node) + ? node._store && (node._store.validated = 1) + : "object" === typeof node && + null !== node && + node.$$typeof === REACT_LAZY_TYPE && + ("fulfilled" === node._payload.status + ? isValidElement(node._payload.value) && + node._payload.value._store && + (node._payload.value._store.validated = 1) + : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + } + var React = __webpack_require__("./node_modules/react/index.js"), + REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), + ReactSharedInternals = + React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, + hasOwnProperty = Object.prototype.hasOwnProperty, + isArrayImpl = Array.isArray, + createTask = console.createTask + ? console.createTask + : function () { + return null; + }; + React = { + react_stack_bottom_frame: function (callStackForError) { + return callStackForError(); + } + }; + var specialPropKeyWarningShown; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind( + React, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutKeySpread = {}; + __rspack_unused_export = REACT_FRAGMENT_TYPE; + exports.jsx = function (type, config, maybeKey) { + var trackActualOwner = + 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; + if (trackActualOwner) { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + var debugStackDEV = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + } else debugStackDEV = unknownOwnerDebugStack; + return jsxDEVImpl( + type, + config, + maybeKey, + !1, + debugStackDEV, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + __rspack_unused_export = function (type, config, maybeKey) { + var trackActualOwner = + 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; + if (trackActualOwner) { + var previousStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 10; + var debugStackDEV = Error("react-stack-top-frame"); + Error.stackTraceLimit = previousStackTraceLimit; + } else debugStackDEV = unknownOwnerDebugStack; + return jsxDEVImpl( + type, + config, + maybeKey, + !0, + debugStackDEV, + trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + })(); + + +}, +"./node_modules/react/cjs/react-jsx-runtime.production.js"(__unused_rspack_module, exports) { +var __rspack_unused_export; +/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); +function jsxProd(type, config, maybeKey) { + var key = null; + void 0 !== maybeKey && (key = "" + maybeKey); + void 0 !== config.key && (key = "" + config.key); + if ("key" in config) { + maybeKey = {}; + for (var propName in config) + "key" !== propName && (maybeKey[propName] = config[propName]); + } else maybeKey = config; + config = maybeKey.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + ref: void 0 !== config ? config : null, + props: maybeKey + }; +} +__rspack_unused_export = REACT_FRAGMENT_TYPE; +exports.jsx = jsxProd; +__rspack_unused_export = jsxProd; + + +}, +"./node_modules/react/cjs/react.development.js"(module, exports, __webpack_require__) { +/* module decorator */ module = __webpack_require__.nmd(module); +/** + * @license React + * react.development.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +"production" !== process.env.NODE_ENV && + (function () { + function defineDeprecationWarning(methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function () { + console.warn( + "%s(...) is deprecated in plain JavaScript React classes. %s", + info[0], + info[1] + ); + } + }); + } + function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) + return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; + } + function warnNoop(publicInstance, callerName) { + publicInstance = + ((publicInstance = publicInstance.constructor) && + (publicInstance.displayName || publicInstance.name)) || + "ReactClass"; + var warningKey = publicInstance + "." + callerName; + didWarnStateUpdateForUnmountedComponent[warningKey] || + (console.error( + "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", + callerName, + publicInstance + ), + (didWarnStateUpdateForUnmountedComponent[warningKey] = !0)); + } + function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + function ComponentDummy() {} + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + function noop() {} + function testStringCoercion(value) { + return "" + value; + } + function checkKeyStringCoercion(value) { + try { + testStringCoercion(value); + var JSCompiler_inline_result = !1; + } catch (e) { + JSCompiler_inline_result = !0; + } + if (JSCompiler_inline_result) { + JSCompiler_inline_result = console; + var JSCompiler_temp_const = JSCompiler_inline_result.error; + var JSCompiler_inline_result$jscomp$0 = + ("function" === typeof Symbol && + Symbol.toStringTag && + value[Symbol.toStringTag]) || + value.constructor.name || + "Object"; + JSCompiler_temp_const.call( + JSCompiler_inline_result, + "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", + JSCompiler_inline_result$jscomp$0 + ); + return testStringCoercion(value); + } + } + function getComponentNameFromType(type) { + if (null == type) return null; + if ("function" === typeof type) + return type.$$typeof === REACT_CLIENT_REFERENCE + ? null + : type.displayName || type.name || null; + if ("string" === typeof type) return type; + switch (type) { + case REACT_FRAGMENT_TYPE: + return "Fragment"; + case REACT_PROFILER_TYPE: + return "Profiler"; + case REACT_STRICT_MODE_TYPE: + return "StrictMode"; + case REACT_SUSPENSE_TYPE: + return "Suspense"; + case REACT_SUSPENSE_LIST_TYPE: + return "SuspenseList"; + case REACT_ACTIVITY_TYPE: + return "Activity"; + case REACT_VIEW_TRANSITION_TYPE: + return "ViewTransition"; + } + if ("object" === typeof type) + switch ( + ("number" === typeof type.tag && + console.error( + "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." + ), + type.$$typeof) + ) { + case REACT_PORTAL_TYPE: + return "Portal"; + case REACT_CONTEXT_TYPE: + return type.displayName || "Context"; + case REACT_CONSUMER_TYPE: + return (type._context.displayName || "Context") + ".Consumer"; + case REACT_FORWARD_REF_TYPE: + var innerType = type.render; + type = type.displayName; + type || + ((type = innerType.displayName || innerType.name || ""), + (type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef")); + return type; + case REACT_MEMO_TYPE: + return ( + (innerType = type.displayName || null), + null !== innerType + ? innerType + : getComponentNameFromType(type.type) || "Memo" + ); + case REACT_LAZY_TYPE: + innerType = type._payload; + type = type._init; + try { + return getComponentNameFromType(type(innerType)); + } catch (x) {} + } + return null; + } + function getTaskName(type) { + if (type === REACT_FRAGMENT_TYPE) return "<>"; + if ( + "object" === typeof type && + null !== type && + type.$$typeof === REACT_LAZY_TYPE + ) + return "<...>"; + try { + var name = getComponentNameFromType(type); + return name ? "<" + name + ">" : "<...>"; + } catch (x) { + return "<...>"; + } + } + function getOwner() { + var dispatcher = ReactSharedInternals.A; + return null === dispatcher ? null : dispatcher.getOwner(); + } + function UnknownOwner() { + return Error("react-stack-top-frame"); + } + function hasValidKey(config) { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) return !1; + } + return void 0 !== config.key; + } + function defineKeyPropWarningGetter(props, displayName) { + function warnAboutAccessingKey() { + specialPropKeyWarningShown || + ((specialPropKeyWarningShown = !0), + console.error( + "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", + displayName + )); + } + warnAboutAccessingKey.isReactWarning = !0; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: !0 + }); + } + function elementRefGetterWithDeprecationWarning() { + var componentName = getComponentNameFromType(this.type); + didWarnAboutElementRef[componentName] || + ((didWarnAboutElementRef[componentName] = !0), + console.error( + "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." + )); + componentName = this.props.ref; + return void 0 !== componentName ? componentName : null; + } + function ReactElement(type, key, props, owner, debugStack, debugTask) { + var refProp = props.ref; + type = { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + props: props, + _owner: owner + }; + null !== (void 0 !== refProp ? refProp : null) + ? Object.defineProperty(type, "ref", { + enumerable: !1, + get: elementRefGetterWithDeprecationWarning + }) + : Object.defineProperty(type, "ref", { enumerable: !1, value: null }); + type._store = {}; + Object.defineProperty(type._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: 0 + }); + Object.defineProperty(type, "_debugInfo", { + configurable: !1, + enumerable: !1, + writable: !0, + value: null + }); + Object.defineProperty(type, "_debugStack", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugStack + }); + Object.defineProperty(type, "_debugTask", { + configurable: !1, + enumerable: !1, + writable: !0, + value: debugTask + }); + Object.freeze && (Object.freeze(type.props), Object.freeze(type)); + return type; + } + function cloneAndReplaceKey(oldElement, newKey) { + newKey = ReactElement( + oldElement.type, + newKey, + oldElement.props, + oldElement._owner, + oldElement._debugStack, + oldElement._debugTask + ); + oldElement._store && + (newKey._store.validated = oldElement._store.validated); + return newKey; + } + function validateChildKeys(node) { + isValidElement(node) + ? node._store && (node._store.validated = 1) + : "object" === typeof node && + null !== node && + node.$$typeof === REACT_LAZY_TYPE && + ("fulfilled" === node._payload.status + ? isValidElement(node._payload.value) && + node._payload.value._store && + (node._payload.value._store.validated = 1) + : node._store && (node._store.validated = 1)); + } + function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); + } + function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return ( + "$" + + key.replace(/[=:]/g, function (match) { + return escaperLookup[match]; + }) + ); + } + function getElementKey(element, index) { + return "object" === typeof element && + null !== element && + null != element.key + ? (checkKeyStringCoercion(element.key), escape("" + element.key)) + : index.toString(36); + } + function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ( + ("string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), + (thenable.reason = error)); + } + )), + thenable.status) + ) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = !1; + if (null === children) invokeCallback = !0; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = !0; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = !0; + break; + case REACT_LAZY_TYPE: + return ( + (invokeCallback = children._init), + mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ) + ); + } + } + if (invokeCallback) { + invokeCallback = children; + callback = callback(invokeCallback); + var childKey = + "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar; + isArrayImpl(callback) + ? ((escapedPrefix = ""), + null != childKey && + (escapedPrefix = + childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), + mapIntoArray(callback, array, escapedPrefix, "", function (c) { + return c; + })) + : null != callback && + (isValidElement(callback) && + (null != callback.key && + ((invokeCallback && invokeCallback.key === callback.key) || + checkKeyStringCoercion(callback.key)), + (escapedPrefix = cloneAndReplaceKey( + callback, + escapedPrefix + + (null == callback.key || + (invokeCallback && invokeCallback.key === callback.key) + ? "" + : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + + childKey + )), + "" !== nameSoFar && + null != invokeCallback && + isValidElement(invokeCallback) && + null == invokeCallback.key && + invokeCallback._store && + !invokeCallback._store.validated && + (escapedPrefix._store.validated = 2), + (callback = escapedPrefix)), + array.push(callback)); + return 1; + } + invokeCallback = 0; + childKey = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + (nameSoFar = children[i]), + (type = childKey + getElementKey(nameSoFar, i)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if (((i = getIteratorFn(children)), "function" === typeof i)) + for ( + i === children.entries && + (didWarnAboutMaps || + console.warn( + "Using Maps as children is not supported. Use an array of keyed ReactElements instead." + ), + (didWarnAboutMaps = !0)), + children = i.call(children), + i = 0; + !(nameSoFar = children.next()).done; + + ) + (nameSoFar = nameSoFar.value), + (type = childKey + getElementKey(nameSoFar, i++)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === array + ? "object with keys {" + Object.keys(children).join(", ") + "}" + : array) + + "). If you meant to render a collection of children, use an array instead." + ); + } + return invokeCallback; + } + function mapChildren(children, func, context) { + if (null == children) return children; + var result = [], + count = 0; + mapIntoArray(children, result, "", "", function (child) { + return func.call(context, child, count++); + }); + return result; + } + function lazyInitializer(payload) { + if (-1 === payload._status) { + var resolveDebugValue = null, + rejectDebugValue = null, + ioInfo = payload._ioInfo; + null != ioInfo && + ((ioInfo.start = ioInfo.end = performance.now()), + (ioInfo.value = new Promise(function (resolve, reject) { + resolveDebugValue = resolve; + rejectDebugValue = reject; + }))); + ioInfo = payload._result; + var thenable = ioInfo(); + thenable.then( + function (moduleObject) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 1; + payload._result = moduleObject; + var _ioInfo = payload._ioInfo; + if (null != _ioInfo) { + _ioInfo.end = performance.now(); + var debugValue = + null == moduleObject ? void 0 : moduleObject.default; + resolveDebugValue(debugValue); + _ioInfo.value.status = "fulfilled"; + _ioInfo.value.value = debugValue; + } + void 0 === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = moduleObject)); + } + }, + function (error) { + if (0 === payload._status || -1 === payload._status) { + payload._status = 2; + payload._result = error; + var _ioInfo2 = payload._ioInfo; + null != _ioInfo2 && + ((_ioInfo2.end = performance.now()), + _ioInfo2.value.then(noop, noop), + rejectDebugValue(error), + (_ioInfo2.value.status = "rejected"), + (_ioInfo2.value.reason = error)); + void 0 === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + } + ); + ioInfo = payload._ioInfo; + if (null != ioInfo) { + var displayName = thenable.displayName; + "string" === typeof displayName && (ioInfo.name = displayName); + } + -1 === payload._status && + ((payload._status = 0), (payload._result = thenable)); + } + if (1 === payload._status) + return ( + (ioInfo = payload._result), + void 0 === ioInfo && + console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", + ioInfo + ), + "default" in ioInfo || + console.error( + "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", + ioInfo + ), + ioInfo.default + ); + throw payload._result; + } + function resolveDispatcher() { + var dispatcher = ReactSharedInternals.H; + null === dispatcher && + console.error( + "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." + ); + return dispatcher; + } + function releaseAsyncTransition() { + ReactSharedInternals.asyncTransitions--; + } + function startTransition(scope) { + var prevTransition = ReactSharedInternals.T, + currentTransition = {}; + currentTransition.types = + null !== prevTransition ? prevTransition.types : null; + currentTransition._updatedFibers = new Set(); + ReactSharedInternals.T = currentTransition; + try { + var returnValue = scope(), + onStartTransitionFinish = ReactSharedInternals.S; + null !== onStartTransitionFinish && + onStartTransitionFinish(currentTransition, returnValue); + "object" === typeof returnValue && + null !== returnValue && + "function" === typeof returnValue.then && + (ReactSharedInternals.asyncTransitions++, + returnValue.then(releaseAsyncTransition, releaseAsyncTransition), + returnValue.then(noop, reportGlobalError)); + } catch (error) { + reportGlobalError(error); + } finally { + null === prevTransition && + currentTransition._updatedFibers && + ((scope = currentTransition._updatedFibers.size), + currentTransition._updatedFibers.clear(), + 10 < scope && + console.warn( + "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table." + )), + null !== prevTransition && + null !== currentTransition.types && + (null !== prevTransition.types && + prevTransition.types !== currentTransition.types && + console.error( + "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React." + ), + (prevTransition.types = currentTransition.types)), + (ReactSharedInternals.T = prevTransition); + } + } + function addTransitionType(type) { + var transition = ReactSharedInternals.T; + if (null !== transition) { + var transitionTypes = transition.types; + null === transitionTypes + ? (transition.types = [type]) + : -1 === transitionTypes.indexOf(type) && transitionTypes.push(type); + } else + 0 === ReactSharedInternals.asyncTransitions && + console.error( + "addTransitionType can only be called inside a `startTransition()` callback. It must be associated with a specific Transition." + ), + startTransition(addTransitionType.bind(null, type)); + } + function enqueueTask(task) { + if (null === enqueueTaskImpl) + try { + var requireString = ("require" + Math.random()).slice(0, 7); + enqueueTaskImpl = (module && module[requireString]).call( + module, + "timers" + ).setImmediate; + } catch (_err) { + enqueueTaskImpl = function (callback) { + !1 === didWarnAboutMessageChannel && + ((didWarnAboutMessageChannel = !0), + "undefined" === typeof MessageChannel && + console.error( + "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning." + )); + var channel = new MessageChannel(); + channel.port1.onmessage = callback; + channel.port2.postMessage(void 0); + }; + } + return enqueueTaskImpl(task); + } + function aggregateErrors(errors) { + return 1 < errors.length && "function" === typeof AggregateError + ? new AggregateError(errors) + : errors[0]; + } + function popActScope(prevActQueue, prevActScopeDepth) { + prevActScopeDepth !== actScopeDepth - 1 && + console.error( + "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. " + ); + actScopeDepth = prevActScopeDepth; + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + var queue = ReactSharedInternals.actQueue; + if (null !== queue) + if (0 !== queue.length) + try { + flushActQueue(queue); + enqueueTask(function () { + return recursivelyFlushAsyncActWork(returnValue, resolve, reject); + }); + return; + } catch (error) { + ReactSharedInternals.thrownErrors.push(error); + } + else ReactSharedInternals.actQueue = null; + 0 < ReactSharedInternals.thrownErrors.length + ? ((queue = aggregateErrors(ReactSharedInternals.thrownErrors)), + (ReactSharedInternals.thrownErrors.length = 0), + reject(queue)) + : resolve(returnValue); + } + function flushActQueue(queue) { + if (!isFlushing) { + isFlushing = !0; + var i = 0; + try { + for (; i < queue.length; i++) { + var callback = queue[i]; + do { + ReactSharedInternals.didUsePromise = !1; + var continuation = callback(!1); + if (null !== continuation) { + if (ReactSharedInternals.didUsePromise) { + queue[i] = callback; + queue.splice(0, i); + return; + } + callback = continuation; + } else break; + } while (1); + } + queue.length = 0; + } catch (error) { + queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error); + } finally { + isFlushing = !1; + } + } + } + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && + "function" === + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); + var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator, + didWarnStateUpdateForUnmountedComponent = {}, + ReactNoopUpdateQueue = { + isMounted: function () { + return !1; + }, + enqueueForceUpdate: function (publicInstance) { + warnNoop(publicInstance, "forceUpdate"); + }, + enqueueReplaceState: function (publicInstance) { + warnNoop(publicInstance, "replaceState"); + }, + enqueueSetState: function (publicInstance) { + warnNoop(publicInstance, "setState"); + } + }, + assign = Object.assign, + emptyObject = {}; + Object.freeze(emptyObject); + Component.prototype.isReactComponent = {}; + Component.prototype.setState = function (partialState, callback) { + if ( + "object" !== typeof partialState && + "function" !== typeof partialState && + null != partialState + ) + throw Error( + "takes an object of state variables to update or a function which returns an object of state variables." + ); + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + var deprecatedAPIs = { + isMounted: [ + "isMounted", + "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." + ], + replaceState: [ + "replaceState", + "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." + ] + }; + for (fnName in deprecatedAPIs) + deprecatedAPIs.hasOwnProperty(fnName) && + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + ComponentDummy.prototype = Component.prototype; + deprecatedAPIs = PureComponent.prototype = new ComponentDummy(); + deprecatedAPIs.constructor = PureComponent; + assign(deprecatedAPIs, Component.prototype); + deprecatedAPIs.isPureReactComponent = !0; + var isArrayImpl = Array.isArray, + REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), + ReactSharedInternals = { + H: null, + A: null, + T: null, + S: null, + actQueue: null, + asyncTransitions: 0, + isBatchingLegacy: !1, + didScheduleLegacyUpdate: !1, + didUsePromise: !1, + thrownErrors: [], + getCurrentStack: null, + recentlyCreatedOwnerStacks: 0 + }, + hasOwnProperty = Object.prototype.hasOwnProperty, + createTask = console.createTask + ? console.createTask + : function () { + return null; + }; + deprecatedAPIs = { + react_stack_bottom_frame: function (callStackForError) { + return callStackForError(); + } + }; + var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime; + var didWarnAboutElementRef = {}; + var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind( + deprecatedAPIs, + UnknownOwner + )(); + var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); + var didWarnAboutMaps = !1, + userProvidedKeyEscapeRegex = /\/+/g, + reportGlobalError = + "function" === typeof reportError + ? reportError + : function (error) { + if ( + "object" === typeof window && + "function" === typeof window.ErrorEvent + ) { + var event = new window.ErrorEvent("error", { + bubbles: !0, + cancelable: !0, + message: + "object" === typeof error && + null !== error && + "string" === typeof error.message + ? String(error.message) + : String(error), + error: error + }); + if (!window.dispatchEvent(event)) return; + } else if ( + "object" === typeof process && + "function" === typeof process.emit + ) { + process.emit("uncaughtException", error); + return; + } + console.error(error); + }, + didWarnAboutMessageChannel = !1, + enqueueTaskImpl = null, + actScopeDepth = 0, + didWarnNoAwaitAct = !1, + isFlushing = !1, + queueSeveralMicrotasks = + "function" === typeof queueMicrotask + ? function (callback) { + queueMicrotask(function () { + return queueMicrotask(callback); + }); + } + : enqueueTask; + deprecatedAPIs = Object.freeze({ + __proto__: null, + c: function (size) { + return resolveDispatcher().useMemoCache(size); + } + }); + var fnName = { + map: mapChildren, + forEach: function (children, forEachFunc, forEachContext) { + mapChildren( + children, + function () { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function (children) { + var n = 0; + mapChildren(children, function () { + n++; + }); + return n; + }, + toArray: function (children) { + return ( + mapChildren(children, function (child) { + return child; + }) || [] + ); + }, + only: function (children) { + if (!isValidElement(children)) + throw Error( + "React.Children.only expected to receive a single React element child." + ); + return children; + } + }; + exports.Activity = REACT_ACTIVITY_TYPE; + exports.Children = fnName; + exports.Component = Component; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.ViewTransition = REACT_VIEW_TRANSITION_TYPE; + exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + ReactSharedInternals; + exports.__COMPILER_RUNTIME = deprecatedAPIs; + exports.act = function (callback) { + var prevActQueue = ReactSharedInternals.actQueue, + prevActScopeDepth = actScopeDepth; + actScopeDepth++; + var queue = (ReactSharedInternals.actQueue = + null !== prevActQueue ? prevActQueue : []), + didAwaitActCall = !1; + try { + var result = callback(); + } catch (error) { + ReactSharedInternals.thrownErrors.push(error); + } + if (0 < ReactSharedInternals.thrownErrors.length) + throw ( + (popActScope(prevActQueue, prevActScopeDepth), + (callback = aggregateErrors(ReactSharedInternals.thrownErrors)), + (ReactSharedInternals.thrownErrors.length = 0), + callback) + ); + if ( + null !== result && + "object" === typeof result && + "function" === typeof result.then + ) { + var thenable = result; + queueSeveralMicrotasks(function () { + didAwaitActCall || + didWarnNoAwaitAct || + ((didWarnNoAwaitAct = !0), + console.error( + "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);" + )); + }); + return { + then: function (resolve, reject) { + didAwaitActCall = !0; + thenable.then( + function (returnValue) { + popActScope(prevActQueue, prevActScopeDepth); + if (0 === prevActScopeDepth) { + try { + flushActQueue(queue), + enqueueTask(function () { + return recursivelyFlushAsyncActWork( + returnValue, + resolve, + reject + ); + }); + } catch (error$0) { + ReactSharedInternals.thrownErrors.push(error$0); + } + if (0 < ReactSharedInternals.thrownErrors.length) { + var _thrownError = aggregateErrors( + ReactSharedInternals.thrownErrors + ); + ReactSharedInternals.thrownErrors.length = 0; + reject(_thrownError); + } + } else resolve(returnValue); + }, + function (error) { + popActScope(prevActQueue, prevActScopeDepth); + 0 < ReactSharedInternals.thrownErrors.length + ? ((error = aggregateErrors( + ReactSharedInternals.thrownErrors + )), + (ReactSharedInternals.thrownErrors.length = 0), + reject(error)) + : reject(error); + } + ); + } + }; + } + var returnValue$jscomp$0 = result; + popActScope(prevActQueue, prevActScopeDepth); + 0 === prevActScopeDepth && + (flushActQueue(queue), + 0 !== queue.length && + queueSeveralMicrotasks(function () { + didAwaitActCall || + didWarnNoAwaitAct || + ((didWarnNoAwaitAct = !0), + console.error( + "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)" + )); + }), + (ReactSharedInternals.actQueue = null)); + if (0 < ReactSharedInternals.thrownErrors.length) + throw ( + ((callback = aggregateErrors(ReactSharedInternals.thrownErrors)), + (ReactSharedInternals.thrownErrors.length = 0), + callback) + ); + return { + then: function (resolve, reject) { + didAwaitActCall = !0; + 0 === prevActScopeDepth + ? ((ReactSharedInternals.actQueue = queue), + enqueueTask(function () { + return recursivelyFlushAsyncActWork( + returnValue$jscomp$0, + resolve, + reject + ); + })) + : resolve(returnValue$jscomp$0); + } + }; + }; + exports.addTransitionType = addTransitionType; + exports.cache = function (fn) { + return function () { + return fn.apply(null, arguments); + }; + }; + exports.cacheSignal = function () { + return null; + }; + exports.captureOwnerStack = function () { + var getCurrentStack = ReactSharedInternals.getCurrentStack; + return null === getCurrentStack ? null : getCurrentStack(); + }; + exports.cloneElement = function (element, config, children) { + if (null === element || void 0 === element) + throw Error( + "The argument must be a React element, but you passed " + + element + + "." + ); + var props = assign({}, element.props), + key = element.key, + owner = element._owner; + if (null != config) { + var JSCompiler_inline_result; + a: { + if ( + hasOwnProperty.call(config, "ref") && + (JSCompiler_inline_result = Object.getOwnPropertyDescriptor( + config, + "ref" + ).get) && + JSCompiler_inline_result.isReactWarning + ) { + JSCompiler_inline_result = !1; + break a; + } + JSCompiler_inline_result = void 0 !== config.ref; + } + JSCompiler_inline_result && (owner = getOwner()); + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (key = "" + config.key)); + for (propName in config) + !hasOwnProperty.call(config, propName) || + "key" === propName || + "__self" === propName || + "__source" === propName || + ("ref" === propName && void 0 === config.ref) || + (props[propName] = config[propName]); + } + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + JSCompiler_inline_result = Array(propName); + for (var i = 0; i < propName; i++) + JSCompiler_inline_result[i] = arguments[i + 2]; + props.children = JSCompiler_inline_result; + } + props = ReactElement( + element.type, + key, + props, + owner, + element._debugStack, + element._debugTask + ); + for (key = 2; key < arguments.length; key++) + validateChildKeys(arguments[key]); + return props; + }; + exports.createContext = function (defaultValue) { + defaultValue = { + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null + }; + defaultValue.Provider = defaultValue; + defaultValue.Consumer = { + $$typeof: REACT_CONSUMER_TYPE, + _context: defaultValue + }; + defaultValue._currentRenderer = null; + defaultValue._currentRenderer2 = null; + return defaultValue; + }; + exports.createElement = function (type, config, children) { + for (var i = 2; i < arguments.length; i++) + validateChildKeys(arguments[i]); + var propName; + i = {}; + var key = null; + if (null != config) + for (propName in (didWarnAboutOldJSXRuntime || + !("__self" in config) || + "key" in config || + ((didWarnAboutOldJSXRuntime = !0), + console.warn( + "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform" + )), + hasValidKey(config) && + (checkKeyStringCoercion(config.key), (key = "" + config.key)), + config)) + hasOwnProperty.call(config, propName) && + "key" !== propName && + "__self" !== propName && + "__source" !== propName && + (i[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) i.children = children; + else if (1 < childrenLength) { + for ( + var childArray = Array(childrenLength), _i = 0; + _i < childrenLength; + _i++ + ) + childArray[_i] = arguments[_i + 2]; + Object.freeze && Object.freeze(childArray); + i.children = childArray; + } + if (type && type.defaultProps) + for (propName in ((childrenLength = type.defaultProps), childrenLength)) + void 0 === i[propName] && (i[propName] = childrenLength[propName]); + key && + defineKeyPropWarningGetter( + i, + "function" === typeof type + ? type.displayName || type.name || "Unknown" + : type + ); + (propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++) + ? ((childArray = Error.stackTraceLimit), + (Error.stackTraceLimit = 10), + (childrenLength = Error("react-stack-top-frame")), + (Error.stackTraceLimit = childArray)) + : (childrenLength = unknownOwnerDebugStack); + return ReactElement( + type, + key, + i, + getOwner(), + childrenLength, + propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask + ); + }; + exports.createRef = function () { + var refObject = { current: null }; + Object.seal(refObject); + return refObject; + }; + exports.forwardRef = function (render) { + null != render && render.$$typeof === REACT_MEMO_TYPE + ? console.error( + "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))." + ) + : "function" !== typeof render + ? console.error( + "forwardRef requires a render function but was given %s.", + null === render ? "null" : typeof render + ) + : 0 !== render.length && + 2 !== render.length && + console.error( + "forwardRef render functions accept exactly two parameters: props and ref. %s", + 1 === render.length + ? "Did you forget to use the ref parameter?" + : "Any additional parameter will be undefined." + ); + null != render && + null != render.defaultProps && + console.error( + "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?" + ); + var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render }, + ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: !1, + configurable: !0, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; + render.name || + render.displayName || + (Object.defineProperty(render, "name", { value: name }), + (render.displayName = name)); + } + }); + return elementType; + }; + exports.isValidElement = isValidElement; + exports.lazy = function (ctor) { + ctor = { _status: -1, _result: ctor }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: ctor, + _init: lazyInitializer + }, + ioInfo = { + name: "lazy", + start: -1, + end: -1, + value: null, + owner: null, + debugStack: Error("react-stack-top-frame"), + debugTask: console.createTask ? console.createTask("lazy()") : null + }; + ctor._ioInfo = ioInfo; + lazyType._debugInfo = [{ awaited: ioInfo }]; + return lazyType; + }; + exports.memo = function (type, compare) { + null == type && + console.error( + "memo: The first argument must be a component. Instead received: %s", + null === type ? "null" : typeof type + ); + compare = { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: void 0 === compare ? null : compare + }; + var ownName; + Object.defineProperty(compare, "displayName", { + enumerable: !1, + configurable: !0, + get: function () { + return ownName; + }, + set: function (name) { + ownName = name; + type.name || + type.displayName || + (Object.defineProperty(type, "name", { value: name }), + (type.displayName = name)); + } + }); + return compare; + }; + exports.startTransition = startTransition; + exports.unstable_useCacheRefresh = function () { + return resolveDispatcher().useCacheRefresh(); + }; + exports.use = function (usable) { + return resolveDispatcher().use(usable); + }; + exports.useActionState = function (action, initialState, permalink) { + return resolveDispatcher().useActionState( + action, + initialState, + permalink + ); + }; + exports.useCallback = function (callback, deps) { + return resolveDispatcher().useCallback(callback, deps); + }; + exports.useContext = function (Context) { + var dispatcher = resolveDispatcher(); + Context.$$typeof === REACT_CONSUMER_TYPE && + console.error( + "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?" + ); + return dispatcher.useContext(Context); + }; + exports.useDebugValue = function (value, formatterFn) { + return resolveDispatcher().useDebugValue(value, formatterFn); + }; + exports.useDeferredValue = function (value, initialValue) { + return resolveDispatcher().useDeferredValue(value, initialValue); + }; + exports.useEffect = function (create, deps) { + null == create && + console.warn( + "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useEffect(create, deps); + }; + exports.useEffectEvent = function (callback) { + return resolveDispatcher().useEffectEvent(callback); + }; + exports.useId = function () { + return resolveDispatcher().useId(); + }; + exports.useImperativeHandle = function (ref, create, deps) { + return resolveDispatcher().useImperativeHandle(ref, create, deps); + }; + exports.useInsertionEffect = function (create, deps) { + null == create && + console.warn( + "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useInsertionEffect(create, deps); + }; + exports.useLayoutEffect = function (create, deps) { + null == create && + console.warn( + "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?" + ); + return resolveDispatcher().useLayoutEffect(create, deps); + }; + exports.useMemo = function (create, deps) { + return resolveDispatcher().useMemo(create, deps); + }; + exports.useOptimistic = function (passthrough, reducer) { + return resolveDispatcher().useOptimistic(passthrough, reducer); + }; + exports.useReducer = function (reducer, initialArg, init) { + return resolveDispatcher().useReducer(reducer, initialArg, init); + }; + exports.useRef = function (initialValue) { + return resolveDispatcher().useRef(initialValue); + }; + exports.useState = function (initialState) { + return resolveDispatcher().useState(initialState); + }; + exports.useSyncExternalStore = function ( + subscribe, + getSnapshot, + getServerSnapshot + ) { + return resolveDispatcher().useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ); + }; + exports.useTransition = function () { + return resolveDispatcher().useTransition(); + }; + exports.version = "19.3.0"; + "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && + "function" === + typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); + })(); + + +}, +"./node_modules/react/cjs/react.production.js"(__unused_rspack_module, exports) { +/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + +var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), + REACT_PORTAL_TYPE = Symbol.for("react.portal"), + REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), + REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), + REACT_PROFILER_TYPE = Symbol.for("react.profiler"), + REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), + REACT_CONTEXT_TYPE = Symbol.for("react.context"), + REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), + REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), + REACT_MEMO_TYPE = Symbol.for("react.memo"), + REACT_LAZY_TYPE = Symbol.for("react.lazy"), + REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), + REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"), + MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +function getIteratorFn(maybeIterable) { + if (null === maybeIterable || "object" !== typeof maybeIterable) return null; + maybeIterable = + (MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) || + maybeIterable["@@iterator"]; + return "function" === typeof maybeIterable ? maybeIterable : null; +} +var ReactNoopUpdateQueue = { + isMounted: function () { + return !1; + }, + enqueueForceUpdate: function () {}, + enqueueReplaceState: function () {}, + enqueueSetState: function () {} + }, + assign = Object.assign, + emptyObject = {}; +function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; +} +Component.prototype.isReactComponent = {}; +Component.prototype.setState = function (partialState, callback) { + if ( + "object" !== typeof partialState && + "function" !== typeof partialState && + null != partialState + ) + throw Error( + "takes an object of state variables to update or a function which returns an object of state variables." + ); + this.updater.enqueueSetState(this, partialState, callback, "setState"); +}; +Component.prototype.forceUpdate = function (callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); +}; +function ComponentDummy() {} +ComponentDummy.prototype = Component.prototype; +function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; +} +var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy()); +pureComponentPrototype.constructor = PureComponent; +assign(pureComponentPrototype, Component.prototype); +pureComponentPrototype.isPureReactComponent = !0; +var isArrayImpl = Array.isArray; +function noop() {} +var ReactSharedInternals = { H: null, A: null, T: null, S: null }, + hasOwnProperty = Object.prototype.hasOwnProperty; +function ReactElement(type, key, props) { + var refProp = props.ref; + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key, + ref: void 0 !== refProp ? refProp : null, + props: props + }; +} +function cloneAndReplaceKey(oldElement, newKey) { + return ReactElement(oldElement.type, newKey, oldElement.props); +} +function isValidElement(object) { + return ( + "object" === typeof object && + null !== object && + object.$$typeof === REACT_ELEMENT_TYPE + ); +} +function escape(key) { + var escaperLookup = { "=": "=0", ":": "=2" }; + return ( + "$" + + key.replace(/[=:]/g, function (match) { + return escaperLookup[match]; + }) + ); +} +var userProvidedKeyEscapeRegex = /\/+/g; +function getElementKey(element, index) { + return "object" === typeof element && null !== element && null != element.key + ? escape("" + element.key) + : index.toString(36); +} +function resolveThenable(thenable) { + switch (thenable.status) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + default: + switch ( + ("string" === typeof thenable.status + ? thenable.then(noop, noop) + : ((thenable.status = "pending"), + thenable.then( + function (fulfilledValue) { + "pending" === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = fulfilledValue)); + }, + function (error) { + "pending" === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + )), + thenable.status) + ) { + case "fulfilled": + return thenable.value; + case "rejected": + throw thenable.reason; + } + } + throw thenable; +} +function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if ("undefined" === type || "boolean" === type) children = null; + var invokeCallback = !1; + if (null === children) invokeCallback = !0; + else + switch (type) { + case "bigint": + case "string": + case "number": + invokeCallback = !0; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = !0; + break; + case REACT_LAZY_TYPE: + return ( + (invokeCallback = children._init), + mapIntoArray( + invokeCallback(children._payload), + array, + escapedPrefix, + nameSoFar, + callback + ) + ); + } + } + if (invokeCallback) + return ( + (callback = callback(children)), + (invokeCallback = + "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar), + isArrayImpl(callback) + ? ((escapedPrefix = ""), + null != invokeCallback && + (escapedPrefix = + invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), + mapIntoArray(callback, array, escapedPrefix, "", function (c) { + return c; + })) + : null != callback && + (isValidElement(callback) && + (callback = cloneAndReplaceKey( + callback, + escapedPrefix + + (null == callback.key || + (children && children.key === callback.key) + ? "" + : ("" + callback.key).replace( + userProvidedKeyEscapeRegex, + "$&/" + ) + "/") + + invokeCallback + )), + array.push(callback)), + 1 + ); + invokeCallback = 0; + var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":"; + if (isArrayImpl(children)) + for (var i = 0; i < children.length; i++) + (nameSoFar = children[i]), + (type = nextNamePrefix + getElementKey(nameSoFar, i)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if (((i = getIteratorFn(children)), "function" === typeof i)) + for ( + children = i.call(children), i = 0; + !(nameSoFar = children.next()).done; + + ) + (nameSoFar = nameSoFar.value), + (type = nextNamePrefix + getElementKey(nameSoFar, i++)), + (invokeCallback += mapIntoArray( + nameSoFar, + array, + escapedPrefix, + type, + callback + )); + else if ("object" === type) { + if ("function" === typeof children.then) + return mapIntoArray( + resolveThenable(children), + array, + escapedPrefix, + nameSoFar, + callback + ); + array = String(children); + throw Error( + "Objects are not valid as a React child (found: " + + ("[object Object]" === array + ? "object with keys {" + Object.keys(children).join(", ") + "}" + : array) + + "). If you meant to render a collection of children, use an array instead." + ); + } + return invokeCallback; +} +function mapChildren(children, func, context) { + if (null == children) return children; + var result = [], + count = 0; + mapIntoArray(children, result, "", "", function (child) { + return func.call(context, child, count++); + }); + return result; +} +function lazyInitializer(payload) { + if (-1 === payload._status) { + var ctor = payload._result, + thenable = ctor(); + thenable.then( + function (moduleObject) { + if (0 === payload._status || -1 === payload._status) + (payload._status = 1), + (payload._result = moduleObject), + void 0 === thenable.status && + ((thenable.status = "fulfilled"), + (thenable.value = moduleObject)); + }, + function (error) { + if (0 === payload._status || -1 === payload._status) + (payload._status = 2), + (payload._result = error), + void 0 === thenable.status && + ((thenable.status = "rejected"), (thenable.reason = error)); + } + ); + -1 === payload._status && + ((payload._status = 0), (payload._result = thenable)); + } + if (1 === payload._status) return payload._result.default; + throw payload._result; +} +var reportGlobalError = + "function" === typeof reportError + ? reportError + : function (error) { + if ( + "object" === typeof window && + "function" === typeof window.ErrorEvent + ) { + var event = new window.ErrorEvent("error", { + bubbles: !0, + cancelable: !0, + message: + "object" === typeof error && + null !== error && + "string" === typeof error.message + ? String(error.message) + : String(error), + error: error + }); + if (!window.dispatchEvent(event)) return; + } else if ( + "object" === typeof process && + "function" === typeof process.emit + ) { + process.emit("uncaughtException", error); + return; + } + console.error(error); + }; +function startTransition(scope) { + var prevTransition = ReactSharedInternals.T, + currentTransition = {}; + currentTransition.types = + null !== prevTransition ? prevTransition.types : null; + ReactSharedInternals.T = currentTransition; + try { + var returnValue = scope(), + onStartTransitionFinish = ReactSharedInternals.S; + null !== onStartTransitionFinish && + onStartTransitionFinish(currentTransition, returnValue); + "object" === typeof returnValue && + null !== returnValue && + "function" === typeof returnValue.then && + returnValue.then(noop, reportGlobalError); + } catch (error) { + reportGlobalError(error); + } finally { + null !== prevTransition && + null !== currentTransition.types && + (prevTransition.types = currentTransition.types), + (ReactSharedInternals.T = prevTransition); + } +} +function addTransitionType(type) { + var transition = ReactSharedInternals.T; + if (null !== transition) { + var transitionTypes = transition.types; + null === transitionTypes + ? (transition.types = [type]) + : -1 === transitionTypes.indexOf(type) && transitionTypes.push(type); + } else startTransition(addTransitionType.bind(null, type)); +} +var Children = { + map: mapChildren, + forEach: function (children, forEachFunc, forEachContext) { + mapChildren( + children, + function () { + forEachFunc.apply(this, arguments); + }, + forEachContext + ); + }, + count: function (children) { + var n = 0; + mapChildren(children, function () { + n++; + }); + return n; + }, + toArray: function (children) { + return ( + mapChildren(children, function (child) { + return child; + }) || [] + ); + }, + only: function (children) { + if (!isValidElement(children)) + throw Error( + "React.Children.only expected to receive a single React element child." + ); + return children; + } +}; +exports.Activity = REACT_ACTIVITY_TYPE; +exports.Children = Children; +exports.Component = Component; +exports.Fragment = REACT_FRAGMENT_TYPE; +exports.Profiler = REACT_PROFILER_TYPE; +exports.PureComponent = PureComponent; +exports.StrictMode = REACT_STRICT_MODE_TYPE; +exports.Suspense = REACT_SUSPENSE_TYPE; +exports.ViewTransition = REACT_VIEW_TRANSITION_TYPE; +exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = + ReactSharedInternals; +exports.__COMPILER_RUNTIME = { + __proto__: null, + c: function (size) { + return ReactSharedInternals.H.useMemoCache(size); + } +}; +exports.addTransitionType = addTransitionType; +exports.cache = function (fn) { + return function () { + return fn.apply(null, arguments); + }; +}; +exports.cacheSignal = function () { + return null; +}; +exports.cloneElement = function (element, config, children) { + if (null === element || void 0 === element) + throw Error( + "The argument must be a React element, but you passed " + element + "." + ); + var props = assign({}, element.props), + key = element.key; + if (null != config) + for (propName in (void 0 !== config.key && (key = "" + config.key), config)) + !hasOwnProperty.call(config, propName) || + "key" === propName || + "__self" === propName || + "__source" === propName || + ("ref" === propName && void 0 === config.ref) || + (props[propName] = config[propName]); + var propName = arguments.length - 2; + if (1 === propName) props.children = children; + else if (1 < propName) { + for (var childArray = Array(propName), i = 0; i < propName; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + return ReactElement(element.type, key, props); +}; +exports.createContext = function (defaultValue) { + defaultValue = { + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null + }; + defaultValue.Provider = defaultValue; + defaultValue.Consumer = { + $$typeof: REACT_CONSUMER_TYPE, + _context: defaultValue + }; + return defaultValue; +}; +exports.createElement = function (type, config, children) { + var propName, + props = {}, + key = null; + if (null != config) + for (propName in (void 0 !== config.key && (key = "" + config.key), config)) + hasOwnProperty.call(config, propName) && + "key" !== propName && + "__self" !== propName && + "__source" !== propName && + (props[propName] = config[propName]); + var childrenLength = arguments.length - 2; + if (1 === childrenLength) props.children = children; + else if (1 < childrenLength) { + for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++) + childArray[i] = arguments[i + 2]; + props.children = childArray; + } + if (type && type.defaultProps) + for (propName in ((childrenLength = type.defaultProps), childrenLength)) + void 0 === props[propName] && + (props[propName] = childrenLength[propName]); + return ReactElement(type, key, props); +}; +exports.createRef = function () { + return { current: null }; +}; +exports.forwardRef = function (render) { + return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; +}; +exports.isValidElement = isValidElement; +exports.lazy = function (ctor) { + return { + $$typeof: REACT_LAZY_TYPE, + _payload: { _status: -1, _result: ctor }, + _init: lazyInitializer + }; +}; +exports.memo = function (type, compare) { + return { + $$typeof: REACT_MEMO_TYPE, + type: type, + compare: void 0 === compare ? null : compare + }; +}; +exports.startTransition = startTransition; +exports.unstable_useCacheRefresh = function () { + return ReactSharedInternals.H.useCacheRefresh(); +}; +exports.use = function (usable) { + return ReactSharedInternals.H.use(usable); +}; +exports.useActionState = function (action, initialState, permalink) { + return ReactSharedInternals.H.useActionState(action, initialState, permalink); +}; +exports.useCallback = function (callback, deps) { + return ReactSharedInternals.H.useCallback(callback, deps); +}; +exports.useContext = function (Context) { + return ReactSharedInternals.H.useContext(Context); +}; +exports.useDebugValue = function () {}; +exports.useDeferredValue = function (value, initialValue) { + return ReactSharedInternals.H.useDeferredValue(value, initialValue); +}; +exports.useEffect = function (create, deps) { + return ReactSharedInternals.H.useEffect(create, deps); +}; +exports.useEffectEvent = function (callback) { + return ReactSharedInternals.H.useEffectEvent(callback); +}; +exports.useId = function () { + return ReactSharedInternals.H.useId(); +}; +exports.useImperativeHandle = function (ref, create, deps) { + return ReactSharedInternals.H.useImperativeHandle(ref, create, deps); +}; +exports.useInsertionEffect = function (create, deps) { + return ReactSharedInternals.H.useInsertionEffect(create, deps); +}; +exports.useLayoutEffect = function (create, deps) { + return ReactSharedInternals.H.useLayoutEffect(create, deps); +}; +exports.useMemo = function (create, deps) { + return ReactSharedInternals.H.useMemo(create, deps); +}; +exports.useOptimistic = function (passthrough, reducer) { + return ReactSharedInternals.H.useOptimistic(passthrough, reducer); +}; +exports.useReducer = function (reducer, initialArg, init) { + return ReactSharedInternals.H.useReducer(reducer, initialArg, init); +}; +exports.useRef = function (initialValue) { + return ReactSharedInternals.H.useRef(initialValue); +}; +exports.useState = function (initialState) { + return ReactSharedInternals.H.useState(initialState); +}; +exports.useSyncExternalStore = function ( + subscribe, + getSnapshot, + getServerSnapshot +) { + return ReactSharedInternals.H.useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ); +}; +exports.useTransition = function () { + return ReactSharedInternals.H.useTransition(); +}; +exports.version = "19.3.0"; + + +}, +"./node_modules/react/index.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react/cjs/react.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react/cjs/react.development.js"); +} + + +}, +"./node_modules/react/jsx-runtime.js"(module, __unused_rspack_exports, __webpack_require__) { + + +if (process.env.NODE_ENV === 'production') { + module.exports = __webpack_require__("./node_modules/react/cjs/react-jsx-runtime.production.js"); +} else { + module.exports = __webpack_require__("./node_modules/react/cjs/react-jsx-runtime.development.js"); +} + + +}, +"./src/cli/_shared.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_commands_js__rspack_import_0 = __webpack_require__("./src/core/commands.js"); +/* import */ var _core_store_js__rspack_import_1 = __webpack_require__("./src/core/store.js"); +/* import */ var _gbot_js__rspack_import_2 = __webpack_require__("./src/gbot.ts"); + + + + +/** Shared backend selection flags (were leading globals on the hand CLI). */ const backendFlagsSchema = zod__rspack_import_3/* .object */.Ikc({ + dir: zod__rspack_import_3/* .string */.YjP().min(1).optional().describe('Agents directory for --files mode'), + files: zod__rspack_import_3/* .boolean */.zMY().optional().describe('Force the on-disk agents store'), + gateway: zod__rspack_import_3/* .boolean */.zMY().optional().describe('Force the live gateway') +}).strict(); +/** The flat failure document `outcomeFromError` builds for `exitCode: 'result'` routes. */ const failureDocumentSchema = zod__rspack_import_3/* .object */.Ikc({ + delivery: zod__rspack_import_3/* ["enum"] */.k5n([ + 'accepted', + 'queued', + 'rejected', + 'unknown' + ]), + error: zod__rspack_import_3/* .string */.YjP(), + exitCode: zod__rspack_import_3/* .literal */.euz(1) +}).catchall(zod__rspack_import_3/* .json */.Pq9()); +// The framework prints thrown route errors verbatim; a fetch or proxy failure can echo a credential. +const redactBackendErrors = (backend)=>new Proxy(backend, { + get (target, property, receiver) { + const value = Reflect.get(target, property, receiver); + return typeof value === 'function' ? (...args)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(()=>value.apply(target, args)) : value; + } + }); +const openBackendFromInput = async (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>redactBackendErrors(await (0,_core_commands_js__rspack_import_0/* .openBackend */.f)({ + files: Boolean(input.files), + gateway: Boolean(input.gateway), + root: input.dir + }))); +const avatarShapeSchema = zod__rspack_import_3/* ["enum"] */.k5n(_core_store_js__rspack_import_1/* .AVATAR_SHAPES */.Jb); +const avatarColorSchema = zod__rspack_import_3/* ["enum"] */.k5n(_core_store_js__rspack_import_1/* .AVATAR_COLORS */.T7); +const onOffSchema = zod__rspack_import_3/* ["enum"] */.k5n([ + 'on', + 'off' +]); +const parseOnOff = (value)=>value === 'on'; +const agentSummarySchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: zod__rspack_import_3/* .string */.YjP().optional(), + avatarShape: zod__rspack_import_3/* .string */.YjP().optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + hiddenFromSidebar: zod__rspack_import_3/* .boolean */.zMY().optional(), + id: zod__rspack_import_3/* .string */.YjP(), + kind: zod__rspack_import_3/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + members: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP()).optional(), + name: zod__rspack_import_3/* .string */.YjP(), + notifyOnAgentUpdates: zod__rspack_import_3/* .boolean */.zMY().optional(), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const skillSchema = zod__rspack_import_3/* .object */.Ikc({ + description: zod__rspack_import_3/* .string */.YjP(), + id: zod__rspack_import_3/* .string */.YjP(), + name: zod__rspack_import_3/* .string */.YjP(), + pluginId: zod__rspack_import_3/* .string */.YjP().optional(), + source: zod__rspack_import_3/* .string */.YjP(), + sourceRef: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const createFieldsSchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: avatarColorSchema.optional(), + avatarShape: avatarShapeSchema.optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + name: zod__rspack_import_3/* .string */.YjP().min(1), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const updateFieldsSchema = zod__rspack_import_3/* .object */.Ikc({ + avatarColor: avatarColorSchema.optional(), + avatarShape: avatarShapeSchema.optional(), + description: zod__rspack_import_3/* .string */.YjP().optional(), + hidden: onOffSchema.optional(), + name: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + notify: onOffSchema.optional(), + title: zod__rspack_import_3/* .string */.YjP().optional() +}).strict(); +const toCreateInput = (fields)=>({ + avatarColor: fields.avatarColor ?? '', + avatarShape: fields.avatarShape ?? '', + description: fields.description ?? '', + name: fields.name, + title: fields.title ?? '' + }); +const toUpdatePatch = (fields)=>{ + const patch = {}; + if (fields.name !== undefined) patch.name = fields.name; + if (fields.description !== undefined) patch.description = fields.description; + if (fields.title !== undefined) patch.title = fields.title; + if (fields.avatarShape !== undefined) patch.avatarShape = fields.avatarShape; + if (fields.avatarColor !== undefined) patch.avatarColor = fields.avatarColor; + if (fields.notify !== undefined) patch.notifyOnAgentUpdates = parseOnOff(fields.notify); + if (fields.hidden !== undefined) patch.hiddenFromSidebar = parseOnOff(fields.hidden); + if (Object.keys(patch).length === 0) { + throw new Error('update needs at least one of --name --description --title --avatar-shape --avatar-color --notify --hidden'); + } + return patch; +}; + +__webpack_require__.d(__webpack_exports__, { +}, { + FS: openBackendFromInput, + R9: failureDocumentSchema, + b7: skillSchema, + bY: createFieldsSchema, + cp: toCreateInput, + lK: backendFlagsSchema, + li: toUpdatePatch, + qP: updateFieldsSchema, + t_: agentSummarySchema +}); + + +}, +"./src/cli/approvals/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_grok_approval_routes_js__rspack_import_1 = __webpack_require__("./src/core/grok-approval-routes.ts"); + + + + +const config = { + description: 'List current Grok approval cards (latest 200 entries).', + positionals: [ + 'target' + ], + inputJsonSchema: { + type: 'object', + properties: { + target: { + type: 'string' + } + }, + required: [ + 'target' + ], + additionalProperties: false + } +}; +async function route({ input }) { + const out = await (0,_core_grok_approval_routes_js__rspack_import_1/* .listOperation */.gi)(input); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.cE), + resultSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/approvals/respond.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_grok_approval_routes_js__rspack_import_1 = __webpack_require__("./src/core/grok-approval-routes.ts"); + + + + +const config = { + description: 'Explicit user decision: accept a Grok request once or decline; never grant persistent permissions.', + inputJsonSchema: { + type: 'object', + properties: { + target: { + type: 'string' + }, + entryId: { + type: 'string' + }, + requestId: { + type: 'string' + }, + decision: { + type: 'string', + enum: [ + 'accept', + 'decline' + ] + } + }, + required: [ + 'target', + 'entryId', + 'requestId', + 'decision' + ], + additionalProperties: false + } +}; +async function route({ input }) { + const out = await (0,_core_grok_approval_routes_js__rspack_import_1/* .respondOperation */.lr)(input); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.v1), + resultSchema: () => (/* reexport safe */ _core_grok_approval_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/bots/create.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'Create a Grok Bot bot.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + name: { + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'name' + ], + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .createFieldsSchema */.bY).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsCreate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, ...fields } = input; + const rec = await backend.createAgent((0,_shared_js__rspack_import_1/* .toCreateInput */.cp)(fields)); + if (rec == null) throw new Error('createAgent returned no record'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_3/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_2/* .Agent.Text */.g6.Text, { + children: `Created bot ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsCreate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/delete.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Delete a bot or group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsDelete({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.deleteAgent(input.ref); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Deleted ${rec.isGroup ? 'group' : 'bot'} ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsDelete) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/get.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show one bot or group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsGet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsGet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'List Grok Bot bots (not groups).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .agentSummarySchema */.t_); +async function botsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const all = await backend.list(); + const rows = all.filter((r)=>!r.isGroup); + const bots = rows.map(_core_format_js__rspack_import_3/* .summarize */.eh); + const text = rows.length === 0 ? 'No bots.' : rows.map((r)=>(0,_core_format_js__rspack_import_3/* .formatRecord */.bM)(r, all)).join('\n\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: bots, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/bots/update.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Update a bot or group profile.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + hidden: { + type: 'string' + }, + name: { + type: 'string' + }, + notify: { + type: 'string' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .updateFieldsSchema */.qP).extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function botsUpdate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, ref, ...fields } = input; + const rec = await backend.updateAgent(ref, (0,_shared_js__rspack_import_1/* .toUpdatePatch */.li)(fields)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated ${rec.isGroup ? 'group' : 'bot'} ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (botsUpdate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/bridge/respond.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge respond.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + interactionId: { + type: 'string' + }, + generation: { + type: 'string' + }, + threadId: { + type: 'string' + }, + turnId: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + exchangeId: { + type: 'string' + }, + decision: { + type: 'string', + enum: [ + 'accept', + 'decline', + 'cancel' + ] + }, + answersJson: { + type: 'string', + description: 'JSON object mapping each advertised question ID to {"answers":["answer"]}; exact IDs required.' + } + }, + required: [ + 'interactionId', + 'generation', + 'threadId', + 'turnId' + ], + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('respond', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.v1), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/run.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var node_child_process__rspack_import_1 = __webpack_require__("node:child_process"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_relay_managed_js__rspack_import_2 = __webpack_require__("./src/core/relay/managed.js"); + + + + + +const inputSchema = zod__rspack_import_3/* .object */.Ikc({ + lifetimeMs: zod__rspack_import_3/* .number */.aig().int().min(100).max(82800000).default(82800000) +}).strict(); +const resultSchema = zod__rspack_import_3/* .object */.Ikc({ + state: zod__rspack_import_3/* .string */.YjP(), + exitCode: zod__rspack_import_3/* .number */.aig() +}); +const config = { + description: 'Run a bounded foreground relay (up to 23 hours). Use the packaged gbot-relay.mjs script for unlimited service lifetime.', + exitCode: 'result', + render: { + maxElapsedMs: 86400000 + }, + inputJsonSchema: { + type: 'object', + properties: { + lifetimeMs: { + type: 'number', + description: 'Foreground lifetime in milliseconds (100..82800000; default 23h).' + } + }, + additionalProperties: false + } +}; +async function route({ signal, input }) { + const context = await (0,_agent_bundle_runtime__rspack_import_4/* .agent */.MA)(); + const script = await (0,_core_relay_managed_js__rspack_import_2/* .resolveRelayWorker */._v)({ + pluginRoot: context.plugin.state === 'available' ? context.plugin.value.root : undefined + }); + // The renderer may terminate immediately on abort. The separate worker can finish + // asynchronous socket/ledger cleanup after the synchronous termination signal. + const child = (0,node_child_process__rspack_import_1.spawn)(process.execPath, [ + script, + '--lifetime-ms', + String(input.lifetimeMs), + '--parent-pid', + String(process.pid) + ], { + stdio: [ + 'ignore', + 'ignore', + 'inherit' + ] + }); + const stop = ()=>{ + child.kill('SIGTERM'); + }; + signal.addEventListener('abort', stop, { + once: true + }); + if (signal.aborted) stop(); + let exitCode; + try { + exitCode = await new Promise((resolve, reject)=>{ + child.once('error', reject); + child.once('exit', (code)=>resolve(code ?? 1)); + }); + } finally{ + signal.removeEventListener('abort', stop); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + state: 'stopped', + exitCode + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: "Relay worker stopped." + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/bridge/start.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge start.', + exitCode: 'result', + positionals: [ + 'grokTarget' + ], + inputJsonSchema: { + type: 'object', + properties: { + grokTarget: { + type: 'string' + }, + codexThreadId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + busyPolicy: { + type: 'string', + enum: [ + 'steer', + 'reject' + ] + }, + requestId: { + type: 'string' + } + }, + required: [ + 'grokTarget' + ], + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('startBinding', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.xD), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/status.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge status.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + bindingId: { + type: 'string' + }, + limit: { + type: 'number' + } + }, + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('status', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.np), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/bridge/stop.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); + + + + + +const config = { + description: 'Managed Grok/Codex bridge stop.', + exitCode: 'result', + inputJsonSchema: { + type: 'object', + properties: { + bindingId: { + type: 'string' + }, + all: { + type: 'boolean' + }, + worker: { + type: 'boolean' + } + }, + additionalProperties: false + } +}; +async function route({ input }) { + let out; + try { + out = { + ...await (0,_core_relay_routes_js__rspack_import_1/* .bridgeOperation */.n1)('stop', input, await (0,_agent_bundle_runtime__rspack_import_3/* .agent */.MA)()), + exitCode: 0 + }; + } catch (error) { + out = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: JSON.stringify(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.d5), + resultSchema: () => (/* reexport safe */ _core_relay_routes_js__rspack_import_1.Ax) +}, { + config: config +}); + + +}, +"./src/cli/codex/desktop-shim.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_desktop_shim_js__rspack_import_1 = __webpack_require__("./src/core/desktop-shim.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); + + + + + +const config = { + description: 'Install, remove, or check the ChatGPT Desktop shim: a CODEX_CLI_PATH wrapper that bridges Desktop stdio onto the managed Codex daemon (stock app-server proxy hangs). macOS persists via LaunchAgent; always fails open to real Codex.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + action: { + description: 'install | uninstall | status', + enum: [ + 'install', + 'uninstall', + 'status' + ], + type: 'string' + } + }, + required: [ + 'action' + ], + type: 'object' + }, + positionals: [ + 'action' + ] +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({ + action: zod__rspack_import_2/* ["enum"] */.k5n([ + 'install', + 'uninstall', + 'status' + ]) +}).strict(); +const resultSchema = zod__rspack_import_2/* .object */.Ikc({ + exitCode: zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .literal */.euz(0), + zod__rspack_import_2/* .literal */.euz(1) + ]) +}).passthrough(); +const formatWarnings = (warnings)=>warnings.length === 0 ? '' : `\nwarnings:\n${warnings.map((w)=>` - ${String(w)}`).join('\n')}`; +async function codexDesktopShim({ input }) { + switch(input.action){ + case 'install': + { + let out; + try { + out = (0,_core_desktop_shim_js__rspack_import_1/* .installDesktopShim */.B0)(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + action: 'install', + error: message, + exitCode: 1 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Desktop shim install failed: ${message}` + }) + }); + } + const text = `Installed ChatGPT Desktop shim:\n` + ` wrapper: ${out.wrapperPath}\n` + ` bridge: ${out.bridgePath}\n` + ` login env: ${out.envScriptPath}` + (out.plistPath ? `\n LaunchAgent: ${out.plistPath}` : '\n LaunchAgent: n/a (macOS-only)') + `\nFully quit and relaunch ChatGPT.app so it inherits CODEX_CLI_PATH; ` + `Desktop falls back to stock Codex if the shim is ever removed.` + formatWarnings(out.warnings); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); + } + case 'uninstall': + { + let out; + try { + out = (0,_core_desktop_shim_js__rspack_import_1/* .uninstallDesktopShim */.gM)(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + action: 'uninstall', + error: message, + exitCode: 1 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Desktop shim uninstall failed: ${message}` + }) + }); + } + const removed = out.removed.length === 0 ? '(nothing installed)' : out.removed.join(', '); + const text = `Removed ChatGPT Desktop shim: ${removed}. ` + `Desktop and Codex fall back to stock behavior; relaunch ChatGPT.app to pick it up.` + formatWarnings(out.warnings); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); + } + case 'status': + { + const out = (0,_core_desktop_shim_js__rspack_import_1/* .desktopShimStatus */.em)(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatDesktopShimStatus */.fX)(out) + }) + }); + } + default: + { + const _exhaustive = input.action; + throw new Error(`unknown desktop-shim action: ${String(_exhaustive)}`); + } + } +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexDesktopShim) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/list-threads.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_format_js__rspack_import_6 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'List Codex daemon-managed threads.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + cursor: { + description: 'Opaque pagination cursor (may start with -)', + type: 'string' + }, + limit: { + default: 20, + description: 'Max threads to list (1-200)', + type: 'number' + } + }, + type: 'object' + } +}; +const inputSchema = zod__rspack_import_4/* .object */.Ikc({ + cursor: zod__rspack_import_4/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_4/* .number */.aig().int().min(1).max(200).default(20) +}).strict(); +const resultSchema = zod__rspack_import_4/* .union */.KCZ([ + zod__rspack_import_4/* .object */.Ikc({ + exitCode: zod__rspack_import_4/* .literal */.euz(0), + limit: zod__rspack_import_4/* .number */.aig().int().min(1).max(200), + nextCursor: zod__rspack_import_4/* .string */.YjP().nullable(), + threads: zod__rspack_import_4/* .array */.YOg(zod__rspack_import_4/* .record */.g1P(zod__rspack_import_4/* .string */.YjP(), zod__rspack_import_4/* .json */.Pq9())) + }).strict(), + _shared_js__rspack_import_3/* .failureDocumentSchema */.R9 +]); +async function codexListThreads({ input }) { + let out; + try { + out = await (0,_core_codex_bridge_js__rspack_import_1/* .listCodexThreads */.X$)({ + cursor: input.cursor, + limit: input.limit + }); + } catch (error) { + const failure = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: failure, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: failure.error + }) + }); + } + const more = out.nextCursor ? `\n\nmore: --cursor ${JSON.stringify((0,_core_codex_bridge_js__rspack_import_1/* .singleLine */.pF)(out.nextCursor))}` : ''; + const text = out.threads.length === 0 ? 'No Codex threads.' : out.threads.map(_core_format_js__rspack_import_6/* .formatCodexThread */.nz).join('\n\n') + more; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexListThreads) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/queue.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_2 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_format_js__rspack_import_6 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'List the experimental Codex thread queue (GROK_BOT_CODEX_EXPERIMENTAL=1).', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + threadId: { + type: 'string' + } + }, + required: [ + 'threadId' + ], + type: 'object' + }, + positionals: [ + 'threadId' + ] +}; +const inputSchema = zod__rspack_import_4/* .object */.Ikc({ + threadId: zod__rspack_import_4/* .string */.YjP().min(1) +}).strict(); +const resultSchema = zod__rspack_import_4/* .union */.KCZ([ + zod__rspack_import_4/* .object */.Ikc({ + exitCode: zod__rspack_import_4/* .literal */.euz(0), + nextCursor: zod__rspack_import_4/* .string */.YjP().nullable(), + queued: zod__rspack_import_4/* .array */.YOg(zod__rspack_import_4/* .object */.Ikc({ + clientUserMessageId: zod__rspack_import_4/* .string */.YjP().nullable(), + id: zod__rspack_import_4/* .string */.YjP().nullable(), + text: zod__rspack_import_4/* .string */.YjP() + }).strict()), + threadId: zod__rspack_import_4/* .string */.YjP() + }).strict(), + _shared_js__rspack_import_3/* .failureDocumentSchema */.R9 +]); +async function codexQueue({ input }) { + let out; + try { + out = await (0,_core_codex_bridge_js__rspack_import_1/* .listCodexQueue */.Bt)(input.threadId); + } catch (error) { + const failure = (0,_core_codex_contract_js__rspack_import_2/* .outcomeFromError */.DG)(error); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: failure, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: failure.error + }) + }); + } + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_6/* .formatCodexQueue */.e_)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexQueue) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/send.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); +/* import */ var _core_relay_routes_js__rspack_import_2 = __webpack_require__("./src/core/relay/routes.ts"); + + + + + +const resultSchema = zod__rspack_import_3/* .union */.KCZ([ + _core_codex_routes_js__rspack_import_1/* .resultSchema */.FD, + _core_relay_routes_js__rspack_import_2/* .relayResultSchema */.Ax +]); +const inputSchema = zod__rspack_import_3/* .object */.Ikc({ + ..._core_codex_routes_js__rspack_import_1/* .sendFields */.at, + whenBusy: zod__rspack_import_3/* ["enum"] */.k5n([ + 'reject', + 'queue', + 'steer' + ]).optional(), + replyToGrok: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + requestId: zod__rspack_import_3/* .string */.YjP().min(1).max(128).optional(), + correlationId: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + replyTo: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + message: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP()).min(1) +}).strict(); +const config = { + description: 'Send to Codex; acceptance is distinct from completion. Options precede threadId.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId', + 'message' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + replyToGrok: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + requestId: { + type: 'string' + }, + threadId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + timeoutMs: { + type: 'number', + description: 'Observation timeout: 1-600000 milliseconds.' + }, + correlationId: { + type: 'string' + }, + envelope: { + type: 'boolean' + }, + hop: { + type: 'number' + }, + replyTo: { + type: 'string' + }, + expectedTurnId: { + type: 'string', + description: 'Required active-turn guard for steer; stale guards reject.' + }, + wait: { + type: 'boolean' + }, + maxOutputBytes: { + type: 'number', + description: 'Reply budget: 1-4194304 bytes.' + }, + whenBusy: { + type: 'string', + enum: [ + 'reject', + 'queue', + 'steer' + ] + }, + message: { + type: 'array', + items: { + type: 'string' + } + } + }, + required: [ + 'threadId', + 'message' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_4/* .agent */.MA)(); + if (input.replyToGrok || input.bindingId) { + const out = await (0,_core_relay_routes_js__rspack_import_2/* .codexReturnOperation */.lt)({ + ...input, + message: input.message.join(' ').trim() + }, context); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: out.delivery === 'rejected' ? 1 : 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: `Delivery ${out.delivery}; terminal answer returns to Grok automatically.` + }) + }); + } + const out = await (0,_core_codex_routes_js__rspack_import_1/* .sendOperation */.UP)({ + ...input, + whenBusy: input.whenBusy ?? 'reject', + message: input.message.join(' ').trim() + }, signal, (message)=>context.progress.report({ + message + }), true); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/status.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_codex_bridge_js__rspack_import_1 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); + + + + + +const config = { + description: 'Probe the local Codex app-server daemon. Exit 0 only when it is usable.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: {}, + type: 'object' + } +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({}).strict(); +const resultSchema = zod__rspack_import_2/* .object */.Ikc({ + exitCode: zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .literal */.euz(0), + zod__rspack_import_2/* .literal */.euz(1) + ]) +}).passthrough(); +async function codexStatusCmd(_props) { + const status = await (0,_core_codex_bridge_js__rspack_import_1/* .codexStatus */.MU)(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: status, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatCodexStatus */.P2)(status) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (codexStatusCmd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/codex/wait.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); + + + + +const config = { + description: 'Bounded Codex wait observation; never interrupts execution.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId', + 'turnId' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + "threadId": { + "type": "string" + }, + "expectedCwd": { + "type": "string" + }, + "timeoutMs": { + "type": "number", + "description": "Observation timeout: 1-600000 milliseconds." + }, + "turnId": { + "type": "string" + }, + "messageId": { + "type": "string" + }, + "maxOutputBytes": { + "type": "number", + "description": "Reply budget: 1-4194304 bytes." + } + }, + required: [ + 'threadId', + 'turnId' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_2/* .agent */.MA)(); + const out = await (0,_core_codex_routes_js__rspack_import_1/* .observeOperation */.gT)('wait', input, signal, (message)=>context.progress.report({ + message + })); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.jS), + resultSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/codex/watch.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_codex_routes_js__rspack_import_1 = __webpack_require__("./src/core/codex/routes.ts"); + + + + +const config = { + description: 'Bounded Codex watch observation; never interrupts execution.', + exitCode: 'result', + render: { + maxElapsedMs: 660000 + }, + positionals: [ + 'threadId' + ], + inputJsonSchema: { + type: 'object', + additionalProperties: false, + properties: { + "threadId": { + "type": "string" + }, + "expectedCwd": { + "type": "string" + }, + "timeoutMs": { + "type": "number", + "description": "Observation timeout: 1-600000 milliseconds." + }, + "maxEvents": { + "type": "number", + "description": "Maximum observed events: 1-500." + } + }, + required: [ + 'threadId' + ] + } +}; +async function route({ input, signal }) { + const context = await (0,_agent_bundle_runtime__rspack_import_2/* .agent */.MA)(); + const out = await (0,_core_codex_routes_js__rspack_import_1/* .observeOperation */.gT)('watch', input, signal, (message)=>context.progress.report({ + message + })); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_codex_routes_js__rspack_import_1/* .resultText */.D6)(out) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (route), + inputSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.R9), + resultSchema: () => (/* reexport safe */ _core_codex_routes_js__rspack_import_1.FD) +}, { + config: config +}); + + +}, +"./src/cli/doctor.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_6 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_5 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_app_session_js__rspack_import_1 = __webpack_require__("./src/core/app-session.js"); +/* import */ var _core_gateway_js__rspack_import_2 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _core_store_js__rspack_import_3 = __webpack_require__("./src/core/store.js"); +/* import */ var _shared_js__rspack_import_4 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'Show which agents root and auth sources gbot can see.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_4/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_5/* .object */.Ikc({ + candidates: zod__rspack_import_5/* .array */.YOg(zod__rspack_import_5/* .string */.YjP()), + found: zod__rspack_import_5/* .array */.YOg(zod__rspack_import_5/* .string */.YjP()), + gatewayAuthPresent: zod__rspack_import_5/* .boolean */.zMY(), + grokBotAppSession: zod__rspack_import_5/* .record */.g1P(zod__rspack_import_5/* .string */.YjP(), zod__rspack_import_5/* .json */.Pq9()), + note: zod__rspack_import_5/* .string */.YjP(), + resolved: zod__rspack_import_5/* .string */.YjP().nullable() +}).strict(); +async function doctor({ input }) { + const candidates = (0,_core_store_js__rspack_import_3/* .defaultCandidateRoots */.ye)().filter((c)=>typeof c === 'string'); + const found = candidates.filter(_core_store_js__rspack_import_3/* .looksLikeAgentsRoot */.A8); + let resolved = null; + try { + resolved = (0,_core_store_js__rspack_import_3/* .resolveAgentsRoot */.v1)(input.dir); + } catch (err) { + if (!(err instanceof _core_store_js__rspack_import_3/* .StoreError */.AD)) throw err; + } + const note = 'Live roster is on the box. Prefer CURSOR_ACCESS_TOKEN then EnsureSandBox then POST gateway /api/*.'; + const gatewayAuthPresent = (0,_core_gateway_js__rspack_import_2/* .hasGatewayAuth */.nF)(); + const grokBotAppSession = (0,_core_app_session_js__rspack_import_1/* .inspectGrokBotGatewaySession */.hd)(); + const sessionJson = { + present: grokBotAppSession.present, + usable: grokBotAppSession.usable, + ...grokBotAppSession.error === undefined ? {} : { + error: grokBotAppSession.error + }, + ...'code' in grokBotAppSession && grokBotAppSession.code != null ? { + code: grokBotAppSession.code + } : {} + }; + const value = { + resolved, + found, + candidates, + gatewayAuthPresent, + grokBotAppSession: sessionJson, + note + }; + const sessionLine = grokBotAppSession.usable ? 'Grok Bot app session: usable' : grokBotAppSession.present ? `Grok Bot app session: present but unusable: ${grokBotAppSession.error}` : 'Grok Bot app session: not found'; + const text = [ + `resolved: ${resolved ?? '(none)'}`, + `gateway auth: ${gatewayAuthPresent ? 'present' : 'no'}`, + sessionLine, + 'found:', + found.length ? found.map((p)=>` ${p}`).join('\n') : ' (none)', + 'candidates:', + ...candidates.map((c)=>` ${c}`), + note + ].join('\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_6/* .Agent.Result */.g6.Result, { + value: value, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_6/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (doctor) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/add.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Add a bot to a group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + bot: { + type: 'string' + }, + group: { + type: 'string' + } + }, + required: [ + 'group', + 'bot' + ], + type: 'object' + }, + positionals: [ + 'group', + 'bot' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + bot: zod__rspack_import_2/* .string */.YjP().min(1), + group: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsAdd({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.addGroupMember(input.group, input.bot); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Added to ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsAdd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/create.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); + + + + + +const config = { + description: 'Create a Grok Bot group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + member: { + description: 'Member bot id or name (repeatable)', + items: { + type: 'string' + }, + type: 'array' + }, + name: { + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'name', + 'member' + ], + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .createFieldsSchema */.bY).extend({ + member: zod__rspack_import_2/* .array */.YOg(zod__rspack_import_2/* .string */.YjP().min(1)).min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsCreate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const { dir: _d, files: _f, gateway: _g, member, ...fields } = input; + const rec = await backend.createGroup({ + ...(0,_shared_js__rspack_import_1/* .toCreateInput */.cp)(fields), + memberIds: member + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Created group ${rec.name} (${rec.id}) with ${rec.memberIds.length} members` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsCreate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/delete.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Delete a group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsDelete({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group. Use bots delete.`); + const deleted = await backend.deleteAgent(input.ref); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(deleted), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Deleted group ${deleted.name} (${deleted.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsDelete) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/get.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show one group by id or name.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsGet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group.`); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsGet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_3 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'List Grok Bot groups.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .agentSummarySchema */.t_); +async function groupsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const all = await backend.list(); + const rows = all.filter((r)=>r.isGroup); + const groups = rows.map(_core_format_js__rspack_import_3/* .summarize */.eh); + const text = rows.length === 0 ? 'No groups.' : rows.map((r)=>(0,_core_format_js__rspack_import_3/* .formatRecord */.bM)(r, all)).join('\n\n'); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: groups, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/members.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Show members of a group (same payload as groups get).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + ref: { + description: 'Group id or name', + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsMembers({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.resolve(input.ref); + if (!rec.isGroup) throw new Error(`"${rec.name}" is a bot, not a group.`); + const all = await backend.list(); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_4/* .formatRecord */.bM)(rec, all) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsMembers) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/remove.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Remove a bot from a group.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + bot: { + type: 'string' + }, + group: { + type: 'string' + } + }, + required: [ + 'group', + 'bot' + ], + type: 'object' + }, + positionals: [ + 'group', + 'bot' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + bot: zod__rspack_import_2/* .string */.YjP().min(1), + group: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsRemove({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.removeGroupMember(input.group, input.bot); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Removed from ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsRemove) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/set.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: "Replace a group's member list.", + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + group: { + type: 'string' + }, + member: { + description: 'Member bot id or name (repeatable)', + items: { + type: 'string' + }, + type: 'array' + } + }, + required: [ + 'group', + 'member' + ], + type: 'object' + }, + positionals: [ + 'group' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + group: zod__rspack_import_2/* .string */.YjP().min(1), + member: zod__rspack_import_2/* .array */.YOg(zod__rspack_import_2/* .string */.YjP().min(1)).min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsSet({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const rec = await backend.setGroupMembers(input.group, input.member); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated ${rec.name}. Members: ${rec.memberIds.length}` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsSet) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/groups/update.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_4 = __webpack_require__("./src/core/format.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + + +const config = { + description: 'Update a group profile (members stay on set/add/remove).', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + avatarColor: { + type: 'string' + }, + avatarShape: { + type: 'string' + }, + description: { + type: 'string' + }, + hidden: { + type: 'string' + }, + name: { + type: 'string' + }, + notify: { + type: 'string' + }, + ref: { + description: 'Group id or name', + type: 'string' + }, + title: { + type: 'string' + } + }, + required: [ + 'ref' + ], + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.merge */.lK.merge(_shared_js__rspack_import_1/* .updateFieldsSchema */.qP).extend({ + ref: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .agentSummarySchema */.t_; +async function groupsUpdate({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const current = await backend.resolve(input.ref); + if (!current.isGroup) throw new Error(`"${current.name}" is a bot, not a group. Use bots update.`); + const { dir: _d, files: _f, gateway: _g, ref, ...fields } = input; + const rec = await backend.updateAgent(ref, (0,_shared_js__rspack_import_1/* .toUpdatePatch */.li)(fields)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: (0,_core_format_js__rspack_import_4/* .summarize */.eh)(rec), + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Updated group ${rec.name} (${rec.id})` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (groupsUpdate) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/history.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_history_js__rspack_import_1 = __webpack_require__("./src/core/history.js"); + + + + +const config = { + description: 'Read the opt-in local JSONL history without contacting the gateway.', + inputJsonSchema: { + additionalProperties: false, + properties: { + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + limit: { + default: 40, + description: 'Maximum matching rows (1 or more)', + type: 'number' + }, + path: { + description: 'Print the history file path', + type: 'boolean' + }, + ref: { + description: 'Bot or group id or name', + type: 'string' + }, + search: { + description: 'Case-insensitive message text filter', + type: 'string' + } + }, + type: 'object' + }, + positionals: [ + 'ref' + ] +}; +const inputSchema = zod__rspack_import_2/* .object */.Ikc({ + historyDir: zod__rspack_import_2/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_2/* .number */.aig().int().min(1).default(40), + path: zod__rspack_import_2/* .boolean */.zMY().default(false), + ref: zod__rspack_import_2/* .string */.YjP().min(1).optional(), + search: zod__rspack_import_2/* .string */.YjP().optional() +}).strict().refine((input)=>!input.path || input.ref === undefined && input.search === undefined && input.limit === 40, '--path cannot be combined with a target, --search, or --limit'); +const historyRowSchema = zod__rspack_import_2/* .record */.g1P(zod__rspack_import_2/* .string */.YjP(), zod__rspack_import_2/* .json */.Pq9()); +const resultSchema = zod__rspack_import_2/* .union */.KCZ([ + zod__rspack_import_2/* .array */.YOg(historyRowSchema), + zod__rspack_import_2/* .object */.Ikc({ + path: zod__rspack_import_2/* .string */.YjP() + }).strict() +]); +async function history({ input }) { + const file = (0,_core_history_js__rspack_import_1/* .historyPath */.ae)(input.historyDir); + if (input.path) { + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: { + path: file + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: file + }) + }); + } + const rows = await (0,_core_history_js__rspack_import_1/* .readHistory */.Lu)(file, { + limit: input.limit, + ref: input.ref, + search: input.search + }); + const text = rows.length ? rows.map((row)=>`[${row.recordedAt}] ${row.target.name} (${row.target.id}) [${row.role}] ${row.text}`).join('\n') : 'No local history.'; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: rows, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (history) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/send.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_7 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _agent_bundle_runtime__rspack_import_8 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_6 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_relay_routes_js__rspack_import_1 = __webpack_require__("./src/core/relay/routes.ts"); +/* import */ var _core_codex_bridge_js__rspack_import_2 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _core_codex_contract_js__rspack_import_3 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _core_history_js__rspack_import_4 = __webpack_require__("./src/core/history.js"); +/* import */ var _shared_js__rspack_import_5 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + + +const config = { + description: 'Send a message to a Grok Bot bot or group by name or id.', + exitCode: 'result', + inputJsonSchema: { + additionalProperties: false, + properties: { + replyMode: { + type: 'string', + enum: [ + 'auto', + 'manual' + ] + }, + codexThreadId: { + type: 'string' + }, + bindingId: { + type: 'string' + }, + expectedCwd: { + type: 'string' + }, + requestId: { + type: 'string' + }, + correlationId: { + description: 'Stable correlation id for multi-hop replies', + type: 'string' + }, + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + envelope: { + description: 'Prepend the [gbot …] header', + type: 'boolean' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + hop: { + description: 'Hop count; refused at GROK_BOT_MAX_HOPS', + type: 'number' + }, + message: { + items: { + type: 'string' + }, + type: 'array' + }, + noHistory: { + description: 'Skip local history for this command', + type: 'boolean' + }, + replyTo: { + description: 'Prior message id this send replies to', + type: 'string' + }, + target: { + type: 'string' + } + }, + required: [ + 'target', + 'message' + ], + type: 'object' + }, + positionals: [ + 'target', + 'message' + ] +}; +const inputSchema = _shared_js__rspack_import_5/* .backendFlagsSchema.extend */.lK.extend({ + ..._core_relay_routes_js__rspack_import_1/* .routeFields */.zK, + replyMode: zod__rspack_import_6/* ["enum"] */.k5n([ + 'auto', + 'manual' + ]).optional(), + correlationId: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + envelope: zod__rspack_import_6/* .boolean */.zMY().default(false), + historyDir: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + hop: zod__rspack_import_6/* .number */.aig().int().min(0).optional(), + message: zod__rspack_import_6/* .array */.YOg(zod__rspack_import_6/* .string */.YjP()).min(1), + noHistory: zod__rspack_import_6/* .boolean */.zMY().default(false), + replyTo: zod__rspack_import_6/* .string */.YjP().min(1).optional(), + target: zod__rspack_import_6/* .string */.YjP().min(1) +}).strict(); +const receiptSchema = zod__rspack_import_6/* .object */.Ikc({ + correlationId: zod__rspack_import_6/* .string */.YjP(), + delivery: zod__rspack_import_6/* ["enum"] */.k5n([ + 'accepted', + 'unknown' + ]), + envelopeId: zod__rspack_import_6/* .string */.YjP(), + exitCode: zod__rspack_import_6/* .literal */.euz(0), + hop: zod__rspack_import_6/* .number */.aig().int().min(0), + id: zod__rspack_import_6/* .string */.YjP(), + kind: zod__rspack_import_6/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + maxHops: zod__rspack_import_6/* .number */.aig().int().min(0), + messageId: zod__rspack_import_6/* .string */.YjP().optional(), + name: zod__rspack_import_6/* .string */.YjP(), + replyTo: zod__rspack_import_6/* .string */.YjP().optional(), + result: zod__rspack_import_6/* .record */.g1P(zod__rspack_import_6/* .string */.YjP(), zod__rspack_import_6/* .json */.Pq9()) +}).strict(); +// Refusals and gateway failures are the same flat document `codex send` emits. +const resultSchema = zod__rspack_import_6/* .union */.KCZ([ + receiptSchema, + _shared_js__rspack_import_5/* .failureDocumentSchema */.R9, + _core_relay_routes_js__rspack_import_1/* .relayResultSchema */.Ax +]); +const deliver = async (input)=>{ + const envelope = (0,_core_codex_bridge_js__rspack_import_2/* .buildEnvelope */.nq)({ + correlationId: input.correlationId, + envelope: input.envelope, + hop: input.hop, + replyTo: input.replyTo + }); + const message = input.message.join(' ').trim(); + const backend = await (0,_shared_js__rspack_import_5/* .openBackendFromInput */.FS)(input); + const out = await backend.send(input.target, (0,_core_codex_bridge_js__rspack_import_2/* .withEnvelopeHeader */.Mr)(message, envelope)); + (0,_core_history_js__rspack_import_4/* .saveHistory */.QX)(out, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'send', + prompt: message + }); + return { + id: out.target.id, + name: out.target.name, + kind: out.target.isGroup ? 'group' : 'bot', + result: out.result, + delivery: out.delivery === 'accepted' ? 'accepted' : 'unknown', + ...typeof out.messageId === 'string' ? { + messageId: out.messageId + } : {}, + envelopeId: envelope.messageId, + correlationId: envelope.correlationId, + ...input.replyTo ? { + replyTo: input.replyTo + } : {}, + hop: envelope.hop, + maxHops: envelope.maxHops, + exitCode: 0 + }; +}; +async function send({ input }) { + let value; + try { + if (input.replyMode === 'auto' || input.codexThreadId || input.bindingId) { + (0,_core_relay_routes_js__rspack_import_1/* .assertManagedSendOptions */.MB)(input); + if (input.files) throw Error('Automatic routes require the gateway backend'); + const out = await (0,_core_relay_routes_js__rspack_import_1/* .grokSendOperation */.bv)({ + target: input.target, + message: input.message.join(' ').trim(), + replyMode: input.replyMode ?? 'auto', + codexThreadId: input.codexThreadId, + bindingId: input.bindingId, + expectedCwd: input.expectedCwd, + requestId: input.requestId, + hop: input.hop, + correlationId: input.correlationId + }, await (0,_agent_bundle_runtime__rspack_import_7/* .agent */.MA)()); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Result */.g6.Result, { + value: { + ...out, + exitCode: out.delivery === 'rejected' ? 1 : 0 + }, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Text */.g6.Text, { + children: `Delivery ${out.delivery}; inspect codex bridge status for automatic reply delivery.` + }) + }); + } + value = await deliver(input); + } catch (error) { + value = (0,_core_codex_contract_js__rspack_import_3/* .outcomeFromError */.DG)(error); + } + const text = value.exitCode === 0 ? `Sent to ${value.kind} ${value.name} (${value.id})${value.messageId ? ` message ${value.messageId}` : ''}; envelope ${value.envelopeId}` : value.error; + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Result */.g6.Result, { + value: value, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_8/* .Agent.Text */.g6.Text, { + children: text + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (send) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/add.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var node_fs_promises__rspack_import_1 = __webpack_require__("node:fs/promises"); +/* import */ var node_path__rspack_import_2 = __webpack_require__("node:path"); +/* import */ var _agent_bundle_runtime__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_4 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_3 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + +const config = { + description: 'Add a SKILL.md to the shared skill library. Every bot sees it.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + path: { + description: 'SKILL.md file, or a directory holding one', + type: 'string' + } + }, + required: [ + 'path' + ], + type: 'object' + }, + positionals: [ + 'path' + ] +}; +const inputSchema = _shared_js__rspack_import_3/* .backendFlagsSchema.extend */.lK.extend({ + path: zod__rspack_import_4/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_3/* .skillSchema */.b7; +const skillFile = async (path)=>{ + const target = (0,node_path__rspack_import_2.resolve)(path); + return (await (0,node_fs_promises__rspack_import_1.stat)(target)).isDirectory() ? (0,node_path__rspack_import_2.join)(target, 'SKILL.md') : target; +}; +async function skillsAdd({ input }) { + const markdown = await (0,node_fs_promises__rspack_import_1.readFile)(await skillFile(input.path), 'utf8'); + const backend = await (0,_shared_js__rspack_import_3/* .openBackendFromInput */.FS)(input); + const skill = resultSchema.parse(await backend.addSkill(markdown)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Result */.g6.Result, { + value: skill, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_5/* .Agent.Text */.g6.Text, { + children: `Added skill ${skill.name} (${skill.id}) to the shared library` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsAdd) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/list.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'List the skill library every bot in this Grok Bot shares.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + } + }, + type: 'object' + } +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema */.lK; +const resultSchema = zod__rspack_import_2/* .array */.YOg(_shared_js__rspack_import_1/* .skillSchema */.b7); +async function skillsList({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const skills = resultSchema.parse(await backend.skills()); + const lines = skills.map((s)=>`${s.id} ${s.name} [${s.source}]${s.description ? ` ${s.description}` : ''}`); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: skills, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: lines.length > 0 ? lines.join('\n') : 'No skills.' + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsList) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/skills/remove.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_3 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _shared_js__rspack_import_1 = __webpack_require__("./src/cli/_shared.ts"); + + + + +const config = { + description: 'Remove a library skill by id or name. Every bot loses it.', + inputJsonSchema: { + additionalProperties: false, + properties: { + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + skill: { + description: 'Skill id or name', + type: 'string' + } + }, + required: [ + 'skill' + ], + type: 'object' + }, + positionals: [ + 'skill' + ] +}; +const inputSchema = _shared_js__rspack_import_1/* .backendFlagsSchema.extend */.lK.extend({ + skill: zod__rspack_import_2/* .string */.YjP().min(1) +}).strict(); +const resultSchema = _shared_js__rspack_import_1/* .skillSchema */.b7; +async function skillsRemove({ input }) { + const backend = await (0,_shared_js__rspack_import_1/* .openBackendFromInput */.FS)(input); + const skill = resultSchema.parse(await backend.removeSkill(input.skill)); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Result */.g6.Result, { + value: skill, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_3/* .Agent.Text */.g6.Text, { + children: `Removed skill ${skill.name} (${skill.id}) from the shared library` + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (skillsRemove) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/cli/thread.tsx"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var react_jsx_runtime__rspack_import_0 = __webpack_require__("./node_modules/react/jsx-runtime.js"); +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_format_js__rspack_import_5 = __webpack_require__("./src/core/format.js"); +/* import */ var _core_history_js__rspack_import_1 = __webpack_require__("./src/core/history.js"); +/* import */ var _core_transcript_js__rspack_import_6 = __webpack_require__("./src/core/transcript.js"); +/* import */ var _shared_js__rspack_import_2 = __webpack_require__("./src/cli/_shared.ts"); + + + + + + + +const config = { + description: 'Read the most recent messages in a Grok Bot bot or group thread.', + inputJsonSchema: { + additionalProperties: false, + properties: { + after: { + description: 'Return entries after this opaque entry id', + type: 'string' + }, + dir: { + description: 'Agents directory for --files mode', + type: 'string' + }, + files: { + description: 'Force the on-disk agents store', + type: 'boolean' + }, + full: { + description: 'Show full entry text in human output', + type: 'boolean' + }, + gateway: { + description: 'Force the live gateway', + type: 'boolean' + }, + historyDir: { + description: 'Directory containing history.jsonl', + type: 'string' + }, + limit: { + default: 40, + description: 'How many trailing entries to return (1-200)', + type: 'number' + }, + noHistory: { + description: 'Skip local history for this command', + type: 'boolean' + }, + root: { + description: 'Read one rooted thread by message id', + type: 'string' + }, + target: { + type: 'string' + } + }, + required: [ + 'target' + ], + type: 'object' + }, + positionals: [ + 'target' + ] +}; +const inputSchema = _shared_js__rspack_import_2/* .backendFlagsSchema.extend */.lK.extend({ + after: zod__rspack_import_3/* .string */.YjP().min(1).max(1024).optional(), + full: zod__rspack_import_3/* .boolean */.zMY().default(false), + historyDir: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(200).default(40), + noHistory: zod__rspack_import_3/* .boolean */.zMY().default(false), + root: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + target: zod__rspack_import_3/* .string */.YjP().min(1) +}).strict().refine((input)=>input.after === undefined || input.root === undefined, '--after cannot be combined with --root'); +const resultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +async function thread({ input }) { + const backend = await (0,_shared_js__rspack_import_2/* .openBackendFromInput */.FS)(input); + if (input.root !== undefined) { + const rooted = await backend.thread(input.target, input.root); + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(rooted, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread', + rootId: input.root + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: rooted, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(rooted, { + full: input.full + }) + }) + }); + } + const out = await backend.transcript(input.target, input.limit); + if (input.after !== undefined) { + const delta = (0,_core_transcript_js__rspack_import_6/* .transcriptDelta */.N3)(out.transcript, { + after: input.after, + limit: input.limit + }); + const selected = { + ...out, + transcript: { + entries: delta.entries + }, + cursor: delta.cursor, + entryCount: delta.entryCount, + gapReset: delta.gapReset + }; + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(selected, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread' + }); + const text = (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(selected, { + full: input.full + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: selected, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: `${text}\n\ncursor: ${delta.cursor}${delta.gapReset ? ' (gap reset)' : ''}` + }) + }); + } + (0,_core_history_js__rspack_import_1/* .saveHistory */.QX)(out, { + dir: input.historyDir, + disabled: input.noHistory, + event: 'thread' + }); + return /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Result */.g6.Result, { + value: out, + children: /*#__PURE__*/ (0,react_jsx_runtime__rspack_import_0.jsx)(_agent_bundle_runtime__rspack_import_4/* .Agent.Text */.g6.Text, { + children: (0,_core_format_js__rspack_import_5/* .formatTranscript */.oZ)(out, { + full: input.full + }) + }) + }); +} + +__webpack_require__.d(__webpack_exports__, { + "default": () => (thread) +}, { + config: config, + inputSchema: inputSchema, + resultSchema: resultSchema +}); + + +}, +"./src/core/codex/routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _codex_bridge_js__rspack_import_0 = __webpack_require__("./src/core/codex-bridge.js"); +/* import */ var _contract_js__rspack_import_1 = __webpack_require__("./src/core/codex/contract.js"); +/* import */ var _conversation_js__rspack_import_2 = __webpack_require__("./src/core/codex/conversation.js"); + + + + +const id = zod__rspack_import_3/* .string */.YjP().regex(/^[A-Za-z0-9_.:-]{1,128}$/); +const observationFields = { + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).optional(), + threadId: id, + timeoutMs: zod__rspack_import_3/* .number */.aig().int().min(1).max(600000).optional() +}; +const sendFields = { + ...observationFields, + correlationId: id.optional(), + envelope: zod__rspack_import_3/* .boolean */.zMY().optional(), + hop: zod__rspack_import_3/* .number */.aig().int().min(0).optional(), + replyTo: id.optional(), + expectedTurnId: id.optional(), + whenBusy: zod__rspack_import_3/* ["enum"] */.k5n([ + 'reject', + 'queue', + 'steer' + ]).default('reject'), + wait: zod__rspack_import_3/* .boolean */.zMY().default(false), + maxOutputBytes: zod__rspack_import_3/* .number */.aig().int().min(1).max(4194304).optional() +}; +const sendSchema = zod__rspack_import_3/* .object */.Ikc({ + ...sendFields, + message: zod__rspack_import_3/* .string */.YjP().min(1).max(4194304) +}).strict(); +const waitSchema = zod__rspack_import_3/* .object */.Ikc({ + ...observationFields, + turnId: id, + messageId: id.optional(), + maxOutputBytes: zod__rspack_import_3/* .number */.aig().int().min(1).max(4194304).optional() +}).strict(); +const watchSchema = zod__rspack_import_3/* .object */.Ikc({ + ...observationFields, + maxEvents: zod__rspack_import_3/* .number */.aig().int().min(1).max(500).default(100) +}).strict(); +const threadsSchema = zod__rspack_import_3/* .object */.Ikc({ + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(200).default(20), + cursor: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional() +}).strict(); +const resultSchema = zod__rspack_import_3/* .object */.Ikc({ + exitCode: zod__rspack_import_3/* .number */.aig().int().min(0).max(1), + threadId: zod__rspack_import_3/* .string */.YjP().optional(), + turnId: zod__rspack_import_3/* .string */.YjP().optional(), + messageId: zod__rspack_import_3/* .string */.YjP().optional(), + delivery: zod__rspack_import_3/* ["enum"] */.k5n([ + 'accepted', + 'queued', + 'rejected', + 'unknown' + ]).optional(), + execution: zod__rspack_import_3/* .object */.Ikc({ + state: zod__rspack_import_3/* ["enum"] */.k5n([ + 'completed', + 'failed', + 'interrupted', + 'waiting-for-input', + 'timeout', + 'disconnected', + 'unknown' + ]), + error: zod__rspack_import_3/* .unknown */.L5J().optional() + }).optional(), + reply: zod__rspack_import_3/* .object */.Ikc({ + text: zod__rspack_import_3/* .string */.YjP().max(4194304), + items: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .object */.Ikc({ + id: zod__rspack_import_3/* .string */.YjP(), + type: zod__rspack_import_3/* .literal */.euz('agentMessage'), + phase: zod__rspack_import_3/* ["enum"] */.k5n([ + 'final_answer' + ]).nullable(), + text: zod__rspack_import_3/* .string */.YjP().max(4194304) + })).max(2000), + truncated: zod__rspack_import_3/* .boolean */.zMY() + }).optional(), + interactions: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .unknown */.L5J())).max(500).optional(), + events: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .unknown */.L5J())).max(500).optional(), + reason: zod__rspack_import_3/* .string */.YjP().optional(), + truncated: zod__rspack_import_3/* .boolean */.zMY().optional() +}).passthrough(); +async function sendOperation(input, signal, progress, oneShot = false) { + let envelope; + let receipt; + try { + envelope = (0,_codex_bridge_js__rspack_import_0/* .buildEnvelope */.nq)(input); + if (oneShot && !input.wait && input.whenBusy !== 'steer') { + return await (0,_codex_bridge_js__rspack_import_0/* .sendToCodexThread */.ZS)(input.threadId, input.message, { + envelope, + whenBusy: input.whenBusy, + expectedCwd: input.expectedCwd, + signal + }); + } + await progress?.('Opening Codex conversation'); + const conversation = await (0,_conversation_js__rspack_import_2/* .openCodexConversation */.j)(input.threadId, { + expectedCwd: input.expectedCwd, + signal + }); + try { + receipt = await conversation.send(input.message, { + envelope, + whenBusy: input.whenBusy, + expectedTurnId: input.expectedTurnId + }); + if (!input.wait || receipt.delivery !== 'accepted' || !receipt.turnId) return receipt; + await progress?.(`Accepted message ${receipt.messageId}; observing turn ${receipt.turnId}`); + const result = await conversation.wait({ + turnId: receipt.turnId, + messageId: receipt.messageId, + timeoutMs: input.timeoutMs, + maxOutputBytes: input.maxOutputBytes, + signal + }); + return { + ...receipt, + execution: result.execution, + reply: result.reply, + interactions: result.interactions, + exitCode: result.execution.state === 'completed' ? 0 : 1 + }; + } finally{ + await conversation.close(); + } + } catch (error) { + if (receipt?.delivery === 'accepted') return { + ...receipt, + execution: { + state: 'unknown', + error: (0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error).error + }, + reply: { + text: '', + items: [], + truncated: true + }, + interactions: [], + exitCode: 1 + }; + return { + ...(0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error), + threadId: input.threadId, + ...envelope ? { + messageId: envelope.messageId, + correlationId: envelope.correlationId, + hop: envelope.hop + } : {} + }; + } +} +async function observeOperation(kind, input, signal, progress) { + try { + await progress?.(`Observing Codex thread ${input.threadId}`); + const conversation = await (0,_conversation_js__rspack_import_2/* .openCodexConversation */.j)(input.threadId, { + expectedCwd: input.expectedCwd, + signal + }); + try { + if (kind === 'wait') { + const result = await conversation.wait({ + ...input, + signal + }); + return { + ...result, + exitCode: result.execution.state === 'completed' ? 0 : 1 + }; + } + const result = await conversation.watch({ + ...input, + signal + }); + return { + ...result, + exitCode: [ + 'timeout', + 'event-limit' + ].includes(result.reason) ? 0 : 1 + }; + } finally{ + await conversation.close(); + } + } catch (error) { + return { + ...(0,_contract_js__rspack_import_1/* .outcomeFromError */.DG)(error), + threadId: input.threadId, + ...'turnId' in input ? { + turnId: input.turnId, + messageId: input.messageId + } : {} + }; + } +} +async function threadsOperation(input) { + try { + return { + ...await listCodexThreads(input), + exitCode: 0 + }; + } catch (error) { + return outcomeFromError(error); + } +} +function resultText(result) { + if (result.execution && typeof result.execution === 'object' && 'state' in result.execution) return `Codex turn ${result.turnId}: ${result.execution.state}`; + if (result.delivery === 'queued') return `Queued ${result.queuedSubmissionId} on busy Codex thread ${result.threadId}; message ${result.messageId}`; + if (result.error) return String(result.error); + if (result.delivery === 'accepted') return `Started turn ${result.turnId} (${result.turnStatus}) on Codex thread ${result.threadId}; message ${result.messageId}`; + if (result.delivery) return `Codex delivery ${result.delivery} on thread ${result.threadId}`; + if (result.reason) return `Codex observation: ${result.reason}`; + if (Array.isArray(result.threads)) return `${result.threads.length} Codex threads`; + return String(result.error ?? 'Codex observation complete'); +} + +__webpack_require__.d(__webpack_exports__, { + D6: () => (resultText), + UP: () => (sendOperation), + gT: () => (observeOperation) +}, { + FD: resultSchema, + R9: watchSchema, + at: sendFields, + jS: waitSchema +}); + + +}, +"./src/core/grok-approval-routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _gateway_js__rspack_import_0 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _grok_approvals_js__rspack_import_1 = __webpack_require__("./src/core/grok-approvals.js"); +/* import */ var _gbot_js__rspack_import_2 = __webpack_require__("./src/gbot.ts"); + + + + +const listSchema = zod__rspack_import_3/* .strictObject */.rej({ + target: zod__rspack_import_3/* .string */.YjP().min(1).max(1024) +}); +const respondSchema = _grok_approvals_js__rspack_import_1/* .grokApprovalResponseSchema */.T5; +const resultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +const listOperation = (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>(0,_gateway_js__rspack_import_0/* .listGrokApprovals */.MI)(await (0,_gateway_js__rspack_import_0/* .connectGateway */.Vq)(), listSchema.parse(input).target)); +const respondOperation = (input)=>(0,_gbot_js__rspack_import_2/* .withRedactedErrors */.yF)(async ()=>{ + const { target, ...response } = respondSchema.parse(input); + return (0,_gateway_js__rspack_import_0/* .respondGrokApproval */.OR)(await (0,_gateway_js__rspack_import_0/* .connectGateway */.Vq)(), target, response); + }); + +__webpack_require__.d(__webpack_exports__, { +}, { + FD: resultSchema, + cE: listSchema, + gi: listOperation, + lr: respondOperation, + v1: respondSchema +}); + + +}, +"./src/core/relay/routes.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var _agent_bundle_runtime__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/40.js"); +/* import */ var zod__rspack_import_3 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _managed_js__rspack_import_0 = __webpack_require__("./src/core/relay/managed.js"); +/* import */ var _gbot_js__rspack_import_1 = __webpack_require__("./src/gbot.ts"); +/* import */ var _codex_bridge_js__rspack_import_2 = __webpack_require__("./src/core/codex-bridge.js"); + + + + + +const id = zod__rspack_import_3/* .string */.YjP().min(1).max(128); +const routeFields = { + codexThreadId: id.optional(), + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional(), + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + requestId: id.optional() +}; +const grokSendSchema = zod__rspack_import_3/* .object */.Ikc({ + target: zod__rspack_import_3/* .string */.YjP().min(1), + message: zod__rspack_import_3/* .string */.YjP().min(1), + replyMode: zod__rspack_import_3/* ["enum"] */.k5n([ + "auto", + "manual" + ]).optional(), + hop: zod__rspack_import_3/* .number */.aig().int().min(0).optional(), + correlationId: id.optional(), + ...routeFields +}).strict(); +const bridgeStartSchema = zod__rspack_import_3/* .object */.Ikc({ + grokTarget: zod__rspack_import_3/* .string */.YjP().min(1), + codexThreadId: id.optional(), + expectedCwd: zod__rspack_import_3/* .string */.YjP().min(1).max(4096).optional(), + busyPolicy: zod__rspack_import_3/* ["enum"] */.k5n([ + "steer", + "reject" + ]).optional(), + requestId: id.optional() +}).strict(); +const bridgeStatusSchema = zod__rspack_import_3/* .object */.Ikc({ + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + limit: zod__rspack_import_3/* .number */.aig().int().min(1).max(100).optional() +}).strict(); +const bridgeStopSchema = zod__rspack_import_3/* .object */.Ikc({ + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + all: zod__rspack_import_3/* .boolean */.zMY().optional(), + worker: zod__rspack_import_3/* .boolean */.zMY().optional() +}).strict().refine((x)=>!!x.bindingId || x.all === true || x.worker === true, "Specify bindingId, all or worker"); +const respondSchema = zod__rspack_import_3/* .object */.Ikc({ + interactionId: zod__rspack_import_3/* .string */.YjP().min(1).max(512), + generation: id, + threadId: id, + turnId: id, + bindingId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + exchangeId: zod__rspack_import_3/* .string */.YjP().min(1).max(512).optional(), + decision: zod__rspack_import_3/* ["enum"] */.k5n([ + "accept", + "decline", + "cancel" + ]).optional(), + answersJson: zod__rspack_import_3/* .string */.YjP().min(2).max(65536).optional() +}).strict().refine((x)=>!!x.bindingId || !!x.exchangeId, "Binding or exchange scope required").refine((x)=>!!x.decision !== !!x.answersJson, "Supply decision or answersJson"); +const answersSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP().min(1).max(128), zod__rspack_import_3/* .object */.Ikc({ + answers: zod__rspack_import_3/* .array */.YOg(zod__rspack_import_3/* .string */.YjP().max(8192)).max(20) +}).strict()); +const relayResultSchema = zod__rspack_import_3/* .record */.g1P(zod__rspack_import_3/* .string */.YjP(), zod__rspack_import_3/* .json */.Pq9()); +function nativeCodexThread(context) { + return context.host.state === "available" && (0,_agent_bundle_runtime__rspack_import_4/* .lineageHostFromClient */.bg)(context.host.value.name) === "codex" && context.lineage.state === "available" && context.lineage.source === "native" && context.lineage.value.resolution === "native" ? context.lineage.value.conversation : undefined; +} +function options(context) { + return { + pluginRoot: context?.plugin.state === "available" ? context.plugin.value.root : undefined, + signal: context?.signal + }; +} +function destination(input, context) { + const codexThreadId = input.codexThreadId ?? (context ? nativeCodexThread(context) : undefined); + // Native workspace evidence belongs to the invocation, not the plugin installation directory. + const workspace = context?.workspace; + const expectedCwd = input.expectedCwd ?? (workspace?.state === "available" && workspace.source === "native" ? workspace.value.root : undefined); + return { + codexThreadId, + expectedCwd + }; +} +async function grokSendOperation(input, context) { + const route = destination(input, input.bindingId ? undefined : context); + if (input.replyMode !== "manual" && (input.bindingId || route.codexThreadId)) return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)("sendToGrok", { + grokTarget: input.target, + message: input.message, + hop: input.hop, + correlationId: input.correlationId, + ...route, + ...input.bindingId ? { + bindingId: input.bindingId + } : {}, + ...input.requestId ? { + requestId: input.requestId + } : {} + }, options(context))); + if (input.replyMode === "auto") throw Error("Automatic reply delivery requires a native Codex source, codexThreadId or bindingId"); + const message = input.hop !== undefined || input.correlationId !== undefined ? (0,_codex_bridge_js__rspack_import_2/* .withEnvelopeHeader */.Mr)(input.message, (0,_codex_bridge_js__rspack_import_2/* .buildEnvelope */.nq)(input)) : input.message; + const sent = await (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(async ()=>(0,_gbot_js__rspack_import_1/* .sendPrompt */.LV)(await (0,_gbot_js__rspack_import_1/* .connectGateway */.Vq)(), input.target, message)); + return { + result: sent.result, + target: (0,_gbot_js__rspack_import_1/* .summarizeTarget */.rW)(sent.target), + delivery: sent.delivery === "accepted" ? "accepted" : "unknown", + ...sent.delivery === "accepted" && typeof sent.messageId === "string" ? { + messageId: sent.messageId + } : {}, + replyRoute: { + mode: "manual", + reason: input.replyMode === "manual" ? "requested" : "source-unavailable" + } + }; +} +async function bridgeOperation(method, input, context) { + let routed = method === "startBinding" ? { + ...input, + ...destination(input, context) + } : input; + if (method === "respond") { + const { decision, answersJson, ...scope } = respondSchema.parse(input); + routed = { + ...scope, + result: decision ? { + decision + } : { + answers: answersSchema.parse(JSON.parse(answersJson)) + } + }; + } + if (method === "startBinding" && !routed.codexThreadId) throw Error("Specify codexThreadId when native Codex source identity is unavailable"); + return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)(method, routed, options(context))); +} +function assertManagedSendOptions(input) { + if (input.expectedTurnId !== undefined) throw Error("Managed relay does not support expectedTurnId; omit it to use managed guarded steering, or use a plain Codex send for an explicit turn guard"); + if (input.replyTo !== undefined || input.envelope === true) throw Error("Managed relay does not support legacy replyTo/envelope options; omit them or use a plain send. Use hop/correlationId for explicit managed chains"); +} +async function codexReturnOperation(input, context) { + assertManagedSendOptions(input); + if (input.whenBusy === "queue") throw Error("Managed relay supports steer or reject, not experimental queue"); + return (0,_gbot_js__rspack_import_1/* .withRedactedErrors */.yF)(()=>(0,_managed_js__rspack_import_0/* .managedOperation */.Bb)("sendToCodex", { + grokTarget: input.replyToGrok, + codexThreadId: input.threadId, + expectedCwd: input.expectedCwd, + bindingId: input.bindingId, + message: input.message, + requestId: input.requestId, + busyPolicy: input.whenBusy, + hop: input.hop, + correlationId: input.correlationId + }, options(context))); +} + +__webpack_require__.d(__webpack_exports__, { + MB: () => (assertManagedSendOptions), + bv: () => (grokSendOperation), + lt: () => (codexReturnOperation), + n1: () => (bridgeOperation) +}, { + Ax: relayResultSchema, + d5: bridgeStopSchema, + np: bridgeStatusSchema, + v1: respondSchema, + xD: bridgeStartSchema, + zK: routeFields +}); + + +}, +"./src/gbot.ts"(__unused_rspack_module, __webpack_exports__, __webpack_require__) { +/* import */ var zod__rspack_import_2 = __webpack_require__("./node_modules/zod/v4/classic/schemas.js"); +/* import */ var _core_gateway_js__rspack_import_0 = __webpack_require__("./src/core/gateway.js"); +/* import */ var _core_url_policy_js__rspack_import_1 = __webpack_require__("./src/core/url-policy.js"); + + + + + +// Hosts and the CLI print thrown error text (and stack), and a fetch or proxy failure can echo +// a credential. Rewrap with a redacted message; keep `name` and own fields such as `reason`, +// `delivery`, `mode`, and correlation ids so outcome documents still classify the failure. +const withRedactedErrors = async (run)=>{ + try { + return await run(); + } catch (error) { + const wrapped = new Error((0,_core_url_policy_js__rspack_import_1/* .redactSecrets */.fp)(error instanceof Error ? error.message : String(error))); + if (error instanceof Error) Object.assign(wrapped, error, { + name: error.name + }); + throw wrapped; + } +}; +const targetSchema = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP(), + kind: zod__rspack_import_2/* ["enum"] */.k5n([ + 'bot', + 'group' + ]), + name: zod__rspack_import_2/* .string */.YjP() +}); +const summarizeTarget = (record)=>({ + id: record.id, + kind: record.isGroup ? 'group' : 'bot', + name: record.name + }); +const entrySchema = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP(), + kind: zod__rspack_import_2/* .string */.YjP(), + role: zod__rspack_import_2/* .string */.YjP().optional(), + text: zod__rspack_import_2/* .string */.YjP(), + truncated: zod__rspack_import_2/* .boolean */.zMY(), + fullLength: zod__rspack_import_2/* .number */.aig().int().min(0), + timestampMs: zod__rspack_import_2/* .number */.aig().optional() +}); +const ENTRY_FULL_MAX = 20000; +const TRANSCRIPT_TOTAL_MAX = 200000; +// Metadata fields are capped too: an uncapped id/kind/role would bypass the total budget. +const ENTRY_META_MAX = 200; +const RECEIPT_CURSOR_MAX = 1024; +const entryFields = zod__rspack_import_2/* .object */.Ikc({ + id: zod__rspack_import_2/* .string */.YjP().default(''), + kind: zod__rspack_import_2/* .string */.YjP().default('message'), + role: zod__rspack_import_2/* .string */.YjP().optional(), + timestampMs: zod__rspack_import_2/* .number */.aig().optional() +}); +const capMeta = (value)=>value.length > ENTRY_META_MAX ? `${value.slice(0, ENTRY_META_MAX)}…` : value; +const threadEntry = (raw)=>{ + const fields = entryFields.safeParse(raw); + const full = entryText(raw); + const truncated = full.length > ENTRY_FULL_MAX; + const text = truncated ? full.slice(0, ENTRY_FULL_MAX) : full; + if (!fields.success) { + return { + id: '', + kind: 'unknown', + text, + truncated, + fullLength: full.length + }; + } + const { id, kind, role, timestampMs } = fields.data; + return { + id: capMeta(id), + kind: capMeta(kind), + ...role === undefined ? {} : { + role: capMeta(role) + }, + text, + truncated, + fullLength: full.length, + ...timestampMs === undefined ? {} : { + timestampMs + } + }; +}; +const metaLength = (entry)=>entry.id.length + entry.kind.length + (entry.role?.length ?? 0); +const transcriptEntries = (transcript)=>{ + const rows = unwrapEntries(transcript); + let remaining = TRANSCRIPT_TOTAL_MAX; + return rows.map((raw)=>{ + const entry = threadEntry(raw); + const allowText = Math.max(0, Math.min(entry.text.length, remaining - metaLength(entry))); + if (allowText < entry.text.length) { + entry.text = allowText <= 0 ? '' : entry.text.slice(0, allowText); + entry.truncated = entry.fullLength > entry.text.length; + } + remaining = Math.max(0, remaining - metaLength(entry) - entry.text.length); + return entry; + }); +}; + +__webpack_require__.d(__webpack_exports__, { + LV: () => (/* reexport safe */ _core_gateway_js__rspack_import_0.LV), + Vq: () => (/* reexport safe */ _core_gateway_js__rspack_import_0.Vq) +}, { + rW: summarizeTarget, + yF: withRedactedErrors +}); + + +}, +"node:async_hooks"(module) { + +module.exports = __rspack_external_node_async_hooks_4d8b1b4a; + + +}, +"node:buffer"(module) { + +module.exports = __rspack_external_node_buffer_4f2f74e0; + + +}, +"node:child_process"(module) { + +module.exports = __rspack_external_node_child_process_cd435d64; + + +}, +"node:crypto"(module) { + +module.exports = __rspack_external_node_crypto_2e7c4b46; + + +}, +"node:fs"(module) { + +module.exports = __rspack_external_node_fs_1b05aee1; + + +}, +"node:fs/promises"(module) { + +module.exports = __rspack_external_node_fs_promises_3b710708; + + +}, +"node:net"(module) { + +module.exports = __rspack_external_node_net_5ed819e1; + + +}, +"node:os"(module) { + +module.exports = __rspack_external_node_os_4f3c9d58; + + +}, +"node:path"(module) { + +module.exports = __rspack_external_node_path_806ed179; + + +}, +"node:readline"(module) { + +module.exports = __rspack_external_node_readline_d8f53bef; + + +}, +"node:string_decoder"(module) { + +module.exports = __rspack_external_node_string_decoder_69b9bd04; + + +}, +"node:url"(module) { + +module.exports = __rspack_external_node_url_3991086a; + + +}, +"node:worker_threads"(module) { + +module.exports = __rspack_external_node_worker_threads_28ca7740; + + +}, +"util"(module) { +module.exports = __rspack_createRequire_require("util"); + +}, +"./node_modules/@agent-bundle/runtime/dist/302.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_buffer__rspack_import_0 = __webpack_require__("node:buffer"); +/* import */ var react__rspack_import_1 = __webpack_require__("./node_modules/react/index.js"); + + +const isServerComponent = (value)=>'function' == typeof value; +const asMcpElement = (node)=>{ + let element = node; + while(isValidElement(element) && isServerComponent(element.type))element = element.type(element.props); + if (!isValidElement(element) || 'string' != typeof element.type || !element.type.startsWith('mcp-')) throw new Error('Expected an MCP result element'); + return { + props: element.props, + type: element.type + }; +}; +const requiredString = (value, message)=>{ + if ('string' != typeof value || '' === value.trim()) throw new Error(message); + return value; +}; +const textChild = (children, message)=>{ + const values = Children.toArray(children); + if (1 !== values.length || 'string' != typeof values[0]) throw new Error(message); + return values[0]; +}; +const jsonLeafBytes = (value)=>node_buffer__rspack_import_0.Buffer.byteLength(JSON.stringify(value), 'utf8'); +const isArrayIndex = (key, length)=>{ + if ('0' === key) return length > 0; + if (!/^[1-9]\d*$/.test(key)) return false; + const index = Number(key); + return Number.isSafeInteger(index) && index < length; +}; +const jsonPathError = (reason, path)=>new Error('' === path ? reason : `${reason} at ${path}`); +const cloneJsonValue = (value, ancestors, path, depth = 0, budget)=>{ + budget?.checkDepth(depth); + budget?.addNode(); + if (null === value || 'boolean' == typeof value || 'string' == typeof value) { + budget?.addBytes(jsonLeafBytes(value)); + return value; + } + if ('number' == typeof value) { + if (!Number.isFinite(value)) throw jsonPathError('non-finite number', path); + budget?.addBytes(jsonLeafBytes(value)); + return value; + } + if ('object' != typeof value) throw jsonPathError('non-JSON value', path); + if (ancestors.has(value)) throw jsonPathError('cyclic value', path); + ancestors.add(value); + try { + if (Array.isArray(value)) { + const keys = Reflect.ownKeys(value); + if (keys.length !== value.length + 1 || keys.some((key)=>'length' !== key && ('string' != typeof key || !isArrayIndex(key, value.length)))) throw jsonPathError('sparse or decorated array', path); + budget?.addBytes(2); + const clone = []; + for(let index = 0; index < value.length; index += 1){ + if (index > 0) budget?.addBytes(1); + const elementPath = `${path}[${index}]`; + if (!Object.hasOwn(value, index)) throw jsonPathError('sparse array', elementPath); + const descriptor = Object.getOwnPropertyDescriptor(value, String(index)); + if (void 0 === descriptor || !('value' in descriptor)) throw jsonPathError('array accessor', elementPath); + clone.push(void 0 === descriptor.value ? cloneJsonValue(null, ancestors, elementPath, depth + 1, budget) : cloneJsonValue(descriptor.value, ancestors, elementPath, depth + 1, budget)); + } + return clone; + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && null !== prototype) throw jsonPathError('non-plain object', path); + budget?.addBytes(2); + const clone = Object.create(null); + let properties = 0; + for (const key of Reflect.ownKeys(value)){ + if ('string' != typeof key) throw jsonPathError('symbol key', path); + const propertyPath = '' === path ? key : `${path}.${key}`; + const descriptor = Object.getOwnPropertyDescriptor(value, key); + if (void 0 === descriptor || !descriptor.enumerable || !('value' in descriptor)) throw jsonPathError('non-enumerable or accessor property', propertyPath); + if (void 0 !== descriptor.value) { + if (properties > 0) budget?.addBytes(1); + budget?.addBytes(jsonLeafBytes(key) + 1); + properties += 1; + clone[key] = cloneJsonValue(descriptor.value, ancestors, propertyPath, depth + 1, budget); + } + } + return clone; + } finally{ + ancestors.delete(value); + } +}; +const jsonRecord = (value, message)=>{ + try { + if (null === value || 'object' != typeof value || Array.isArray(value)) throw new Error('not a plain object'); + return cloneJsonValue(value, new Set(), ''); + } catch (error) { + throw new Error(`${message} (${error instanceof Error ? error.message : String(error)})`, { + cause: error + }); + } +}; +const deepFreezeJson = (value)=>{ + if ('object' == typeof value && null !== value) { + for (const child of Object.values(value))deepFreezeJson(child); + Object.freeze(value); + } + return value; +}; +const snapshotJsonValue = (value, message, budget)=>{ + try { + return deepFreezeJson(cloneJsonValue(value, new Set(), '', budget?.depth ?? 0, budget?.limits)); + } catch (error) { + if (error instanceof Error && 'AgentContractError' === error.name) throw error; + throw new Error(`${message} (${error instanceof Error ? error.message : String(error)})`, { + cause: error + }); + } +}; +const lowerContent = (node)=>{ + const element = asMcpElement(node); + const { props } = element; + switch(element.type){ + case 'mcp-text': + return { + text: textChild(props.children, 'mcp-text requires one text child'), + type: 'text' + }; + case 'mcp-image': + return { + data: requiredString(props.data, 'mcp-image requires non-empty data and mimeType'), + mimeType: requiredString(props.mimeType, 'mcp-image requires non-empty data and mimeType'), + type: 'image' + }; + case 'mcp-audio': + return { + data: requiredString(props.data, 'mcp-audio requires non-empty data and mimeType'), + mimeType: requiredString(props.mimeType, 'mcp-audio requires non-empty data and mimeType'), + type: 'audio' + }; + case 'mcp-resource-link': + { + const mimeType = props.mimeType; + if (void 0 !== mimeType && 'string' != typeof mimeType) throw new Error('mcp-resource-link mimeType must be a string'); + return { + ...void 0 === mimeType ? {} : { + mimeType + }, + name: requiredString(props.name, 'mcp-resource-link requires non-empty uri and name'), + type: 'resource_link', + uri: requiredString(props.uri, 'mcp-resource-link requires non-empty uri and name') + }; + } + case 'mcp-embedded-resource': + { + const hasText = void 0 !== props.text; + const hasTextChild = void 0 !== props.children; + const hasBlob = void 0 !== props.blob; + if (Number(hasText) + Number(hasTextChild) + Number(hasBlob) !== 1) throw new Error('mcp-embedded-resource accepts exactly one text or blob value'); + const mimeType = props.mimeType; + if (void 0 !== mimeType && 'string' != typeof mimeType) throw new Error('mcp-embedded-resource mimeType must be a string'); + const resource = { + ...void 0 === mimeType ? {} : { + mimeType + }, + uri: requiredString(props.uri, 'mcp-embedded-resource requires a non-empty uri'), + ...hasBlob ? { + blob: requiredString(props.blob, 'mcp-embedded-resource blob must be non-empty') + } : { + text: hasTextChild ? textChild(props.children, 'mcp-embedded-resource requires one text child') : requiredString(props.text, 'mcp-embedded-resource text must be non-empty') + } + }; + return { + resource, + type: 'resource' + }; + } + case 'mcp-result': + throw new Error('mcp-result may not be nested'); + default: + throw new Error(`Unsupported MCP result element: ${element.type}`); + } +}; +const lowerMcpResult = (node)=>{ + const root = asMcpElement(node); + if ('mcp-result' !== root.type) throw new Error('Expected mcp-result as the root element'); + if (void 0 !== root.props.isError && 'boolean' != typeof root.props.isError) throw new Error('mcp-result isError must be a boolean'); + const structuredContent = root.props.structuredContent; + const metadata = root.props._meta; + return { + content: Children.toArray(root.props.children).map(lowerContent), + ...void 0 === metadata ? {} : { + _meta: jsonRecord(metadata, 'mcp-result _meta must be JSON-serializable') + }, + ...void 0 === structuredContent ? {} : { + structuredContent: jsonRecord(structuredContent, 'mcp-result structuredContent must be JSON-serializable') + }, + ...void 0 === root.props.isError ? {} : { + isError: root.props.isError + } + }; +}; +const AGENT_DOCUMENT_VERSION = 1; +const agentRenderAbortError = ()=>new DOMException('Agent render was aborted', 'AbortError'); +const DEFAULT_AGENT_RENDER_LIMITS = Object.freeze({ + maxDocumentBytes: 1048576, + maxDocumentDepth: 64, + maxDocumentNodes: 10000, + maxElapsedMs: 60000, + maxEventBytes: 1049600, + maxEventRate: 1000, + maxEvents: 10000 +}); +class AgentContractError extends Error { + code; + constructor(code, message, options){ + super(message, options); + this.code = code; + this.name = 'AgentContractError'; + } +} +const resolveAgentRenderLimits = (overrides = {})=>{ + const limits = { + ...DEFAULT_AGENT_RENDER_LIMITS, + ...overrides + }; + for (const [name, value] of Object.entries(limits))if (!Number.isSafeInteger(value) || value <= 0) throw new AgentContractError('invalid-document', `${name} must be a positive safe integer`); + return Object.freeze(limits); +}; +const agent_document_requiredString = (value, field)=>{ + if ('string' != typeof value || '' === value.trim()) throw new AgentContractError('invalid-document', `${field} must be a non-empty string`); + return value; +}; +const agent_document_text = (value, field)=>{ + if ('string' != typeof value) throw new AgentContractError('invalid-document', `${field} must be a string`); + return value; +}; +const optionalString = (value, field)=>void 0 === value ? void 0 : agent_document_requiredString(value, field); +const elapsedTimeExceeded = (maxElapsedMs)=>new AgentContractError('elapsed-time-exceeded', `Agent render elapsed time exceeds ${String(maxElapsedMs)}ms`); +const expectDocumentDepth = (depth, limits)=>{ + if (depth > limits.maxDocumentDepth) throw new AgentContractError('document-depth-exceeded', `Agent Document depth exceeds ${String(limits.maxDocumentDepth)}`); +}; +const admitDocumentNode = (state)=>{ + state.nodes += 1; + if (state.nodes > state.limits.maxDocumentNodes) throw new AgentContractError('document-node-count-exceeded', `Agent Document node count exceeds ${String(state.limits.maxDocumentNodes)}`); +}; +const jsonBudget = (state)=>({ + addBytes (n) { + state.bytes += n; + if (state.bytes > state.limits.maxDocumentBytes) throw new AgentContractError('document-bytes-exceeded', `Agent Document bytes exceed ${String(state.limits.maxDocumentBytes)}`); + }, + addNode () { + admitDocumentNode(state); + }, + checkDepth (depth) { + expectDocumentDepth(depth, state.limits); + } + }); +const snapshotJson = (value, message, depth, state)=>{ + try { + return snapshotJsonValue(value, message, { + depth, + limits: jsonBudget(state) + }); + } catch (error) { + if (error instanceof AgentContractError) throw error; + throw new AgentContractError('invalid-document', error instanceof Error ? error.message : message, { + cause: error + }); + } +}; +const progressNumber = (value, field)=>{ + if ('number' != typeof value || !Number.isFinite(value) || value < 0) throw new AgentContractError('invalid-document', `${field} must be a finite non-negative number`); + return value; +}; +const snapshotNode = (node, depth, state)=>{ + if (null === node || 'object' != typeof node || Array.isArray(node)) throw new AgentContractError('invalid-document', 'Agent Document nodes must be plain objects'); + if (state.ancestors.has(node)) throw new AgentContractError('invalid-document', 'Agent Document node tree must not be cyclic'); + expectDocumentDepth(depth, state.limits); + admitDocumentNode(state); + state.ancestors.add(node); + try { + switch(node.kind){ + case 'result': + { + if (!Array.isArray(node.children)) throw new AgentContractError('invalid-document', 'Agent result children must be an array'); + const children = Object.freeze(node.children.map((child)=>snapshotNode(child, depth + 1, state))); + const metadata = void 0 === node.metadata ? void 0 : snapshotJson(node.metadata, 'Agent result metadata must be JSON-serializable', depth, state); + return Object.freeze({ + children, + kind: 'result', + ...void 0 === metadata ? {} : { + metadata + } + }); + } + case 'markdown': + return Object.freeze({ + kind: 'markdown', + text: agent_document_text(node.text, 'Agent markdown text') + }); + case 'text': + return Object.freeze({ + kind: 'text', + text: agent_document_text(node.text, 'Agent text') + }); + case 'context': + return Object.freeze({ + kind: 'context', + text: agent_document_text(node.text, 'Agent context text') + }); + case 'json': + return Object.freeze({ + kind: 'json', + value: snapshotJson(node.value, 'Agent JSON node value must be JSON-serializable', depth, state) + }); + case 'progress': + { + const completed = progressNumber(node.completed, 'Agent progress completed'); + const total = void 0 === node.total ? void 0 : progressNumber(node.total, 'Agent progress total'); + if (void 0 !== total && completed > total) throw new AgentContractError('invalid-document', 'Agent progress completed must not exceed total'); + const message = optionalString(node.message, 'Agent progress message'); + return Object.freeze({ + completed, + kind: 'progress', + ...void 0 === message ? {} : { + message + }, + ...void 0 === total ? {} : { + total + } + }); + } + case 'image': + return Object.freeze({ + data: agent_document_requiredString(node.data, 'Agent image data'), + kind: 'image', + mimeType: agent_document_requiredString(node.mimeType, 'Agent image mimeType') + }); + case 'audio': + return Object.freeze({ + data: agent_document_requiredString(node.data, 'Agent audio data'), + kind: 'audio', + mimeType: agent_document_requiredString(node.mimeType, 'Agent audio mimeType') + }); + case 'resource': + { + const mimeType = optionalString(node.mimeType, 'Agent resource mimeType'); + return Object.freeze({ + kind: 'resource', + ...void 0 === mimeType ? {} : { + mimeType + }, + name: agent_document_requiredString(node.name, 'Agent resource name'), + uri: agent_document_requiredString(node.uri, 'Agent resource uri') + }); + } + case 'error': + return Object.freeze({ + code: agent_document_requiredString(node.code, 'Agent error code'), + kind: 'error', + message: agent_document_text(node.message, 'Agent error message') + }); + default: + { + const exhaustive = node; + throw new AgentContractError('invalid-document', `Unsupported Agent Document node kind: ${String(exhaustive.kind)}`); + } + } + } finally{ + state.ancestors.delete(node); + } +}; +const documentStatus = (status)=>{ + switch(status){ + case 'success': + case 'represented-error': + case 'failed': + return status; + default: + { + const exhaustive = status; + throw new AgentContractError('invalid-document', `Unsupported Agent Document status: ${String(exhaustive)}`); + } + } +}; +const createAgentDocument = (input, limitOverrides = {})=>{ + if (input.version !== AGENT_DOCUMENT_VERSION) throw new AgentContractError('invalid-document', `Unsupported Agent Document version: ${String(input.version)}`); + const limits = resolveAgentRenderLimits(limitOverrides); + const state = { + ancestors: new Set(), + bytes: 0, + limits, + nodes: 0 + }; + const root = snapshotNode(input.root, 1, state); + const value = void 0 === input.value ? void 0 : snapshotJson(input.value, 'Agent Document value must be JSON-serializable', 1, state); + const document = Object.freeze({ + root, + status: documentStatus(input.status), + ...void 0 === value ? {} : { + value + }, + version: AGENT_DOCUMENT_VERSION + }); + const bytes = node_buffer__rspack_import_0.Buffer.byteLength(JSON.stringify(document), 'utf8'); + if (bytes > limits.maxDocumentBytes) throw new AgentContractError('document-bytes-exceeded', `Agent Document bytes exceed ${String(limits.maxDocumentBytes)}`); + return document; +}; +const snapshotRenderError = (error, limits)=>{ + const data = void 0 === error.data ? void 0 : snapshotJson(error.data, 'Agent render error data must be JSON-serializable', 1, { + ancestors: new Set(), + bytes: 0, + limits, + nodes: 0 + }); + return Object.freeze({ + code: agent_document_requiredString(error.code, 'Agent render error code'), + ...void 0 === data ? {} : { + data + }, + message: agent_document_text(error.message, 'Agent render error message') + }); +}; +const snapshotEvent = (input, sequence, limits)=>{ + switch(input.type){ + case 'shell': + return Object.freeze({ + document: createAgentDocument(input.document, limits), + sequence, + type: 'shell' + }); + case 'progress': + { + const completed = progressNumber(input.completed, 'Agent render progress completed'); + const total = void 0 === input.total ? void 0 : progressNumber(input.total, 'Agent render progress total'); + if (void 0 !== total && completed > total) throw new AgentContractError('invalid-document', 'Agent render progress completed must not exceed total'); + const message = optionalString(input.message, 'Agent render progress message'); + return Object.freeze({ + completed, + ...void 0 === message ? {} : { + message + }, + sequence, + ...void 0 === total ? {} : { + total + }, + type: 'progress' + }); + } + case 'replace': + return Object.freeze({ + boundaryId: agent_document_requiredString(input.boundaryId, 'Agent render boundaryId'), + document: createAgentDocument(input.document, limits), + sequence, + type: 'replace' + }); + case 'error': + { + const boundaryId = optionalString(input.boundaryId, 'Agent render boundaryId'); + return Object.freeze({ + ...void 0 === boundaryId ? {} : { + boundaryId + }, + error: snapshotRenderError(input.error, limits), + sequence, + type: 'error' + }); + } + case 'complete': + return Object.freeze({ + document: createAgentDocument(input.document, limits), + sequence, + type: 'complete' + }); + default: + { + const exhaustive = input; + throw new AgentContractError('invalid-document', `Unsupported Agent render event: ${String(exhaustive.type)}`); + } + } +}; +const createAgentRenderEventSequence = (limitOverrides = {}, now = Date.now)=>{ + const limits = resolveAgentRenderLimits(limitOverrides); + const startedAt = now(); + const recentTimes = []; + let completed = false; + let nextSequence = 0; + return Object.freeze({ + get completed () { + return completed; + }, + get maxElapsedMs () { + return limits.maxElapsedMs; + }, + emit (input) { + if (completed) throw new AgentContractError('handoff-required', 'The render is complete; later work requires a new invocation handoff'); + const emittedAt = now(); + if (emittedAt - startedAt > limits.maxElapsedMs) throw elapsedTimeExceeded(limits.maxElapsedMs); + recentTimes.push(emittedAt); + const windowStart = emittedAt - 1000; + while(void 0 !== recentTimes[0] && recentTimes[0] < windowStart)recentTimes.shift(); + if (recentTimes.length > limits.maxEventRate) throw new AgentContractError('event-rate-exceeded', `Agent render event rate exceeds ${String(limits.maxEventRate)} per second`); + if (nextSequence >= limits.maxEvents) throw new AgentContractError('event-count-exceeded', `Agent render event count exceeds ${String(limits.maxEvents)}`); + const event = snapshotEvent(input, nextSequence, limits); + const bytes = node_buffer__rspack_import_0.Buffer.byteLength(JSON.stringify(event), 'utf8'); + if (bytes > limits.maxEventBytes) throw new AgentContractError('event-bytes-exceeded', `Agent render event bytes exceed ${String(limits.maxEventBytes)}`); + nextSequence += 1; + if ('complete' === event.type) completed = true; + return event; + }, + get nextSequence () { + return nextSequence; + }, + get remainingMs () { + return limits.maxElapsedMs - (now() - startedAt); + } + }); +}; + + +__webpack_require__.d(__webpack_exports__, { + I2: () => (AgentContractError) +}, { + Dy: admitDocumentNode, + MI: expectDocumentDepth, + ZX: createAgentDocument, + i0: resolveAgentRenderLimits, + k2: agentRenderAbortError, + mY: snapshotJsonValue, + n4: createAgentRenderEventSequence, + zm: elapsedTimeExceeded +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/315.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var effect__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var effect__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var effect__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var effect__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Latch.js"); +/* import */ var effect__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Stream.js"); +/* import */ var effect__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Fiber.js"); +/* import */ var _736_js__rspack_import_1 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); +/* import */ var _302_js__rspack_import_2 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/302.js"); + + + +const TYPED_ERROR_NAMES = new Set([ + 'AgentContractError', + 'AgentNoticeError', + 'AgentRequestError', + 'AgentRuntimeError', + 'AgentStateError', + 'McpProjectionError' +]); +const interruptAs = ()=>effect__rspack_import_0/* .interrupt */.GaK; +const abortError = (cause)=>{ + const error = new DOMException('The operation was aborted', 'AbortError'); + if (void 0 !== cause) error.cause = cause; + return error; +}; +const isAbortError = (error)=>error instanceof DOMException && 'AbortError' === error.name || error instanceof Error && 'AbortError' === error.name; +const isTypedRuntimeError = (error)=>error instanceof _736_js__rspack_import_1/* .AgentRequestError */.r8 || error instanceof _302_js__rspack_import_2/* .AgentContractError */.I2 || error instanceof Error && TYPED_ERROR_NAMES.has(error.name); +const toRuntimeError = (value)=>{ + if (isAbortError(value) || isTypedRuntimeError(value)) return value; + if (value instanceof Error) return value; + return new Error(String(value)); +}; +const mapCause = (cause)=>{ + if (effect__rspack_import_3/* .hasInterruptsOnly */.nn(cause)) return abortError(cause); + return toRuntimeError(effect__rspack_import_3/* .squash */.iw(cause)); +}; +const throwExitFailure = (exit)=>{ + if (effect__rspack_import_4/* .isSuccess */.oJ(exit)) return exit.value; + throw mapCause(exit.cause); +}; +const runOptions = (options)=>options?.signal === void 0 ? void 0 : { + signal: options.signal + }; +const runPromise = async (effect, options)=>throwExitFailure(await effect__rspack_import_0/* .runPromiseExit */.NpQ(effect, runOptions(options))); +const makeScopedEffectRuntime = (layer)=>{ + const runtime = ManagedRuntime.make(layer); + let closing; + return Object.freeze({ + close () { + closing ??= runtime.dispose(); + return closing; + }, + async run (effect, options) { + return throwExitFailure(await runtime.runPromiseExit(effect, runOptions(options))); + } + }); +}; +const abortToInterrupt = (signal)=>effect__rspack_import_0/* .suspend */.DYE(()=>{ + if (signal.aborted) return interruptAs(); + return effect__rspack_import_0/* .callback */.E2r((resume)=>{ + let settled = false; + const onAbort = ()=>{ + if (settled) return; + settled = true; + resume(effect__rspack_import_0/* .interrupt */.GaK); + }; + signal.addEventListener('abort', onAbort, { + once: true + }); + if (signal.aborted) onAbort(); + return effect__rspack_import_0/* .sync */.OH5(()=>{ + signal.removeEventListener('abort', onAbort); + }); + }); + }); +const interruptWhenAborted = (effect, signal)=>Effect.raceFirst(effect, abortToInterrupt(signal)); +const streamToReadableStream = (stream, options = {})=>{ + let currentPull; + let fiber; + let terminal; + const latch = effect__rspack_import_5/* .makeUnsafe */.LZ(false); + const source = void 0 === options.signal ? stream : effect__rspack_import_6/* .interruptWhen */.S67(stream, abortToInterrupt(options.signal)); + const settlePull = (error)=>{ + const waiter = currentPull; + currentPull = void 0; + if (void 0 === waiter) return; + if (void 0 === error) waiter.resolve(); + else waiter.reject(error); + }; + const finish = (error)=>{ + if (void 0 !== terminal) return; + terminal = { + error + }; + settlePull(error); + }; + const failController = (controller, error)=>{ + try { + controller.error(error); + } catch {} + finish(error); + }; + return new ReadableStream({ + cancel () { + const running = fiber; + fiber = void 0; + if (void 0 === running) return; + effect__rspack_import_0/* .runFork */.MY7(effect__rspack_import_0/* .asVoid */.NLW(effect__rspack_import_7/* .interrupt */.G(running))); + }, + pull () { + if (void 0 !== terminal) return void 0 === terminal.error ? Promise.resolve() : Promise.reject(terminal.error); + options.onPull?.(); + return new Promise((resolve, reject)=>{ + currentPull = { + reject, + resolve + }; + latch.openUnsafe(); + }); + }, + start (controller) { + const watched = effect__rspack_import_6/* .tapError */.sFT(source, (error)=>effect__rspack_import_0/* .sync */.OH5(()=>{ + failController(controller, toRuntimeError(error)); + })); + fiber = effect__rspack_import_0/* .runFork */.MY7(effect__rspack_import_6/* .runForEachArray */.hM$(watched, (chunk)=>latch.whenOpen(effect__rspack_import_0/* .sync */.OH5(()=>{ + if (void 0 !== terminal) return; + latch.closeUnsafe(); + for (const item of chunk){ + controller.enqueue(item); + if (options.closeOn?.(item) === true) { + controller.close(); + options.onPullDelivered?.(); + finish(); + if (void 0 !== fiber) effect__rspack_import_0/* .runFork */.MY7(effect__rspack_import_7/* .interrupt */.G(fiber)); + return; + } + } + options.onPullDelivered?.(); + settlePull(); + })))); + fiber.addObserver((exit)=>{ + if (void 0 !== terminal) return; + if (effect__rspack_import_4/* .isFailure */.N6(exit)) return void failController(controller, mapCause(exit.cause)); + try { + controller.close(); + } catch {} + finish(); + }); + } + }, options.strategy); +}; +const scopedAbortSignal = effect__rspack_import_0/* .abortSignal */.dsN; + + +__webpack_require__.d(__webpack_exports__, { +}, { + K0: mapCause, + _I: streamToReadableStream, + lQ: scopedAbortSignal, + p7: abortToInterrupt, + pR: runPromise, + qN: toRuntimeError, + zf: isAbortError +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/40.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_fs_promises__rspack_import_0 = __webpack_require__("node:fs/promises"); + + +const CODEX_ROLLOUT_HEAD_BYTES = 1048576; +const ROLLOUT_BASENAME = /rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\.jsonl$/iu; +const codexThreadFromRolloutPath = (path)=>{ + if (void 0 === path) return; + const match = ROLLOUT_BASENAME.exec(path); + return match?.[1]?.toLowerCase(); +}; +const record = (value)=>null === value || 'object' != typeof value || Array.isArray(value) ? void 0 : value; +const codex_rollout_text = (value)=>'string' == typeof value && '' !== value.trim() ? value : void 0; +const parseCodexRolloutMeta = (head)=>{ + const newline = head.indexOf('\n'); + const line = (-1 === newline ? head : head.slice(0, newline)).trim(); + if ('' === line) return; + let parsed; + try { + parsed = JSON.parse(line); + } catch { + return; + } + const item = record(parsed); + if (item?.['type'] !== 'session_meta') return; + const payload = record(item['payload']); + const thread = codex_rollout_text(payload?.['id']); + if (void 0 === payload || void 0 === thread) return; + const root = codex_rollout_text(payload['session_id']); + const source = record(payload['source']); + const subagent = record(source?.['subagent']); + if (void 0 === subagent) { + const kind = codex_rollout_text(source?.['subagent']); + return { + ...void 0 === kind ? {} : { + subagentKind: kind + }, + ...void 0 === root ? {} : { + root + }, + thread + }; + } + const [subagentKind] = Object.keys(subagent); + const spawn = record(subagent['thread_spawn']); + const parent = codex_rollout_text(spawn?.['parent_thread_id']) ?? codex_rollout_text(payload['parent_thread_id']); + const rawDepth = spawn?.['depth']; + const depth = 'number' == typeof rawDepth && Number.isInteger(rawDepth) && rawDepth > 0 ? rawDepth : void 0; + const agentPath = codex_rollout_text(spawn?.['agent_path']) ?? codex_rollout_text(payload['agent_path']); + return { + ...void 0 === agentPath ? {} : { + agentPath + }, + ...void 0 === depth ? {} : { + depth + }, + ...void 0 === parent ? {} : { + parent + }, + ...void 0 === root ? {} : { + root + }, + ...void 0 === subagentKind ? {} : { + subagentKind + }, + thread + }; +}; +const readCodexRolloutHead = async (path)=>{ + let handle; + try { + handle = await promises_open(path, 'r'); + const buffer = Buffer.allocUnsafe(CODEX_ROLLOUT_HEAD_BYTES); + let filled = 0; + while(filled < buffer.length){ + const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled); + if (0 === bytesRead) break; + const newline = buffer.subarray(filled, filled + bytesRead).indexOf(0x0a); + if (-1 !== newline) { + filled += newline; + break; + } + filled += bytesRead; + } + return buffer.subarray(0, filled).toString('utf8'); + } catch { + return; + } finally{ + await handle?.close().catch(()=>void 0); + } +}; +const readCodexSpawnLineage = async (path, thread, read = readCodexRolloutHead)=>{ + if (void 0 === path) return; + const head = await read(path); + if (void 0 === head) return; + const meta = parseCodexRolloutMeta(head); + if (void 0 === meta || meta.thread !== thread || void 0 === meta.parent || void 0 === meta.depth) return; + return { + ...meta, + depth: meta.depth, + parent: meta.parent + }; +}; +const nativeString = (native, key)=>{ + const value = native[key]; + return 'string' == typeof value && '' !== value.trim() ? value : void 0; +}; +const lineageHostFromClient = (clientName)=>{ + if (void 0 === clientName) return; + if (clientName.startsWith('claude')) return 'claude'; + if (clientName.startsWith('codex')) return 'codex'; + if (clientName.startsWith('cursor')) return 'cursor'; +}; +const lineageCarrier = (host, native)=>{ + switch(host){ + case 'claude': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'prompt_id'), + root: nativeString(native, 'session_id') + }; + case 'codex': + return { + conversation: nativeString(native, 'agent_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'turn_id'), + root: nativeString(native, 'session_id') + }; + case 'cursor': + return { + conversation: nativeString(native, 'conversation_id') ?? nativeString(native, 'session_id'), + generation: nativeString(native, 'generation_id'), + root: void 0 + }; + default: + { + const unreachable = host; + throw new Error(`Unhandled lineage host ${String(unreachable)}`); + } + } +}; +const resolveNativeLineage = (host, native)=>{ + const carrier = lineageCarrier(host, native); + if ('cursor' === host || void 0 === carrier.conversation || void 0 === carrier.root) return unavailable('no-shared-runtime'); + if (carrier.conversation !== carrier.root) return unavailable('no-shared-runtime'); + return available({ + conversation: carrier.root, + depth: 0, + ...void 0 === carrier.generation ? {} : { + generation: carrier.generation + }, + resolution: 'native', + root: carrier.root + }, 'native'); +}; +const resolveStandaloneLineage = async (host, native, read)=>{ + const fromPayload = resolveNativeLineage(host, native); + if ('codex' !== host || 'available' === fromPayload.state) return fromPayload; + const carrier = lineageCarrier(host, native); + if (void 0 === carrier.conversation || void 0 === carrier.root) return fromPayload; + const ownRollout = 'SubagentStop' === nativeString(native, 'hook_event_name') ? nativeString(native, "agent_transcript_path") : nativeString(native, "transcript_path"); + const spawn = await readCodexSpawnLineage(ownRollout, carrier.conversation, read); + if (void 0 === spawn) return fromPayload; + const type = nativeString(native, 'agent_type'); + return available({ + conversation: carrier.conversation, + depth: spawn.depth, + ...void 0 === carrier.generation ? {} : { + generation: carrier.generation + }, + parent: spawn.parent, + resolution: "transcript", + root: carrier.root, + subagent: { + id: carrier.conversation, + ...void 0 === type ? {} : { + type + } + } + }, 'derived'); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + bg: lineageHostFromClient +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/49.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_fs__rspack_import_1 = __webpack_require__("node:fs"); +/* import */ var node_os__rspack_import_2 = __webpack_require__("node:os"); +/* import */ var node_path__rspack_import_3 = __webpack_require__("node:path"); +/* import */ var _736_js__rspack_import_4 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/736.js"); + + + + + +const PLUGIN_ROOT_ENV_ANCHOR = 'AGENT_BUNDLE_PLUGIN_ROOT'; +const PLUGIN_STATE_ROOT_ENV_ANCHOR = 'AGENT_BUNDLE_STATE_ROOT'; +const PLUGIN_STATE_DIRECTORY = 'state'; +const unexpandedToken = /\$\{[^}]*\}/u; +const defaultWarn = (message)=>{ + process.stderr.write(`${message}\n`); +}; +const safePluginSegment = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/u; +const pluginStateSegment = (root)=>{ + const canonicalRoot = (0,node_fs__rspack_import_1.existsSync)(root) ? (0,node_fs__rspack_import_1.realpathSync)(root) : (0,node_path__rspack_import_3.resolve)(root); + const digest = (0,node_crypto__rspack_import_0.createHash)('sha256').update(canonicalRoot).digest('hex').slice(0, 16); + const name = (0,node_path__rspack_import_3.basename)(canonicalRoot); + return safePluginSegment.test(name) ? `${name}-${digest}` : `plugin-${digest}`; +}; +const userStateHome = (env = process.env, home = (0,node_os__rspack_import_2.homedir)())=>{ + const xdgStateHome = env.XDG_STATE_HOME ?? ''; + return (0,node_path__rspack_import_3.isAbsolute)(xdgStateHome) ? (0,node_path__rspack_import_3.join)(xdgStateHome, 'agent-bundle') : (0,node_path__rspack_import_3.join)(home, '.agent-bundle', PLUGIN_STATE_DIRECTORY); +}; +const userDataStateRoot = (root, env, home)=>(0,node_path__rspack_import_3.join)(userStateHome(env, home), pluginStateSegment(root)); +const resolvePluginRoot = (options)=>{ + const env = options.env ?? process.env; + const declared = env[PLUGIN_ROOT_ENV_ANCHOR] ?? ''; + let root; + let source; + if ('' === declared.trim()) { + root = (0,node_path__rspack_import_3.resolve)(options.fallback); + source = 'derived'; + } else if (unexpandedToken.test(declared)) { + (options.warn ?? defaultWarn)(`[agent-bundle] ${PLUGIN_ROOT_ENV_ANCHOR} is the unexpanded token ${JSON.stringify(declared)}; anchoring the plugin on ${(0,node_path__rspack_import_3.resolve)(options.fallback)} instead.`); + root = (0,node_path__rspack_import_3.resolve)(options.fallback); + source = 'derived'; + } else { + root = (0,node_path__rspack_import_3.resolve)(declared); + source = 'native'; + } + const derivedStateRoot = 'user-data' === options.stateAnchor ? userDataStateRoot(root, env, options.home) : (0,node_path__rspack_import_3.join)(root, PLUGIN_STATE_DIRECTORY); + const declaredStateRoot = env[PLUGIN_STATE_ROOT_ENV_ANCHOR] ?? ''; + let stateRoot; + let stateSource; + if ('' === declaredStateRoot.trim()) { + stateRoot = derivedStateRoot; + stateSource = 'derived'; + } else if (unexpandedToken.test(declaredStateRoot)) { + (options.warn ?? defaultWarn)(`[agent-bundle] ${PLUGIN_STATE_ROOT_ENV_ANCHOR} is the unexpanded token ${JSON.stringify(declaredStateRoot)}; anchoring state on ${derivedStateRoot} instead.`); + stateRoot = derivedStateRoot; + stateSource = 'derived'; + } else { + stateRoot = (0,node_path__rspack_import_3.resolve)(declaredStateRoot); + stateSource = 'native'; + } + return Object.freeze({ + identity: (0,_736_js__rspack_import_4/* .available */.qC)({ + root, + stateRoot + }, source), + root, + source, + stateRoot, + stateSource + }); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + E7: resolvePluginRoot +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/506.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var react__rspack_import_0 = __webpack_require__("./node_modules/react/index.js"); + +const AgentResult = ({ children, metadata, value })=>(0,react__rspack_import_0.createElement)('agent-result', { + metadata, + value + }, children); +const AgentMarkdown = ({ children })=>(0,react__rspack_import_0.createElement)('agent-markdown', null, children); +const AgentText = ({ children })=>(0,react__rspack_import_0.createElement)('agent-text', null, children); +const AgentContext = ({ children })=>(0,react__rspack_import_0.createElement)('agent-context', null, children); +const AgentJson = ({ value })=>(0,react__rspack_import_0.createElement)('agent-json', { + value + }); +const AgentProgress = ({ completed, message, total })=>(0,react__rspack_import_0.createElement)('agent-progress', { + completed, + message, + total + }); +const AgentImage = ({ data, mimeType })=>(0,react__rspack_import_0.createElement)('agent-image', { + data, + mimeType + }); +const AgentAudio = ({ data, mimeType })=>(0,react__rspack_import_0.createElement)('agent-audio', { + data, + mimeType + }); +const AgentResource = ({ mimeType, name, uri })=>(0,react__rspack_import_0.createElement)('agent-resource', { + mimeType, + name, + uri + }); +const AgentError = ({ children, code })=>(0,react__rspack_import_0.createElement)('agent-error', { + code + }, children); +const Agent = Object.freeze({ + Audio: AgentAudio, + Context: AgentContext, + Error: AgentError, + Image: AgentImage, + Json: AgentJson, + Markdown: AgentMarkdown, + Progress: AgentProgress, + Resource: AgentResource, + Result: AgentResult, + Text: AgentText +}); +const Result = ({ children })=>(0,react__rspack_import_0.createElement)('agent-hook-result', null, children); +const AdditionalContext = ({ children })=>(0,react__rspack_import_0.createElement)('agent-hook-additional-context', null, children); +const Hook = { + AdditionalContext: AdditionalContext, + Result: Result +}; +const McpResult = ({ _meta, children, isError, structuredContent })=>createElement('mcp-result', { + _meta, + isError, + structuredContent + }, children); +const McpText = ({ children })=>createElement('mcp-text', null, children); +const McpImage = ({ data, mimeType })=>createElement('mcp-image', { + data, + mimeType + }); +const McpAudio = ({ data, mimeType })=>createElement('mcp-audio', { + data, + mimeType + }); +const McpResourceLink = ({ mimeType, name, uri })=>createElement('mcp-resource-link', { + mimeType, + name, + uri + }); +const McpEmbeddedResource = ({ blob, children, mimeType, text, uri })=>createElement('mcp-embedded-resource', { + blob, + mimeType, + text, + uri + }, children); +const Mcp = (/* unused pure expression or super */ null && ({ + Audio: McpAudio, + EmbeddedResource: McpEmbeddedResource, + Image: McpImage, + ResourceLink: McpResourceLink, + Result: McpResult, + Text: McpText +})); + + +__webpack_require__.d(__webpack_exports__, { +}, { + g6: Agent, + qn: Hook +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/707.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +const EMPTY_FLIGHT_MANIFEST = Object.freeze({ + clientManifest: Object.freeze({}), + moduleLoading: null, + serverConsumerModuleMap: null, + serverManifest: Object.freeze({}) +}); +const ensureAgentFlightManifest = ()=>{ + const scope = globalThis; + if (void 0 !== scope.__rspack_rsc_manifest__) return; + scope.__rspack_rsc_manifest__ = EMPTY_FLIGHT_MANIFEST; +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + n: ensureAgentFlightManifest +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/736.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_async_hooks__rspack_import_0 = __webpack_require__("node:async_hooks"); + +const AGENT_REQUEST_STORE_VERSION = 6; +const STORE_SYMBOL = Symbol.for('@agent-bundle/runtime/request-store'); +class AgentRequestError extends Error { + code; + constructor(code, message){ + super(message); + this.code = code; + this.name = 'AgentRequestError'; + } +} +const freezeValue = (value)=>{ + if (Array.isArray(value)) return Object.freeze(value.map((item)=>freezeValue(item))); + if (null !== value && 'object' == typeof value && Object.getPrototypeOf(value) === Object.prototype) { + const copy = {}; + for (const [key, nested] of Object.entries(value))copy[key] = freezeValue(nested); + return Object.freeze(copy); + } + return value; +}; +const available = (value, source)=>Object.freeze({ + source, + state: 'available', + value: freezeValue(value) + }); +const unavailable = (reason = 'not-provided')=>Object.freeze({ + reason, + state: 'unavailable' + }); +const snapshotObserved = (observed)=>'available' === observed.state ? available(observed.value, observed.source) : unavailable(observed.reason); +const silentProgress = Object.freeze({ + report: async ()=>void 0 +}); +const emptyCapabilities = ()=>Object.freeze({ + command: unavailable(), + filesystem: unavailable(), + network: unavailable(), + projectRoot: unavailable() + }); +const snapshotCapabilities = (capabilities)=>Object.freeze({ + command: snapshotObserved(capabilities.command), + filesystem: snapshotObserved(capabilities.filesystem), + network: snapshotObserved(capabilities.network), + projectRoot: snapshotObserved(capabilities.projectRoot) + }); +const optionalText = (value)=>{ + if (void 0 === value) return; + if ('' === value.trim()) throw new AgentRequestError('invalid-invocation', 'Agent invocation fields must be non-empty when present'); + return value; +}; +const invocationFrom = (input)=>Object.freeze({ + id: optionalText(input.id) ?? crypto.randomUUID(), + kind: input.kind, + startedAt: optionalText(input.startedAt) ?? new Date().toISOString(), + ...void 0 === input.artifactEpoch ? {} : { + artifactEpoch: optionalText(input.artifactEpoch) + }, + ...void 0 === input.hostContractRevision ? {} : { + hostContractRevision: optionalText(input.hostContractRevision) + }, + ...void 0 === input.operationId ? {} : { + operationId: optionalText(input.operationId) + }, + ...void 0 === input.protocolRevision ? {} : { + protocolRevision: optionalText(input.protocolRevision) + }, + ...void 0 === input.sourceRevision ? {} : { + sourceRevision: optionalText(input.sourceRevision) + }, + ...void 0 === input.surface ? {} : { + surface: optionalText(input.surface) + } + }); +class Lease { + values; + closed = false; + handle; + constructor(values){ + this.values = values; + this.handle = createHandle(this); + } +} +const realm = globalThis; +const getStore = ()=>{ + const existing = realm[STORE_SYMBOL]; + if (void 0 !== existing) { + if (existing.version !== AGENT_REQUEST_STORE_VERSION) throw new AgentRequestError('store-version-conflict', `Incompatible @agent-bundle/runtime request store version: found ${String(existing.version)}, expected ${String(AGENT_REQUEST_STORE_VERSION)}`); + return existing; + } + const created = { + storage: new node_async_hooks__rspack_import_0.AsyncLocalStorage(), + version: AGENT_REQUEST_STORE_VERSION + }; + realm[STORE_SYMBOL] = created; + return created; +}; +const agent_request_open = (lease)=>{ + if (lease.closed) throw new AgentRequestError('request-closed', 'agent() used after the request completed'); + return lease.values; +}; +const createHandle = (lease)=>Object.freeze({ + get invocation () { + return agent_request_open(lease).invocation; + }, + get host () { + return agent_request_open(lease).host; + }, + get session () { + return agent_request_open(lease).session; + }, + get actor () { + return agent_request_open(lease).actor; + }, + get workspace () { + return agent_request_open(lease).workspace; + }, + get plugin () { + return agent_request_open(lease).plugin; + }, + get lineage () { + return agent_request_open(lease).lineage; + }, + get terminal () { + return agent_request_open(lease).terminal; + }, + get capabilities () { + return agent_request_open(lease).capabilities; + }, + get progress () { + return agent_request_open(lease).progress; + }, + get signal () { + return agent_request_open(lease).signal; + }, + get services () { + return agent_request_open(lease).services; + }, + get process () { + return agent_request_open(lease).process; + }, + async provider (key) { + const values = agent_request_open(lease); + values.signal.throwIfAborted(); + const value = await values.provider(key); + agent_request_open(lease).signal.throwIfAborted(); + return value; + }, + get state () { + return agent_request_open(lease).state; + }, + get notices () { + return agent_request_open(lease).notices; + } + }); +const currentLease = ()=>{ + const lease = getStore().storage.getStore(); + if (void 0 === lease) throw new AgentRequestError('outside-invocation', 'agent() used outside a real invocation'); + return lease; +}; +const currentAgentRequest = ()=>{ + const lease = getStore().storage.getStore(); + return void 0 === lease || lease.closed ? void 0 : lease.handle; +}; +const agent = async ()=>{ + const lease = currentLease(); + agent_request_open(lease); + return lease.handle; +}; +const useAgent = ()=>{ + const lease = currentLease(); + agent_request_open(lease); + return lease.handle; +}; +const runAgentRequest = async (init, operation)=>{ + const actor = snapshotObserved(init.actor ?? unavailable()); + const host = snapshotObserved(init.host ?? unavailable()); + const invocation = invocationFrom(init.invocation); + const lineage = snapshotObserved(init.lineage ?? unavailable()); + const plugin = snapshotObserved(init.plugin ?? unavailable()); + const session = snapshotObserved(init.session ?? unavailable()); + const signal = init.signal ?? new AbortController().signal; + const terminal = snapshotObserved(init.terminal ?? unavailable()); + const workspace = snapshotObserved(init.workspace ?? unavailable()); + const noticeLease = void 0 === init.noticeLedger ? void 0 : await init.noticeLedger.openRequest({ + invocation, + principal: Object.freeze({ + actor, + host, + lineage, + session, + workspace + }), + signal + }); + try { + const providers = 'function' == typeof init.providers ? await resolveProvidersDetached(init.providers, providerRequest({ + host, + lineage, + notices: noticeLease?.handle, + plugin, + session, + signal, + state: init.state, + workspace + })) : init.providers; + const providerPromises = new Map(); + const request = providerRequest({ + host, + lineage, + notices: noticeLease?.handle, + plugin, + session, + signal, + state: init.state, + workspace + }); + const values = Object.freeze({ + provider: (key)=>{ + let pending = providerPromises.get(key); + if (void 0 === pending) { + pending = getStore().storage.exit(async ()=>{ + if (void 0 !== providers && Object.hasOwn(providers, key)) return providers[key]; + if (void 0 === init.resolveProvider) throw new TypeError(`Unknown provider ${JSON.stringify(key)}.`); + return init.resolveProvider(key, request); + }); + providerPromises.set(key, pending); + } + return pending; + }, + actor, + capabilities: snapshotCapabilities(init.capabilities ?? emptyCapabilities()), + host, + invocation, + lineage, + notices: noticeLease?.handle, + plugin, + progress: init.progress ?? silentProgress, + process: void 0 === init.process ? void 0 : Object.freeze({ + ...init.process + }), + services: Object.freeze({ + ...init.services ?? {} + }), + session, + signal, + state: init.state, + terminal, + workspace + }); + const lease = new Lease(values); + try { + return await getStore().storage.run(lease, operation); + } finally{ + lease.closed = true; + } + } finally{ + noticeLease?.close(); + } +}; +const resolveProvidersDetached = (resolver, request)=>getStore().storage.exit(async ()=>resolver(request)); +const providerRequest = ({ notices, state, ...axes })=>Object.freeze({ + ...axes, + ...void 0 === notices ? {} : { + notices: Object.freeze({ + inbox: ()=>notices.inbox(), + published: ()=>notices.published() + }) + }, + ...void 0 === state ? {} : { + state: Object.freeze({ + lifetime: state.lifetime, + read: (options)=>state.read(options) + }) + } + }); + + +__webpack_require__.d(__webpack_exports__, { + r8: () => (AgentRequestError) +}, { + MA: agent, + hU: unavailable, + iC: runAgentRequest, + qC: available +}); + + +}, +"./node_modules/@agent-bundle/runtime/dist/index.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var effect__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Latch.js"); +/* import */ var effect__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var effect__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var effect__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/Stream.js"); +/* import */ var effect__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Deferred.js"); +/* import */ var effect__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Queue.js"); +/* import */ var effect__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var effect__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var effect__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Clock.js"); +/* import */ var react__rspack_import_0 = __webpack_require__("./node_modules/react/index.js"); +/* import */ var react_server_dom_rspack_client_node__rspack_import_1 = __webpack_require__("./node_modules/react-server-dom-rspack/client.node.js"); +/* import */ var node_async_hooks__rspack_import_2 = __webpack_require__("node:async_hooks"); +/* import */ var _315_js__rspack_import_5 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/315.js"); +/* import */ var _302_js__rspack_import_6 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/302.js"); +/* import */ var _707_js__rspack_import_13 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/707.js"); +/* import */ var _506_js__rspack_import_15 = __webpack_require__("./node_modules/@agent-bundle/runtime/dist/506.js"); + + + + + + + + + + +const createFlightDemand = ()=>{ + const pulling = effect__rspack_import_3/* .makeUnsafe */.LZ(false); + let shellEmitted = false; + return { + markShell: effect__rspack_import_4/* .sync */.OH5(()=>{ + shellEmitted = true; + }), + notePull () { + pulling.openUnsafe(); + }, + notePullEnd () { + pulling.closeUnsafe(); + }, + wait: effect__rspack_import_4/* .suspend */.DYE(()=>shellEmitted ? pulling.await : effect__rspack_import_4/* ["void"] */.rIH) + }; +}; +const emitBoundRenderEvent = (sequence, input)=>effect__rspack_import_4/* ["try"] */.SvU({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>sequence.emit(input) + }); +const agentElementTypes = Object.freeze([ + 'agent-result', + 'agent-markdown', + 'agent-text', + 'agent-context', + 'agent-json', + 'agent-progress', + 'agent-image', + 'agent-audio', + 'agent-resource', + 'agent-error' +]); +const isAgentElementType = (value)=>agentElementTypes.includes(value); +const protocolElement = (node)=>{ + if (!(0,react__rspack_import_0.isValidElement)(node) || 'string' != typeof node.type || !isAgentElementType(node.type)) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'Flight output must contain only Agent protocol elements; function components and HTML are unsupported'); + return { + props: node.props, + type: node.type + }; +}; +const textChild = (children, type)=>{ + const values = react__rspack_import_0.Children.toArray(children); + if (1 !== values.length || 'string' != typeof values[0]) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', `${type} requires exactly one string child`); + return values[0]; +}; +const decodeBudget = (state)=>({ + addBytes (n) { + state.bytes += n; + if (state.bytes > state.limits.maxDocumentBytes) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('document-bytes-exceeded', `Agent Document bytes exceed ${String(state.limits.maxDocumentBytes)}`); + }, + addNode () { + (0,_302_js__rspack_import_6/* .admitDocumentNode */.Dy)(state); + }, + checkDepth (depth) { + (0,_302_js__rspack_import_6/* .expectDocumentDepth */.MI)(depth, state.limits); + } + }); +const isJsonObject = (value)=>null != value && 'object' == typeof value && !Array.isArray(value); +const budgetedJson = (value, message, depth, state)=>{ + try { + return (0,_302_js__rspack_import_6/* .snapshotJsonValue */.mY)(value, message, { + depth, + limits: decodeBudget(state) + }); + } catch (error) { + if (error instanceof _302_js__rspack_import_6/* .AgentContractError */.I2) throw error; + throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', error instanceof Error ? error.message : message, { + cause: error + }); + } +}; +const jsonMetadata = (value, depth, state)=>void 0 === value ? void 0 : budgetedJson(value, 'Agent result metadata must be JSON-serializable', depth, state); +const adoptedValue = (declared, state)=>declared.charged ? declared : { + charged: true, + depth: declared.depth, + value: budgetedJson(declared.value, 'Agent Document value must be JSON-serializable', declared.depth, state) + }; +const mergedMetadata = (outer, nested)=>{ + if (void 0 === outer) return nested; + if (void 0 === nested) return outer; + return isJsonObject(outer) && isJsonObject(nested) ? { + ...nested, + ...outer + } : outer; +}; +const jsonBytes = (value)=>Buffer.byteLength(JSON.stringify(value), 'utf8'); +const decodeResult = (props, depth, state)=>{ + const decoded = react__rspack_import_0.Children.toArray(props.children).map((child)=>decodeNode(child, depth + 1, state)); + const ownValue = props.value; + const ownMetadata = jsonMetadata(props.metadata, depth, state); + const mergeIndex = void 0 === ownValue ? decoded.findIndex((child)=>'result' === child.kind && state.resultValues.has(child)) : -1; + const merged = -1 === mergeIndex ? void 0 : decoded[mergeIndex]; + const children = void 0 === merged ? decoded : [ + ...decoded.slice(0, mergeIndex), + ...merged.children, + ...decoded.slice(mergeIndex + 1) + ]; + const metadata = void 0 === merged ? ownMetadata : mergedMetadata(ownMetadata, merged.metadata); + const node = { + children, + kind: 'result', + ...void 0 === metadata ? {} : { + metadata + } + }; + if (void 0 === merged) { + if (void 0 !== ownValue) state.resultValues.set(node, { + charged: false, + depth, + value: ownValue + }); + return node; + } + const authored = { + children: decoded, + kind: 'result', + ...void 0 === ownMetadata ? {} : { + metadata: ownMetadata + } + }; + state.discardedBytes += jsonBytes(authored) - jsonBytes(node); + state.resultValues.set(node, adoptedValue(state.resultValues.get(merged), state)); + return node; +}; +const decodeNode = (node, depth, state)=>{ + (0,_302_js__rspack_import_6/* .expectDocumentDepth */.MI)(depth, state.limits); + (0,_302_js__rspack_import_6/* .admitDocumentNode */.Dy)(state); + const element = protocolElement(node); + const { props } = element; + switch(element.type){ + case 'agent-result': + return decodeResult(props, depth, state); + case 'agent-markdown': + return { + kind: 'markdown', + text: textChild(props.children, element.type) + }; + case 'agent-text': + return { + kind: 'text', + text: textChild(props.children, element.type) + }; + case 'agent-context': + return { + kind: 'context', + text: textChild(props.children, element.type) + }; + case 'agent-json': + return { + kind: 'json', + value: budgetedJson(props.value, 'Agent JSON node value must be JSON-serializable', depth, state) + }; + case 'agent-progress': + return { + completed: props.completed, + kind: 'progress', + ...void 0 === props.message ? {} : { + message: props.message + }, + ...void 0 === props.total ? {} : { + total: props.total + } + }; + case 'agent-image': + return { + data: props.data, + kind: 'image', + mimeType: props.mimeType + }; + case 'agent-audio': + return { + data: props.data, + kind: 'audio', + mimeType: props.mimeType + }; + case 'agent-resource': + return { + kind: 'resource', + ...void 0 === props.mimeType ? {} : { + mimeType: props.mimeType + }, + name: props.name, + uri: props.uri + }; + case 'agent-error': + state.representedError = true; + return { + code: props.code, + kind: 'error', + message: textChild(props.children, element.type) + }; + default: + { + const exhaustive = element.type; + throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', `Unsupported Agent protocol element: ${String(exhaustive)}`); + } + } +}; +const decodeAgentDocument = (node, limits = {})=>{ + const resolved = (0,_302_js__rspack_import_6/* .resolveAgentRenderLimits */.i0)(limits); + const root = protocolElement(node); + if ('agent-result' !== root.type) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'Flight output must have Agent.Result as its root'); + const state = { + bytes: 0, + discardedBytes: 0, + limits: resolved, + nodes: 0, + representedError: false, + resultValues: new WeakMap() + }; + const documentRoot = decodeNode(node, 1, state); + const value = state.resultValues.get(documentRoot)?.value; + const document = (0,_302_js__rspack_import_6/* .createAgentDocument */.ZX)({ + root: documentRoot, + status: state.representedError ? 'represented-error' : 'success', + ...void 0 === value ? {} : { + value + }, + version: 1 + }, resolved); + if (state.discardedBytes > 0 && state.discardedBytes + jsonBytes(document) > resolved.maxDocumentBytes) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('document-bytes-exceeded', `Agent Document bytes exceed ${String(resolved.maxDocumentBytes)}`); + return document; +}; +const REACT_FRAGMENT = Symbol.for('react.fragment'); +const REACT_LAZY = Symbol.for('react.lazy'); +const REACT_SUSPENSE = Symbol.for('react.suspense'); +const abortError = _302_js__rspack_import_6/* .agentRenderAbortError */.k2; +const isObject = (value)=>'object' == typeof value && null !== value; +const isThenable = (value)=>isObject(value) && 'function' == typeof value.then; +const isLazyElement = (value)=>isObject(value) && value.$$typeof === REACT_LAZY && isThenable(value._payload); +const childList = (children)=>{ + if (null == children || false === children || true === children) return []; + return Array.isArray(children) ? children : [ + children + ]; +}; +const joinPath = (parent, index)=>'' === parent ? String(index) : `${parent}.${index}`; +const classifyNode = (node)=>{ + if (null == node || 'boolean' == typeof node) return { + kind: 'empty' + }; + if ('string' == typeof node || 'number' == typeof node) return { + kind: 'leaf', + value: node + }; + if (Array.isArray(node)) return { + kind: 'array', + value: node + }; + if (isLazyElement(node)) return { + kind: 'lazy', + value: node + }; + if (isThenable(node)) return { + kind: 'thenable', + value: node + }; + if (!(0,react__rspack_import_0.isValidElement)(node)) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'Flight output contained an unsupported node'); + const type = node.type; + if (type === REACT_SUSPENSE) return { + kind: 'suspense', + value: node + }; + if (type === REACT_FRAGMENT) return { + kind: 'fragment', + value: node + }; + if ('string' == typeof type) return { + kind: 'protocol', + value: node + }; + throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', "Flight output must contain only Agent protocol elements; function components and HTML are unsupported"); +}; +const thenableStatus = (thenable)=>{ + switch(thenable.status){ + case 'fulfilled': + case 'resolved_model': + return 'fulfilled'; + case 'rejected': + return 'rejected'; + case 'pending': + case 'halted': + case void 0: + return 'pending'; + default: + return 'pending'; + } +}; +const unwrapLazy = (lazy)=>{ + if (void 0 !== lazy._init) return lazy._init(lazy._payload); + return lazy._payload.value; +}; +const renderErrorFrom = (reason)=>{ + if (reason instanceof Error) return Object.freeze({ + code: 'boundary', + message: reason.message + }); + if (isObject(reason) && 'string' == typeof reason.message && '' !== reason.message.trim()) return Object.freeze({ + code: 'string' == typeof reason.digest && '' !== reason.digest.trim() ? reason.digest : 'boundary', + message: reason.message + }); + return Object.freeze({ + code: 'boundary', + message: 'Suspended boundary failed' + }); +}; +const boundaryId = (path, ids)=>{ + const existing = ids.get(path); + if (void 0 !== existing) return existing; + const id = `b:${path}`; + ids.set(path, id); + return id; +}; +const errorElement = (error)=>(0,react__rspack_import_0.createElement)('agent-error', { + code: error.code + }, error.message); +const materializePending = (thenable, path, fallback, ctx)=>{ + const status = thenableStatus(thenable); + switch(status){ + case 'pending': + { + const id = boundaryId(path, ctx.ids); + ctx.pending.push({ + id, + thenable + }); + return materializeNode(fallback, `${path}~fallback`, ctx); + } + case 'rejected': + { + const id = boundaryId(path, ctx.ids); + const error = renderErrorFrom(thenable.reason); + ctx.rejected.push({ + error, + id + }); + return errorElement(error); + } + case 'fulfilled': + return materializeNode(thenable.value, path, ctx); + default: + { + const exhaustive = status; + return exhaustive; + } + } +}; +const materializeNode = (node, path, ctx)=>{ + const classified = classifyNode(node); + switch(classified.kind){ + case 'empty': + return null; + case 'leaf': + return classified.value; + case 'array': + return classified.value.map((child, index)=>materializeNode(child, joinPath(path, index), ctx)); + case 'thenable': + return materializePending(classified.value, path, null, ctx); + case 'lazy': + { + const status = thenableStatus(classified.value._payload); + switch(status){ + case 'pending': + case 'rejected': + return materializePending(classified.value._payload, path, null, ctx); + case 'fulfilled': + return materializeNode(unwrapLazy(classified.value), path, ctx); + default: + { + const exhaustive = status; + return exhaustive; + } + } + } + case 'suspense': + { + const props = classified.value.props; + const children = props.children; + const fallback = props.fallback; + const childKind = classifyNode(children); + switch(childKind.kind){ + case 'lazy': + { + const status = thenableStatus(childKind.value._payload); + switch(status){ + case 'pending': + case 'rejected': + return materializePending(childKind.value._payload, path, fallback, ctx); + case 'fulfilled': + return materializeNode(unwrapLazy(childKind.value), path, ctx); + default: + { + const exhaustive = status; + return exhaustive; + } + } + } + case 'thenable': + return materializePending(childKind.value, path, fallback, ctx); + case 'empty': + case 'leaf': + case 'array': + case 'suspense': + case 'fragment': + case 'protocol': + return materializeNode(children, path, ctx); + default: + { + const exhaustive = childKind; + return exhaustive; + } + } + } + case 'fragment': + return materializeNode(classified.value.props.children, path, ctx); + case 'protocol': + { + const props = classified.value.props; + const { children, ...rest } = props; + const materialized = []; + for (const [index, child] of childList(children).entries()){ + const next = materializeNode(child, joinPath(path, index), ctx); + if (Array.isArray(next)) materialized.push(...next); + else materialized.push(next); + } + return (0,react__rspack_import_0.createElement)(classified.value.type, rest, ...materialized); + } + default: + { + const exhaustive = classified; + return exhaustive; + } + } +}; +const snapshotTree = (root, ids)=>{ + const ctx = { + ids, + pending: [], + rejected: [] + }; + return { + pending: ctx.pending, + rejected: ctx.rejected, + tree: materializeNode(root, '', ctx) + }; +}; +const hostError = (signal, error)=>signal.aborted || (0,_315_js__rspack_import_5/* .isAbortError */.zf)(error) ? abortError() : (0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error); +const waitSettledBoundary = (pending)=>effect__rspack_import_4/* .raceAll */.Vdx(pending.map((boundary)=>effect__rspack_import_4/* .promise */.ivC(()=>Promise.resolve(boundary.thenable).then(()=>({ + boundary, + ok: true + }), (error)=>({ + boundary, + error, + ok: false + }))))); +const waitOrDeadline = (wait, sequence)=>{ + const remaining = sequence.remainingMs; + if (remaining <= 0) return effect__rspack_import_4/* .fail */.fJG((0,_302_js__rspack_import_6/* .elapsedTimeExceeded */.zm)(sequence.maxElapsedMs)); + return effect__rspack_import_4/* .raceFirst */.KT6(wait, effect__rspack_import_4/* .sleep */.yy4(effect__rspack_import_7/* .millis */.ne(remaining)).pipe(effect__rspack_import_4/* .flatMap */.qIB(()=>effect__rspack_import_4/* .fail */.fJG((0,_302_js__rspack_import_6/* .elapsedTimeExceeded */.zm)(sequence.maxElapsedMs))))); +}; +const settledBoundaryInputs = (previous, next, winner, limits)=>{ + const stillPending = new Set(next.pending.map((boundary)=>boundary.id)); + const rejectedById = new Map(next.rejected.map((entry)=>[ + entry.id, + entry.error + ])); + const document = decodeAgentDocument(next.tree, limits); + const inputs = []; + const emitFor = (id, fallback)=>{ + const rejected = rejectedById.get(id); + if (void 0 !== rejected) return void inputs.push({ + boundaryId: id, + error: rejected, + type: 'error' + }); + if (void 0 !== fallback && !fallback.ok) return void inputs.push({ + boundaryId: id, + error: renderErrorFrom(fallback.error), + type: 'error' + }); + if (stillPending.has(id) && id !== winner.boundary.id) return; + inputs.push({ + boundaryId: id, + document, + type: 'replace' + }); + }; + emitFor(winner.boundary.id, winner); + for (const boundary of previous.pending)if (boundary.id !== winner.boundary.id) emitFor(boundary.id); + return inputs; +}; +const reconcileLoopStream = (root, ids, initial, limits, flightDone, progressInputs, sequence)=>effect__rspack_import_8/* .paginate */.EnV(initial, (snapshot)=>{ + if (0 === snapshot.pending.length) return waitOrDeadline(effect__rspack_import_9/* ["await"] */.Tx(flightDone), sequence).pipe(effect__rspack_import_4/* .andThen */.hgn(effect__rspack_import_10/* .clear */.IU(progressInputs)), effect__rspack_import_4/* .flatMap */.qIB((queued)=>effect__rspack_import_4/* ["try"] */.SvU({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>[ + [ + ...queued, + { + document: decodeAgentDocument(snapshot.tree, limits), + type: 'complete' + } + ], + effect__rspack_import_11.none() + ] + }))); + return effect__rspack_import_4/* .raceFirst */.KT6(waitOrDeadline(waitSettledBoundary(snapshot.pending), sequence).pipe(effect__rspack_import_4/* .map */.TjK((winner)=>({ + kind: 'boundary', + winner + }))), effect__rspack_import_10/* .take */.s(progressInputs).pipe(effect__rspack_import_4/* .map */.TjK((input)=>({ + kind: 'progress', + input + })))).pipe(effect__rspack_import_4/* .flatMap */.qIB((event)=>{ + switch(event.kind){ + case 'progress': + return effect__rspack_import_4/* .succeed */.PyW([ + [ + event.input + ], + effect__rspack_import_11.some(snapshot) + ]); + case 'boundary': + return effect__rspack_import_4/* ["try"] */.SvU({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>{ + const next = snapshotTree(root, ids); + return [ + settledBoundaryInputs(snapshot, next, event.winner, limits), + effect__rspack_import_11.some(next) + ]; + } + }); + default: + { + const exhaustive = event; + return exhaustive; + } + } + })); + }); +const gatedFlightStream = (flight, demand, flightDone)=>effect__rspack_import_8/* .unwrap */.oAg(effect__rspack_import_4/* .gen */.JkU(function*() { + const reader = yield* effect__rspack_import_4/* .acquireRelease */.Q56(effect__rspack_import_4/* .sync */.OH5(()=>flight.getReader()), (handle, exit)=>effect__rspack_import_4/* .gen */.JkU(function*() { + const cancelExit = yield* effect__rspack_import_4/* .exit */.NS5(effect__rspack_import_4/* .tryPromise */.$mh({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>handle.cancel() + })); + if (effect__rspack_import_12/* .isFailure */.N6(exit)) return void (yield* effect__rspack_import_9/* .fail */.fJ(flightDone, (0,_315_js__rspack_import_5/* .mapCause */.K0)(exit.cause))); + if (effect__rspack_import_12/* .isFailure */.N6(cancelExit)) { + const error = (0,_315_js__rspack_import_5/* .mapCause */.K0)(cancelExit.cause); + yield* effect__rspack_import_9/* .fail */.fJ(flightDone, error); + return yield* effect__rspack_import_4/* .die */.F_Q(error); + } + yield* effect__rspack_import_9/* .succeed */.Py(flightDone, void 0); + })); + return effect__rspack_import_8/* .unfold */.t8s(void 0, ()=>demand.wait.pipe(effect__rspack_import_4/* .flatMap */.qIB(()=>effect__rspack_import_4/* .tryPromise */.$mh({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>reader.read() + })), effect__rspack_import_4/* .map */.TjK((next)=>next.done ? void 0 : [ + next.value, + void 0 + ]))); + })); +const decodeFlightRoot = (flight, demand, signal, flightDone)=>effect__rspack_import_4/* .gen */.JkU(function*() { + (0,_707_js__rspack_import_13/* .ensureAgentFlightManifest */.n)(); + const flightAbort = yield* _315_js__rspack_import_5/* .scopedAbortSignal */.lQ; + const readable = (0,_315_js__rspack_import_5/* .streamToReadableStream */._I)(gatedFlightStream(flight, demand, flightDone), { + signal: flightAbort, + strategy: { + highWaterMark: 1 + } + }); + return yield* effect__rspack_import_4/* .tryPromise */.$mh({ + catch: (error)=>hostError(signal, error), + try: ()=>(0,react_server_dom_rspack_client_node__rspack_import_1.createFromReadableStream)(readable, { + unstable_allowPartialStream: true + }) + }); + }); +const progressInput = (update)=>({ + completed: update.completed ?? 0, + ...void 0 === update.message ? {} : { + message: update.message + }, + ...void 0 === update.total ? {} : { + total: update.total + }, + type: 'progress' + }); +const handoffRequired = ()=>new _302_js__rspack_import_6/* .AgentContractError */.I2('handoff-required', 'The render is complete; later work requires a new invocation handoff'); +const createAgentRenderEventSession = (options)=>{ + const clock = options.clock; + const sequence = (0,_302_js__rspack_import_6/* .createAgentRenderEventSequence */.n4)(options.limits, void 0 === clock ? void 0 : ()=>clock.currentTimeMillisUnsafe()); + const maxBufferedProgress = (0,_302_js__rspack_import_6/* .resolveAgentRenderLimits */.i0)(options.limits).maxEvents; + let offerProgress; + let progressFailure; + const bufferedProgress = []; + const progress = Object.freeze({ + report: async (update)=>{ + if (void 0 !== progressFailure) throw progressFailure; + if (sequence.completed) throw handoffRequired(); + const input = progressInput(update); + if (void 0 === offerProgress) { + if (bufferedProgress.length >= maxBufferedProgress) throw new _302_js__rspack_import_6/* .AgentContractError */.I2('event-count-exceeded', `Agent render event count exceeds ${String(maxBufferedProgress)}`); + bufferedProgress.push(input); + return; + } + await (0,_315_js__rspack_import_5/* .runPromise */.pR)(offerProgress(input)); + } + }); + const events = effect__rspack_import_8/* .unwrap */.oAg(effect__rspack_import_4/* .gen */.JkU(function*() { + const progressInputs = yield* effect__rspack_import_10/* .bounded */.Mm(0); + const flightDone = yield* effect__rspack_import_9/* .make */.L8(); + const bindProgress = ()=>{ + offerProgress = (input)=>effect__rspack_import_10/* .offer */.x(progressInputs, input).pipe(effect__rspack_import_4/* .flatMap */.qIB((accepted)=>{ + if (void 0 !== progressFailure) return effect__rspack_import_4/* .fail */.fJG(progressFailure); + if (!accepted) return effect__rspack_import_4/* .fail */.fJG(handoffRequired()); + return effect__rspack_import_4/* ["void"] */.rIH; + })); + }; + const finalizeProgress = (error)=>effect__rspack_import_4/* .sync */.OH5(()=>{ + progressFailure = error; + }).pipe(effect__rspack_import_4/* .andThen */.hgn(effect__rspack_import_10/* .shutdown */.n_(progressInputs))); + const setup = effect__rspack_import_4/* .gen */.JkU(function*() { + const flight = yield* effect__rspack_import_4/* .tryPromise */.$mh({ + catch: (error)=>hostError(options.signal, error), + try: ()=>options.flight + }); + if (options.signal.aborted) return yield* effect__rspack_import_4/* .fail */.fJG(abortError()); + const root = yield* decodeFlightRoot(flight, options.demand, options.signal, flightDone); + if (options.signal.aborted) return yield* effect__rspack_import_4/* .fail */.fJG(abortError()); + const prepared = yield* effect__rspack_import_4/* ["try"] */.SvU({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>{ + const ids = new Map(); + const initial = snapshotTree(root, ids); + return { + ids, + initial, + shellInput: { + document: decodeAgentDocument(initial.tree, options.limits), + type: 'shell' + } + }; + } + }); + bindProgress(); + return effect__rspack_import_8/* .concat */.xWs(effect__rspack_import_8/* .fromArray */.ciY([ + prepared.shellInput, + ...bufferedProgress + ]), reconcileLoopStream(root, prepared.ids, prepared.initial, options.limits, flightDone, progressInputs, sequence)).pipe(effect__rspack_import_8/* .mapEffect */.WK$((input)=>emitBoundRenderEvent(sequence, input)), effect__rspack_import_8/* .tap */.Mim((event)=>'shell' === event.type ? options.demand.markShell : effect__rspack_import_4/* ["void"] */.rIH), effect__rspack_import_8/* .takeUntil */.QKh((event)=>'complete' === event.type), effect__rspack_import_8/* .onExit */.cfM((exit)=>{ + if (effect__rspack_import_12/* .isSuccess */.oJ(exit)) return finalizeProgress(handoffRequired()); + const error = (0,_315_js__rspack_import_5/* .mapCause */.K0)(exit.cause); + return finalizeProgress(sequence.completed && (0,_315_js__rspack_import_5/* .isAbortError */.zf)(error) ? handoffRequired() : error); + })); + }); + return yield* setup.pipe(effect__rspack_import_4/* .onExit */.cfM((exit)=>effect__rspack_import_12/* .isFailure */.N6(exit) ? finalizeProgress((0,_315_js__rspack_import_5/* .mapCause */.K0)(exit.cause)) : effect__rspack_import_4/* ["void"] */.rIH)); + })); + return { + events: void 0 === clock ? events : effect__rspack_import_8/* .provideService */.PfK(events, effect__rspack_import_14/* .Clock */.zD, clock), + progress + }; +}; +const toPublicEventStream = (events, demand, signal)=>(0,_315_js__rspack_import_5/* .streamToReadableStream */._I)(effect__rspack_import_8/* .interruptWhen */.S67(events, (0,_315_js__rspack_import_5/* .abortToInterrupt */.p7)(signal)), { + closeOn: (event)=>'complete' === event.type, + onPull: demand.notePull, + onPullDelivered: demand.notePullEnd, + strategy: { + highWaterMark: 0 + } + }); +const decodeAgentFlightStream = (flight, options = {})=>{ + const signal = options.signal ?? new AbortController().signal; + const demand = createFlightDemand(); + return toPublicEventStream(createAgentRenderEventSession({ + demand, + flight: Promise.resolve(flight), + limits: options.limits, + signal + }).events, demand, signal); +}; +const dispatcher_abortError = _302_js__rspack_import_6/* .agentRenderAbortError */.k2; +const abortedStream = ()=>new ReadableStream({ + start (controller) { + controller.error(dispatcher_abortError()); + } + }); +const drainCompleteDocument = async (events, signal)=>{ + const reader = events.getReader(); + let complete; + try { + while(true){ + const next = await reader.read(); + if (next.done) break; + switch(next.value.type){ + case 'complete': + complete = next.value.document; + break; + case 'shell': + case 'progress': + case 'replace': + case 'error': + break; + default: + { + const exhaustive = next.value; + return exhaustive; + } + } + } + } catch (error) { + if (signal.aborted) throw dispatcher_abortError(); + throw error; + } + if (void 0 !== complete) return complete; + if (signal.aborted) throw dispatcher_abortError(); + throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'Flight stream ended without a complete document'); +}; +const createAgentRenderDispatcher = (host, options = {})=>{ + const stream = (request)=>{ + if (request.signal.aborted) return abortedStream(); + const demand = createFlightDemand(); + const pendingFlight = {}; + const session = createAgentRenderEventSession({ + demand, + get flight () { + const current = pendingFlight.current; + if (void 0 === current) return Promise.reject(new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'Flight worker is not running')); + return current; + }, + limits: { + ...options.limits, + ...request.limits + }, + signal: request.signal + }); + const rememberFlight = (flight)=>{ + flight.catch(()=>void 0); + return flight; + }; + try { + pendingFlight.current = rememberFlight(host.execute({ + ...void 0 === request.artifactEpoch ? {} : { + artifactEpoch: request.artifactEpoch + }, + invocation: request.invocation, + progress: session.progress, + signal: request.signal + })); + } catch (error) { + pendingFlight.current = rememberFlight(Promise.reject(request.signal.aborted ? dispatcher_abortError() : error)); + } + return toPublicEventStream(session.events, demand, request.signal); + }; + return Object.freeze({ + async dispatch (request) { + return drainCompleteDocument(stream(request), request.signal); + }, + stream + }); +}; +const MCP_PROGRESS_MESSAGE_MAX = 200; +const DEFAULT_MCP_RICH_CONTENT_CAPABILITIES = Object.freeze({ + audio: true, + image: true, + resource: true +}); +class McpProjectionError extends Error { + code; + kind; + constructor(code, message, options){ + super(message, options); + this.code = code; + this.name = 'McpProjectionError'; + this.kind = options?.kind; + } +} +const resolveCapabilities = (partial)=>Object.freeze({ + ...DEFAULT_MCP_RICH_CONTENT_CAPABILITIES, + ...partial + }); +const shortenMcpProgressMessage = (message)=>{ + const trimmed = message.trim(); + if (trimmed.length <= MCP_PROGRESS_MESSAGE_MAX) return trimmed; + return `${trimmed.slice(0, MCP_PROGRESS_MESSAGE_MAX - 1)}…`; +}; +const gatedBlock = (kind, summary, fallback)=>{ + switch(fallback){ + case 'text': + return { + text: summary, + type: 'text' + }; + case 'fail': + throw new McpProjectionError('unsupported-rich-content', `MCP projector cannot emit ${kind} content because the selected capability does not support it`, { + kind + }); + default: + { + const exhaustive = fallback; + return exhaustive; + } + } +}; +const appendNode = (node, content, capabilities, fallback)=>{ + switch(node.kind){ + case 'result': + for (const child of node.children)appendNode(child, content, capabilities, fallback); + break; + case 'context': + case 'markdown': + case 'text': + content.push({ + text: node.text, + type: 'text' + }); + break; + case 'json': + content.push({ + text: JSON.stringify(node.value), + type: 'text' + }); + break; + case 'progress': + break; + case 'image': + content.push(capabilities.image ? { + data: node.data, + mimeType: node.mimeType, + type: 'image' + } : gatedBlock('image', `[image ${node.mimeType}]`, fallback)); + break; + case 'audio': + content.push(capabilities.audio ? { + data: node.data, + mimeType: node.mimeType, + type: 'audio' + } : gatedBlock('audio', `[audio ${node.mimeType}]`, fallback)); + break; + case 'resource': + content.push(capabilities.resource ? { + ...void 0 === node.mimeType ? {} : { + mimeType: node.mimeType + }, + name: node.name, + type: 'resource_link', + uri: node.uri + } : gatedBlock('resource', `[resource ${node.name} ${node.uri}]`, fallback)); + break; + case 'error': + content.push({ + text: `[${node.code}] ${node.message}`, + type: 'text' + }); + break; + default: + { + const exhaustive = node; + throw new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', `Unsupported Agent Document node: ${String(exhaustive.kind)}`); + } + } +}; +const project_mcp_isJsonObject = (value)=>null !== value && 'object' == typeof value && !Array.isArray(value); +const objectStructuredContent = (value)=>{ + if (void 0 === value) return; + const snapshot = (0,_302_js__rspack_import_6/* .snapshotJsonValue */.mY)(value, 'MCP structured content must be JSON-serializable'); + return project_mcp_isJsonObject(snapshot) ? snapshot : void 0; +}; +const resultMetadata = (document)=>{ + if ('result' !== document.root.kind) return; + const metadata = document.root.metadata; + if (void 0 === metadata) return; + const snapshot = (0,_302_js__rspack_import_6/* .snapshotJsonValue */.mY)(metadata, 'MCP result _meta must be JSON-serializable'); + if (!project_mcp_isJsonObject(snapshot)) throw new McpProjectionError('invalid-result-metadata', 'MCP result _meta must be a JSON object; Agent.Result metadata projects to CallToolResult._meta'); + return snapshot; +}; +const documentToCallToolResult = (document, options = {})=>{ + const content = []; + appendNode(document.root, content, resolveCapabilities(options.capabilities), options.richContentFallback ?? 'fail'); + const structured = objectStructuredContent(options.structuredContent ?? document.value); + const metadata = resultMetadata(document); + return { + ...void 0 === metadata ? {} : { + _meta: metadata + }, + content, + ...'success' === document.status ? {} : { + isError: true + }, + ...void 0 === structured ? {} : { + structuredContent: structured + } + }; +}; +const attachMcpStructuredContent = (result, value)=>{ + const structured = objectStructuredContent(value); + if (void 0 === structured) return result; + return { + ...result, + structuredContent: structured + }; +}; +const notifyProgress = (source, token, sendProgress)=>effect__rspack_import_4/* .tryPromise */.$mh({ + catch: (error)=>(0,_315_js__rspack_import_5/* .toRuntimeError */.qN)(error), + try: ()=>sendProgress({ + progress: source.completed, + progressToken: token, + ...void 0 === source.message ? {} : { + message: shortenMcpProgressMessage(source.message) + }, + ...void 0 === source.total ? {} : { + total: source.total + } + }) + }); +const appendProgressNodes = (node, nodes)=>{ + switch(node.kind){ + case 'result': + for (const child of node.children)appendProgressNodes(child, nodes); + break; + case 'progress': + nodes.push(node); + break; + case 'audio': + case 'context': + case 'error': + case 'image': + case 'json': + case 'markdown': + case 'resource': + case 'text': + break; + default: + { + const exhaustive = node; + return exhaustive; + } + } +}; +const documentProgressNodes = (document)=>{ + const nodes = []; + appendProgressNodes(document.root, nodes); + return nodes; +}; +const projectMcpEventStream = effect__rspack_import_4/* .fnUntraced */.D9k(function*(events, options = {}) { + let lastProgress = -1 / 0; + let complete; + const token = options.progressToken; + const sendProgress = options.sendProgress; + const notify = (source)=>{ + if (void 0 === token || void 0 === sendProgress) return effect__rspack_import_4/* ["void"] */.rIH; + if (!(source.completed > lastProgress)) return effect__rspack_import_4/* ["void"] */.rIH; + lastProgress = source.completed; + return notifyProgress(source, token, sendProgress); + }; + yield* effect__rspack_import_8/* .runForEach */.o1d(events, (event)=>effect__rspack_import_4/* .gen */.JkU(function*() { + switch(event.type){ + case 'progress': + yield* notify(event); + return; + case 'shell': + case 'replace': + for (const node of documentProgressNodes(event.document))yield* notify(node); + return; + case 'error': + return; + case 'complete': + complete = event.document; + return; + default: + { + const exhaustive = event; + return exhaustive; + } + } + })); + if (void 0 === complete) return yield* effect__rspack_import_4/* .fail */.fJG(new _302_js__rspack_import_6/* .AgentContractError */.I2('invalid-document', 'MCP projector requires a complete document; the stream ended without one')); + return Object.freeze({ + document: complete, + result: documentToCallToolResult(complete, options) + }); +}); +const projectMcpRenderStream = async (events, options = {})=>{ + const program = projectMcpEventStream(Stream.fromReadableStream({ + evaluate: ()=>events, + onError: (error)=>toRuntimeError(error) + }), options); + return runPromise(void 0 === options.signal ? program : interruptWhenAborted(program, options.signal), void 0 === options.signal ? void 0 : { + signal: options.signal + }); +}; +class AgentRuntimeError extends Error { + code; + expectedEpoch; + receivedEpoch; + constructor(code, message, options){ + super(message, options); + this.code = code; + this.name = 'AgentRuntimeError'; + this.expectedEpoch = options?.expectedEpoch; + this.receivedEpoch = options?.receivedEpoch; + } +} +const assertArtifactEpoch = (expected, received)=>{ + if (void 0 === received || received === expected) return; + throw new AgentRuntimeError('artifact-epoch-mismatch', `Runtime artifact epoch ${JSON.stringify(expected)} does not match request epoch ${JSON.stringify(received)}`, { + expectedEpoch: expected, + receivedEpoch: received + }); +}; +const unavailableError = (code)=>{ + switch(code){ + case 'runtime-restarted': + return new AgentRuntimeError(code, 'The MCP render runtime restarted; this process no longer serves requests'); + case 'runtime-unavailable': + return new AgentRuntimeError(code, 'The MCP render runtime is unavailable'); + default: + { + const exhaustive = code; + return exhaustive; + } + } +}; +const createWarmFlightHost = (options)=>{ + const identity = Object.freeze({ + artifactEpoch: options.artifactEpoch, + instanceId: options.instanceId ?? crypto.randomUUID() + }); + let availability = 'available'; + let unavailable; + return Object.freeze({ + availability: ()=>availability, + identity, + markUnavailable (code = 'runtime-unavailable') { + if (void 0 === unavailable) { + availability = code; + unavailable = unavailableError(code); + } + }, + async close () { + try { + await options.close?.(); + } finally{ + await options.runtimeState?.close(); + } + }, + async execute (request) { + if (void 0 !== unavailable) throw unavailable; + assertArtifactEpoch(identity.artifactEpoch, request.artifactEpoch); + return options.host.execute(request); + } + }); +}; +const MarkdownContent = async ({ children, components })=>{ + const markdown = await renderToMarkdown(children, void 0 === components ? void 0 : { + components + }); + return createElement(Agent.Markdown, null, markdown.replace(/\n+$/u, '')); +}; +const hookComponents = new Set(Object.values(_506_js__rspack_import_15/* .Hook */.qn)); +const isHookComponent = (value)=>hookComponents.has(value); +const resolveHookElement = (node)=>{ + let element = node; + while(isValidElement(element) && isHookComponent(element.type))element = element.type(element.props); + return element; +}; +const isAgentElement = (node, name)=>{ + const resolved = resolveHookElement(node); + return isValidElement(resolved) && resolved.type === name; +}; +const flattenText = (node)=>{ + if ('string' == typeof node || 'number' == typeof node) return String(node); + if (Array.isArray(node)) return node.map(flattenText).join(''); + if (isAgentElement(node, 'agent-hook-result')) throw new Error('Hook result contains duplicate roots'); + throw new Error('Hook additional context may contain only string or number children'); +}; +const lowerHookResult = (node)=>{ + const roots = Children.toArray(node).map(resolveHookElement); + if (1 !== roots.length || !isAgentElement(roots[0], 'agent-hook-result')) throw new Error('Expected exactly one agent-hook-result root'); + const result = roots[0]; + const contexts = Children.toArray(result.props.children).map(resolveHookElement).map((child)=>{ + if (isAgentElement(child, 'agent-hook-result')) throw new Error('Hook result contains duplicate roots'); + if (!isAgentElement(child, 'agent-hook-additional-context')) throw new Error('Hook result may contain only agent-hook-additional-context elements'); + return flattenText(child.props.children); + }); + if (0 === contexts.length) throw new Error('Hook result requires additional context'); + return { + hookSpecificOutput: { + additionalContext: contexts.join(''), + hookEventName: 'PostToolUse' + } + }; +}; +const createRscRequestContext = (label)=>{ + const storage = new AsyncLocalStorage(); + return Object.freeze({ + run (value, operation) { + return storage.run(value, operation); + }, + use () { + const value = storage.getStore(); + if (void 0 === value) throw new Error(`${label} used outside a render request`); + return value; + } + }); +}; +var src_AGENT_DOCUMENT_VERSION = 1; +var src_AGENT_REQUEST_STORE_VERSION = 6; +var src_PLUGIN_STATE_DIRECTORY = "state"; + + + + + + + +__webpack_require__.d(__webpack_exports__, { +}, { + jK: createAgentRenderDispatcher +}); + + +}, +"./node_modules/agent-bundle/dist/667~1.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_crypto__rspack_import_0 = __webpack_require__("node:crypto"); +/* import */ var node_fs_promises__rspack_import_1 = __webpack_require__("node:fs/promises"); +/* import */ var _991_1_js__rspack_import_2 = __webpack_require__("./node_modules/agent-bundle/dist/991~1.js"); + + + +const sha256Hex = (bytes)=>createHash('sha256').update(bytes).digest('hex'); +const serializeJson = (value, key = '')=>{ + if (null !== value && 'object' == typeof value) { + const toJson = value.toJSON; + if ('function' == typeof toJson) return serializeJson(toJson.call(value, key), key); + if (value instanceof Boolean || value instanceof Number || value instanceof String) return JSON.stringify(value); + if (Array.isArray(value)) { + const items = Array.from({ + length: value.length + }, (_, index)=>serializeJson(value[index], String(index)) ?? 'null'); + return `[${items.join(',')}]`; + } + const object = value; + const keys = Object.keys(object); + const orderedKeys = (0,_991_1_js__rspack_import_2/* .isPlainRecord */.UQ)(object) ? keys.sort() : keys; + const entries = orderedKeys.flatMap((objectKey)=>{ + const serialized = serializeJson(object[objectKey], objectKey); + return void 0 === serialized ? [] : [ + `${JSON.stringify(objectKey)}:${serialized}` + ]; + }); + return `{${entries.join(',')}}`; + } + const serialized = JSON.stringify(value); + return 'string' == typeof serialized ? serialized : void 0; +}; +const stableJson = (value)=>{ + const serialized = serializeJson(value); + if (void 0 === serialized) throw new TypeError('Cannot serialize a top-level non-JSON value.'); + return serialized; +}; +const digest = (value)=>createHash('sha256').update(stableJson(value)).digest('hex'); + + +__webpack_require__.d(__webpack_exports__, { +}, { + _Y: stableJson +}); + + +}, +"./node_modules/agent-bundle/dist/790~1.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +const isErrno = (error, code)=>'object' == typeof error && null !== error && 'code' in error && error.code === code; +const errorMessage = (error)=>error instanceof Error ? error.message : String(error); +class CodedError extends Error { + code; + constructor(name, code, message, options){ + super(message, options); + this.name = name; + this.code = code; + } +} + + +__webpack_require__.d(__webpack_exports__, { +}, { + gJ: errorMessage +}); + + +}, +"./node_modules/agent-bundle/dist/991~1.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +const isJsonWhitespace = (code)=>0x09 === code || 0x0a === code || 0x0d === code || 0x20 === code; +const isValueTerminator = (code)=>isJsonWhitespace(code) || 0x2c === code || 0x7d === code || 0x5d === code; +const skipWhitespace = (bytes, index)=>{ + let cursor = index; + while(cursor < bytes.length && isJsonWhitespace(bytes.charCodeAt(cursor)))cursor += 1; + return cursor; +}; +const scanJsonString = (bytes, index)=>{ + let cursor = index + 1; + while(cursor < bytes.length){ + const character = bytes[cursor]; + if ('\\' === character) { + cursor += 2; + continue; + } + if ('"' === character) { + const end = cursor + 1; + return [ + JSON.parse(bytes.slice(index, end)), + end + ]; + } + cursor += 1; + } + throw new SyntaxError('JSON has an unterminated string.'); +}; +const scanJsonValue = (bytes, index)=>{ + let cursor = skipWhitespace(bytes, index); + const character = bytes[cursor]; + if ('{' === character) { + cursor = skipWhitespace(bytes, cursor + 1); + const keys = new Set(); + if ('}' === bytes[cursor]) return cursor + 1; + while(true){ + if ('"' !== bytes[cursor]) throw new SyntaxError('JSON has an invalid object key.'); + const [key, afterKey] = scanJsonString(bytes, cursor); + if (keys.has(key)) throw new SyntaxError(`JSON has duplicate key ${JSON.stringify(key)}.`); + keys.add(key); + cursor = skipWhitespace(bytes, afterKey); + if (':' !== bytes[cursor]) throw new SyntaxError('JSON has an invalid object entry.'); + cursor = skipWhitespace(bytes, scanJsonValue(bytes, cursor + 1)); + if ('}' === bytes[cursor]) return cursor + 1; + if (',' !== bytes[cursor]) throw new SyntaxError('JSON has an invalid object separator.'); + cursor = skipWhitespace(bytes, cursor + 1); + } + } + if ('[' === character) { + cursor = skipWhitespace(bytes, cursor + 1); + if (']' === bytes[cursor]) return cursor + 1; + while(true){ + cursor = skipWhitespace(bytes, scanJsonValue(bytes, cursor)); + if (']' === bytes[cursor]) return cursor + 1; + if (',' !== bytes[cursor]) throw new SyntaxError('JSON has an invalid array separator.'); + cursor = skipWhitespace(bytes, cursor + 1); + } + } + if ('"' === character) return scanJsonString(bytes, cursor)[1]; + while(cursor < bytes.length && !isValueTerminator(bytes.charCodeAt(cursor)))cursor += 1; + return cursor; +}; +class StrictJsonError extends TypeError { + reason; + constructor(reason, message){ + super(message); + this.name = 'StrictJsonError'; + this.reason = reason; + } +} +const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value); +const isJsonRecord = (value)=>isRecord(value); +const ownDataValue = (value, key)=>{ + const descriptor = Object.getOwnPropertyDescriptor(value, key); + if (void 0 === descriptor) return { + found: false, + value: void 0 + }; + return 'value' in descriptor ? { + found: true, + value: descriptor.value + } : void 0; +}; +const dataArrayValues = (value)=>{ + if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) return; + const length = Object.getOwnPropertyDescriptor(value, 'length'); + if (void 0 === length || !('value' in length) || 'number' != typeof length.value || !Number.isSafeInteger(length.value) || length.value < 0 || Reflect.ownKeys(value).length !== length.value + 1) return; + const copy = []; + for(let index = 0; index < length.value; index += 1){ + const descriptor = Object.getOwnPropertyDescriptor(value, String(index)); + if (void 0 === descriptor || !('value' in descriptor)) return; + copy.push(descriptor.value); + } + return Object.freeze(copy); +}; +const isPlainRecord = (value)=>{ + if (!isRecord(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || null === prototype; +}; +const hasOnlyOwnKeys = (value, keys)=>Object.keys(value).every((key)=>keys.includes(key)); +const isPlainDataRecord = (value)=>{ + if (!isRecord(value)) return false; + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && null !== prototype) return false; + return Reflect.ownKeys(value).every((key)=>{ + if ('string' != typeof key) return false; + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return void 0 !== descriptor && 'value' in descriptor; + }); +}; +const hasDataKeys = (value, required, optional = [])=>{ + if (!isPlainDataRecord(value)) return false; + const allowed = new Set([ + ...required, + ...optional + ]); + return Reflect.ownKeys(value).length >= required.length && Reflect.ownKeys(value).every((key)=>'string' == typeof key && allowed.has(key)) && required.every((key)=>Object.hasOwn(value, key)); +}; +const fail = (reason, message)=>{ + throw new StrictJsonError(reason, message); +}; +const snapshotJsonValue = (value, ancestors, nullPrototype)=>{ + if (null === value || 'boolean' == typeof value || 'string' == typeof value) return value; + if ('number' == typeof value) { + if (Number.isFinite(value)) return value; + return fail('nonfinite', 'JSON values must be finite.'); + } + if ('object' != typeof value) return fail('not-json', 'JSON values must be primitives, arrays, or plain objects.'); + if (ancestors.has(value)) return fail('cyclic', 'JSON values must not be cyclic.'); + ancestors.add(value); + try { + const descriptors = Object.getOwnPropertyDescriptors(value); + if (Array.isArray(value)) { + if (Object.getPrototypeOf(value) !== Array.prototype) return fail('array-shape', 'JSON arrays must be ordinary arrays.'); + const length = descriptors.length; + if (void 0 === length || !('value' in length) || !Number.isSafeInteger(length.value) || length.value < 0) return fail('array-shape', 'JSON arrays must have a finite length.'); + const values = []; + for(let index = 0; index < length.value; index += 1){ + const descriptor = descriptors[String(index)]; + if (void 0 === descriptor || !descriptor.enumerable || !('value' in descriptor)) return fail('array-shape', 'JSON arrays must contain only enumerable data properties.'); + values.push(snapshotJsonValue(descriptor.value, ancestors, nullPrototype)); + } + if (Reflect.ownKeys(descriptors).length !== length.value + 1) return fail('array-shape', 'JSON arrays must not have extra properties.'); + return Object.freeze(values); + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && null !== prototype) return fail('exotic-prototype', 'JSON objects must be plain objects.'); + const entries = Reflect.ownKeys(descriptors).map((key)=>{ + if ('string' != typeof key) return fail('not-json', 'JSON objects must not use symbol keys.'); + const descriptor = descriptors[key]; + if (void 0 === descriptor || !descriptor.enumerable || !('value' in descriptor)) return fail('not-json', 'JSON objects must contain only enumerable data properties.'); + return [ + key, + snapshotJsonValue(descriptor.value, ancestors, nullPrototype) + ]; + }); + if (nullPrototype) { + const snapshot = Object.create(null); + for (const [key, entry] of entries)snapshot[key] = entry; + return Object.freeze(snapshot); + } + return Object.freeze(Object.fromEntries(entries)); + } finally{ + ancestors.delete(value); + } +}; +const snapshotStrictJsonValue = (value, options = {})=>snapshotJsonValue(value, new Set(), true === options.nullPrototype); +const parseJsonWithoutDuplicateKeys = (bytes)=>{ + const end = skipWhitespace(bytes, scanJsonValue(bytes, 0)); + if (end !== bytes.length) throw new SyntaxError('JSON has trailing data.'); + return JSON.parse(bytes); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + UQ: isPlainRecord +}); + + +}, +"./node_modules/agent-bundle/dist/cli-entry.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _667_1_js__rspack_import_0 = __webpack_require__("./node_modules/agent-bundle/dist/667~1.js"); +/* import */ var _790_1_js__rspack_import_1 = __webpack_require__("./node_modules/agent-bundle/dist/790~1.js"); +/* import */ var _terminal_capability_js__rspack_import_2 = __webpack_require__("./node_modules/agent-bundle/dist/terminal-capability.js"); + + + +class CliUsageError extends Error { + constructor(message){ + super(message); + this.name = 'CliUsageError'; + } +} +const confirmationRequiredMessage = (server, tool)=>`MCP tool ${server}:${tool} is mutation-capable per its MCP annotations and requires --yes.`; +const cliInputInvalidCode = 'CLI_INPUT_INVALID'; +class CliInputError extends Error { + issues; + constructor(message, issues = []){ + super(message); + this.name = 'CliInputError'; + this.issues = Object.freeze([ + ...issues + ]); + } +} +const isSchemaIssue = (value)=>'object' == typeof value && null !== value && 'string' == typeof value.message && Array.isArray(value.path); +const schemaIssuesOf = (error)=>{ + const issues = error?.issues; + if (!Array.isArray(issues) || 0 === issues.length || !issues.every(isSchemaIssue)) return; + return issues; +}; +const boundLabel = (issue, direction)=>{ + const bound = 'max' === direction ? issue.maximum : issue.minimum; + const inclusiveBound = false !== issue.inclusive; + const value = String(bound); + const quantifier = true === issue.exact ? 'exactly' : 'max' === direction ? inclusiveBound ? 'at most' : 'fewer than' : inclusiveBound ? 'at least' : 'more than'; + switch(issue.origin){ + case 'string': + if ('min' === direction && inclusiveBound && 1 === bound && true !== issue.exact) return 'non-empty string'; + return `string with ${quantifier} ${value} characters`; + case 'array': + case 'set': + return `${String(issue.origin)} with ${quantifier} ${value} items`; + default: + { + const comparator = true === issue.exact ? '==' : 'max' === direction ? inclusiveBound ? '<=' : '<' : inclusiveBound ? '>=' : '>'; + return `${'string' == typeof issue.origin ? issue.origin : 'value'} ${comparator} ${value}`; + } + } +}; +const formatLabel = (issue)=>{ + switch(issue.format){ + case 'starts_with': + return `string starting with ${JSON.stringify(issue.prefix)}`; + case 'ends_with': + return `string ending with ${JSON.stringify(issue.suffix)}`; + case 'includes': + return `string containing ${JSON.stringify(issue.includes)}`; + case 'regex': + return `string matching ${String(issue.pattern)}`; + case 'url': + return 'URL'; + default: + return issue.message; + } +}; +const expectationOf = (issue)=>{ + switch(issue.code){ + case 'invalid_type': + return 'string' == typeof issue.expected ? issue.expected : issue.message; + case 'too_big': + return boundLabel(issue, 'max'); + case 'too_small': + return boundLabel(issue, 'min'); + case 'invalid_value': + case 'invalid_enum_value': + case 'invalid_literal': + return Array.isArray(issue.values) ? `one of: ${issue.values.map((value)=>JSON.stringify(value)).join(', ')}` : issue.message; + case 'invalid_format': + case 'invalid_string': + return formatLabel(issue); + case 'unrecognized_keys': + return Array.isArray(issue.keys) ? `no unknown ${1 === issue.keys.length ? 'key' : 'keys'} ${issue.keys.map((key)=>JSON.stringify(key)).join(', ')}` : issue.message; + default: + return issue.message; + } +}; +const valueAt = (input, path)=>{ + let cursor = input; + for (const segment of path){ + if (null === cursor || 'object' != typeof cursor) return; + cursor = cursor[segment]; + } + return cursor; +}; +const pathSuffix = (path)=>path.map((segment)=>'number' == typeof segment ? `[${String(segment)}]` : `.${String(segment)}`).join(''); +const takesJsonInput = (command)=>'json' === command.input || void 0 !== command.mcp && (void 0 === command.projection || 'json' === command.projection.input); +const targetOf = (command, path)=>{ + if (0 === path.length) return 'input'; + if (takesJsonInput(command)) return `--input${pathSuffix(path)}`; + const [head, ...rest] = path; + const option = command.options.find((candidate)=>candidate.key === head); + if (void 0 === option) return `input${pathSuffix(path)}`; + const spelled = void 0 === option.positional ? `--${option.option}` : `<${option.option}>`; + return `${spelled}${pathSuffix(rest)}`; +}; +const cliInputIssueLine = (issue)=>`Invalid value for ${issue.target}: expected ${issue.expected}; received ${void 0 === issue.received ? 'nothing' : (0,_667_1_js__rspack_import_0/* .stableJson */._Y)(issue.received)}.`; +const cliInputError = (command, input, error)=>{ + const schemaIssues = schemaIssuesOf(error); + if (void 0 === schemaIssues) return new CliInputError(error instanceof Error ? error.message : String(error)); + const issues = schemaIssues.map((issue)=>{ + const received = valueAt(input, issue.path); + return { + expected: expectationOf(issue), + message: issue.message, + ...void 0 === received ? {} : { + received + }, + target: targetOf(command, issue.path) + }; + }); + return new CliInputError(issues.map(cliInputIssueLine).join('\n'), issues); +}; +const resolveTerminal = (hostSurface, options)=>{ + if (void 0 !== options.terminal) return options.terminal; + if (void 0 === options.isTty) return (0,_terminal_capability_js__rspack_import_2/* .detectProcessTerminal */.JH)(hostSurface); + const stdout = { + columns: process.stdout.columns, + fd: 1, + isTTY: options.isTty(), + rows: process.stdout.rows + }; + return (0,_terminal_capability_js__rspack_import_2/* .detectProcessTerminal */.JH)(hostSurface, { + stdout + }); +}; +const webCommandRow = [ + 'web', + "Open one of the plugin's MCP Apps in a browser." +]; +const buildCommandTree = (commands)=>{ + const root = { + children: new Map(), + path: [] + }; + for (const command of commands){ + let node = root; + for (const segment of command.path){ + let child = node.children.get(segment); + if (void 0 === child) { + child = { + children: new Map(), + path: [ + ...node.path, + segment + ] + }; + node.children.set(segment, child); + } + node = child; + } + node.command = command; + const parent = 1 === command.path.length ? root : command.path.slice(0, -1).reduce((cursor, segment)=>cursor.children.get(segment), root); + for (const alias of command.aliases){ + const target = parent.children.get(command.path[command.path.length - 1]); + parent.children.set(alias, target); + } + } + return root; +}; +const optionPlaceholder = (option)=>{ + if ('boolean' === option.kind) return ''; + if (void 0 !== option.choices) return ` <${option.choices.join('|')}>`; + return ` <${option.kind}>`; +}; +const positionalPlaceholder = (option)=>{ + const name = option.repeated ? `${option.option}...` : option.option; + return option.required ? `<${name}>` : `[${name}]`; +}; +const helpColumns = (rows)=>{ + const width = rows.reduce((max, [left])=>Math.max(max, left.length), 0); + return rows.map(([left, right])=>` ${left.padEnd(width)}${'' === right ? '' : ` ${right}`}`).join('\n'); +}; +const sortedPositionals = (command)=>command.options.filter((option)=>void 0 !== option.positional).sort((left, right)=>left.positional - right.positional); +const namedOptions = (command)=>command.options.filter((option)=>void 0 === option.positional); +const globalOptionRows = [ + [ + '-h, --help', + 'Show help.' + ], + [ + ' --json', + 'Emit the canonical JSON result.' + ], + [ + ' --version', + 'Print the version.' + ] +]; +const renderedOptionRows = [ + [ + '-h, --help', + 'Show help.' + ], + [ + ' --json', + 'Emit the canonical JSON result.' + ], + [ + ' --ndjson', + 'Emit the sequence-numbered render-event stream.' + ], + [ + ' --version', + 'Print the version.' + ] +]; +const commandUsage = (name, command)=>{ + const positionals = sortedPositionals(command).map(positionalPlaceholder); + return `Usage: ${name} ${command.path.join(' ')} [options]${0 === positionals.length ? '' : ` ${positionals.join(' ')}`}`; +}; +const commandHelp = (name, command)=>{ + const lines = [ + commandUsage(name, command) + ]; + if (void 0 !== command.description) lines.push('', command.description); + if (command.aliases.length > 0) lines.push('', `Aliases: ${command.aliases.join(', ')}`); + if (void 0 !== command.mcp) { + lines.push('', `MCP tool: ${command.mcp.server}:${command.mcp.tool}`); + if (command.mcp.confirm) lines.push('Mutation-capable; requires --yes.'); + } + if (void 0 !== command.projection) lines.push(`Projection: ${command.projection.module}`); + const positionals = sortedPositionals(command); + if (positionals.length > 0) lines.push('', 'Arguments:', helpColumns(positionals.map((option)=>[ + positionalPlaceholder(option), + [ + option.description ?? '', + ...void 0 === option.choices ? [] : [ + `(${option.choices.join('|')})` + ], + ...void 0 === option.defaultValue ? [] : [ + `[default: ${JSON.stringify(option.defaultValue)}]` + ] + ].filter((part)=>'' !== part).join(' ') + ]))); + const options = namedOptions(command); + const optionRows = options.map((option)=>[ + ` ${[ + option.option, + ...option.aliases ?? [] + ].map((spelling)=>`--${spelling}`).join(', ')}${optionPlaceholder(option)}${option.repeated ? ' ...' : ''}`, + [ + option.description ?? '', + ...option.required ? [ + '(required)' + ] : [], + ...void 0 === option.defaultValue ? [] : [ + `[default: ${JSON.stringify(option.defaultValue)}]` + ] + ].filter((part)=>'' !== part).join(' ') + ]); + lines.push('', 'Options:', helpColumns([ + ...optionRows, + ...command.rendered ? renderedOptionRows : globalOptionRows + ])); + return `${lines.join('\n')}\n`; +}; +const treeHelp = (name, version, description, node, web)=>{ + const lines = []; + if (0 === node.path.length) { + lines.push(`${name} ${version}`); + if (void 0 !== description) lines.push('', description); + lines.push('', `Usage: ${name} [options]`); + } else lines.push(`Usage: ${name} ${node.path.join(' ')} [options]`); + const rows = []; + const seen = new Set(); + for (const [segment, child] of [ + ...node.children.entries() + ].sort(([left], [right])=>left.localeCompare(right))){ + if (seen.has(child)) continue; + seen.add(child); + const label = void 0 === child.command ? `${segment} ` : segment; + rows.push([ + label, + child.command?.description ?? '' + ]); + } + if (web && 0 === node.path.length) { + const at = rows.findIndex(([label])=>label.localeCompare(webCommandRow[0]) > 0); + rows.splice(-1 === at ? rows.length : at, 0, webCommandRow); + } + lines.push('', 'Commands:', helpColumns(rows)); + lines.push('', 'Options:', helpColumns(globalOptionRows)); + return `${lines.join('\n')}\n`; +}; +const coerceValue = (option, value, deferChoices)=>{ + switch(option.kind){ + case 'boolean': + throw new CliUsageError(`--${option.option} is a flag and takes no value.`); + case 'number': + { + const parsed = Number(value); + if ('' === value.trim() || !Number.isFinite(parsed)) throw new CliUsageError(`--${option.option} requires a number; got ${JSON.stringify(value)}.`); + return parsed; + } + case 'enum': + if (!deferChoices && !(option.choices ?? []).includes(value)) throw new CliUsageError(`--${option.option} must be one of: ${(option.choices ?? []).join(', ')}.`); + return value; + case 'string': + return value; + default: + { + const unreachable = option.kind; + throw new TypeError(`Unhandled option kind ${String(unreachable)}.`); + } + } +}; +const coercePositional = (option, value, deferChoices)=>{ + switch(option.kind){ + case 'number': + { + const parsed = Number(value); + if ('' === value.trim() || !Number.isFinite(parsed)) throw new CliUsageError(`<${option.option}> requires a number; got ${JSON.stringify(value)}.`); + return parsed; + } + case 'enum': + if (!deferChoices && !(option.choices ?? []).includes(value)) throw new CliUsageError(`<${option.option}> must be one of: ${(option.choices ?? []).join(', ')}.`); + return value; + case 'string': + return value; + case 'boolean': + throw new CliUsageError(`<${option.option}> cannot be a flag.`); + default: + { + const unreachable = option.kind; + throw new TypeError(`Unhandled option kind ${String(unreachable)}.`); + } + } +}; +const parseCommandArgv = (command, argv)=>{ + const options = new Map(); + for (const option of namedOptions(command)){ + options.set(option.option, option); + for (const alias of option.aliases ?? [])options.set(alias, option); + } + const positionals = sortedPositionals(command); + const deferChoices = command.projection?.mapInput === true; + const values = new Map(); + const bare = []; + let json = false; + let ndjson = false; + let index = 0; + const readOption = (raw)=>{ + const separator = raw.indexOf('='); + const name = -1 === separator ? raw.slice(2) : raw.slice(2, separator); + const inline = -1 === separator ? void 0 : raw.slice(separator + 1); + if ('json' === name && void 0 === inline) { + json = true; + return; + } + if ('ndjson' === name && void 0 === inline) { + ndjson = true; + return; + } + const option = options.get(name); + if (void 0 === option) throw new CliUsageError(`Unknown option: --${name}.`); + if ('boolean' === option.kind) { + if (void 0 !== inline) throw new CliUsageError(`--${name} is a flag and takes no value.`); + if (values.has(option.key)) throw new CliUsageError(`Duplicate option: --${name}.`); + values.set(option.key, true); + return; + } + let value = inline; + if (void 0 === value) { + const next = argv[index + 1]; + if (void 0 === next || next.startsWith('--')) throw new CliUsageError(`--${name} requires a value.`); + value = next; + index += 1; + } + const coerced = coerceValue(option, value, deferChoices); + if (option.repeated) { + const existing = values.get(option.key); + values.set(option.key, Array.isArray(existing) ? [ + ...existing, + coerced + ] : [ + coerced + ]); + return; + } + if (values.has(option.key)) throw new CliUsageError(`Duplicate option: --${name}.`); + values.set(option.key, coerced); + }; + for(; index < argv.length; index += 1){ + const raw = argv[index]; + if ('--' === raw) { + bare.push(...argv.slice(index + 1)); + break; + } + if (raw.startsWith('--')) { + readOption(raw); + continue; + } + if (raw.startsWith('-') && raw.length > 1) { + const positional = positionals[bare.length] ?? (positionals[positionals.length - 1]?.repeated === true ? positionals[positionals.length - 1] : void 0); + const negativeNumber = positional?.kind === 'number' && /^-\d/u.test(raw) && Number.isFinite(Number(raw)); + if (!negativeNumber) throw new CliUsageError(`Unknown option: ${raw}.`); + } + bare.push(raw); + } + let cursor = 0; + for (const option of positionals){ + if (option.repeated) { + const rest = bare.slice(cursor).map((value)=>coercePositional(option, value, deferChoices)); + cursor = bare.length; + if (0 === rest.length) { + if (option.required) throw new CliUsageError(`Missing required argument: <${option.option}...>.`); + continue; + } + values.set(option.key, rest); + continue; + } + if (cursor >= bare.length) { + if (option.required) throw new CliUsageError(`Missing required argument: <${option.option}>.`); + continue; + } + values.set(option.key, coercePositional(option, bare[cursor], deferChoices)); + cursor += 1; + } + if (cursor < bare.length) throw new CliUsageError(`Unexpected argument: ${JSON.stringify(bare[cursor])}.`); + for (const option of namedOptions(command))if (option.required && !values.has(option.key)) throw new CliUsageError(`Missing required option: --${option.option}.`); + if (json && ndjson) throw new CliUsageError('Use either --json or --ndjson, not both.'); + return { + input: Object.fromEntries(values), + json, + ndjson + }; +}; +const parseMcpCommandInput = (command, parsed)=>{ + if (void 0 === command.mcp && 'json' !== command.input) return parsed; + if (command.mcp?.confirm === true && true !== parsed.input['yes']) throw new CliUsageError(confirmationRequiredMessage(command.mcp.server, command.mcp.tool)); + if (void 0 !== command.projection && 'json' !== command.projection.input) { + if (command.mcp?.confirm !== true) return parsed; + const input = { + ...parsed.input + }; + delete input['yes']; + return { + ...parsed, + input + }; + } + const raw = parsed.input['input']; + let input = {}; + if (void 0 !== raw) try { + input = JSON.parse(raw); + } catch { + throw new CliUsageError('--input must be one valid JSON object.'); + } + if ('object' != typeof input || null === input || Array.isArray(input)) throw new CliUsageError('--input must be a JSON object; arrays, null, and scalar values are not accepted.'); + return { + ...parsed, + input: input + }; +}; +const parseGeneratedCliArgv = (command, argv)=>parseMcpCommandInput(command, parseCommandArgv(command, argv)); +const mapGeneratedCliInput = async (command, inputSchema, projectionModule, input)=>{ + const withDefaults = { + ...input + }; + for (const [key, value] of Object.entries(command.projection?.defaults ?? {}))if (!Object.hasOwn(withDefaults, key)) withDefaults[key] = value; + let mapped = withDefaults; + if (command.projection?.mapInput === true) { + const mapInput = projectionModule?.['mapInput']; + if ('function' != typeof mapInput) throw new TypeError(`CLI projection ${command.projection.module} for ${command.routeId} must export a mapInput function.`); + try { + mapped = await mapInput(withDefaults); + } catch (error) { + throw new CliInputError(error instanceof Error ? error.message : String(error)); + } + } + try { + return inputSchema.parse(mapped); + } catch (error) { + throw cliInputError(command, mapped, error); + } +}; +const resultExitCode = (policy, result)=>{ + if ('zero' === policy) return 0; + const exitCode = 'object' == typeof result && null !== result ? result['exitCode'] : void 0; + if ('number' != typeof exitCode || !Number.isInteger(exitCode) || exitCode < 0 || exitCode > 255) throw new Error(`The exitCode result policy requires an integer exitCode property between 0 and 255; got ${JSON.stringify(exitCode)}.`); + return exitCode; +}; +const renderedDocumentExitCode = (policy, document, value)=>'success' === document.status ? resultExitCode(policy, value) : 1; +const markdownBlocks = (node)=>{ + switch(node.kind){ + case 'result': + return node.children.flatMap(markdownBlocks); + case 'markdown': + case 'text': + return [ + node.text + ]; + case 'context': + return [ + node.text.split('\n').map((line)=>`> ${line}`).join('\n') + ]; + case 'json': + return [ + `\`\`\`json\n${JSON.stringify(node.value, null, 2)}\n\`\`\`` + ]; + case 'progress': + return []; + case 'image': + return [ + `![image](data:${node.mimeType};base64,${node.data})` + ]; + case 'audio': + return [ + `[audio](data:${node.mimeType};base64,${node.data})` + ]; + case 'resource': + return [ + `[${node.name}](${node.uri})` + ]; + case 'error': + return [ + `**[${node.code}]** ${node.message}` + ]; + default: + { + const unreachable = node; + throw new TypeError(`Unsupported Agent Document node ${String(unreachable.kind)}.`); + } + } +}; +const projectCliDocumentToMarkdown = (document)=>{ + const blocks = markdownBlocks(document.root).filter((block)=>'' !== block.trim()); + return 0 === blocks.length ? '' : `${blocks.join('\n\n')}\n`; +}; +const progressLine = (event)=>{ + const counter = void 0 === event.total ? String(event.completed) : `${String(event.completed)}/${String(event.total)}`; + return void 0 === event.message ? counter : `${event.message} (${counter})`; +}; +const progressNodes = (node)=>{ + switch(node.kind){ + case 'result': + return node.children.flatMap(progressNodes); + case 'progress': + return [ + node + ]; + case 'audio': + case 'context': + case 'error': + case 'image': + case 'json': + case 'markdown': + case 'resource': + case 'text': + return []; + default: + { + const unreachable = node; + throw new TypeError(`Unsupported Agent Document node ${String(unreachable.kind)}.`); + } + } +}; +const clearProgressLine = '\r\u001B[2K'; +const renderFailedCode = 'render-failed'; +const writeRenderFailure = (mode, error, writeErr)=>{ + const message = (0,_790_1_js__rspack_import_1/* .errorMessage */.gJ)(error); + writeErr('json' === mode ? `${(0,_667_1_js__rspack_import_0/* .stableJson */._Y)({ + error: { + code: renderFailedCode, + message + } + })}\n` : `[${renderFailedCode}] ${message}\n`); +}; +const runRenderedInvocation = async (options)=>{ + const { mode, writeErr, writeOut } = options; + const reader = options.session.events().getReader(); + let complete; + let progressShown = false; + const showProgress = (source)=>{ + if ('tty' !== mode) return; + writeOut(`${clearProgressLine}${progressLine(source)}`); + progressShown = true; + }; + const shownFallbacks = new Set(); + const showFallback = (node)=>{ + const key = JSON.stringify([ + node.completed, + node.message, + node.total + ]); + if (shownFallbacks.has(key)) return; + shownFallbacks.add(key); + showProgress(node); + }; + const clearProgress = ()=>{ + if (progressShown) { + writeOut(clearProgressLine); + progressShown = false; + } + }; + try { + while(true){ + const next = await reader.read(); + if (next.done) break; + const event = next.value; + if ('ndjson' === mode) writeOut(`${JSON.stringify(event)}\n`); + switch(event.type){ + case 'shell': + case 'replace': + for (const node of progressNodes(event.document.root))showFallback(node); + break; + case 'progress': + showProgress(event); + break; + case 'error': + if ('ndjson' !== mode) { + clearProgress(); + writeErr(`[${event.error.code}] ${event.error.message}\n`); + } + break; + case 'complete': + complete = event.document; + break; + default: + { + const unreachable = event; + throw new TypeError(`Unsupported render event ${String(unreachable.type)}.`); + } + } + } + } catch (error) { + clearProgress(); + if (options.signal.aborted || error instanceof DOMException && 'AbortError' === error.name) { + writeErr('Aborted.\n'); + return 1; + } + writeRenderFailure(mode, error, writeErr); + return 1; + } + clearProgress(); + if (void 0 === complete) { + writeErr('The render ended without a complete document.\n'); + return 1; + } + let value = complete.value; + try { + value = options.session.validate(value); + } catch (error) { + writeErr(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } + switch(mode){ + case 'json': + writeOut(`${JSON.stringify(value ?? null)}\n`); + break; + case 'ndjson': + break; + case 'tty': + case 'markdown': + writeOut(projectCliDocumentToMarkdown(complete)); + break; + default: + { + const unreachable = mode; + throw new TypeError(`Unsupported output mode ${String(unreachable)}.`); + } + } + return renderedDocumentExitCode(options.exitCode, complete, value); +}; +const runGeneratedCliEntry = async (options)=>{ + const writeOut = options.writeOut ?? ((text)=>void process.stdout.write(text)); + const writeErr = options.writeErr ?? ((text)=>void process.stderr.write(text)); + const signal = options.signal ?? new AbortController().signal; + const tree = buildCommandTree(options.commands); + let node = tree; + let index = 0; + let parsed; + const web = void 0 !== options.web; + try { + if ('--version' === options.argv[0]) { + writeOut(`${options.name} ${options.version}\n`); + return 0; + } + if (void 0 !== options.web && 'web' === options.argv[0]) return await options.web.run(options.argv.slice(1), { + name: options.name, + signal, + writeErr, + writeOut + }); + while(index < options.argv.length){ + const token = options.argv[index]; + if ('--help' === token || '-h' === token) { + writeOut(void 0 === node.command ? treeHelp(options.name, options.version, options.description, node, web) : commandHelp(options.name, node.command)); + return 0; + } + if (void 0 !== node.command || token.startsWith('-')) break; + const child = node.children.get(token); + if (void 0 === child) throw new CliUsageError(0 === node.path.length ? `Unknown command: ${token}.` : `Unknown command: ${node.path.join(' ')} ${token}.`); + node = child; + index += 1; + } + if (void 0 === node.command) { + if (0 === node.path.length && index >= options.argv.length) { + writeOut(treeHelp(options.name, options.version, options.description, node, web)); + return 0; + } + const token = options.argv[index]; + if (void 0 !== token && token.startsWith('-')) throw new CliUsageError(`Unknown option: ${token}.`); + throw new CliUsageError(`Missing command: ${options.name}${0 === node.path.length ? '' : ` ${node.path.join(' ')}`} .`); + } + const command = node.command; + const rest = options.argv.slice(index); + const terminator = rest.indexOf('--'); + const visible = -1 === terminator ? rest : rest.slice(0, terminator); + if (visible.includes('--help') || visible.includes('-h')) { + writeOut(commandHelp(options.name, command)); + return 0; + } + parsed = parseGeneratedCliArgv(command, rest); + signal.throwIfAborted(); + const terminal = resolveTerminal('cli', options); + if (command.rendered) { + if (void 0 === options.render) throw new Error(`Rendered command ${command.path.join(' ')} has no render host.`); + const mode = parsed.ndjson ? 'ndjson' : parsed.json ? 'json' : 'tty' === terminal.stdout.kind ? 'tty' : 'markdown'; + const session = await options.render(command, parsed.input, { + args: rest, + signal, + terminal + }); + try { + return await runRenderedInvocation({ + exitCode: command.exitCode, + mode, + session, + signal, + writeErr, + writeOut + }); + } finally{ + await session.close(); + } + } + if (parsed.ndjson) throw new CliUsageError('--ndjson requires a rendered command.'); + const result = await options.execute(command, parsed.input, { + args: rest, + json: parsed.json, + signal, + terminal + }); + signal.throwIfAborted(); + const exitCode = resultExitCode(command.exitCode, result); + writeOut(`${(0,_667_1_js__rspack_import_0/* .stableJson */._Y)(void 0 === result ? null : result)}\n`); + return exitCode; + } catch (error) { + if (signal.aborted || error instanceof DOMException && 'AbortError' === error.name) { + writeErr('Aborted.\n'); + return 1; + } + const helpPath = 0 === node.path.length ? '' : ` ${node.path.join(' ')}`; + const helpHint = `Run '${options.name}${helpPath} --help' for usage.\n`; + if (error instanceof CliInputError && error.issues.length > 0 && void 0 !== node.command) { + writeInputIssues({ + command: node.command, + issues: error.issues, + mode: parsed?.ndjson === true ? 'ndjson' : parsed?.json === true ? 'json' : 'text', + name: options.name, + writeErr, + writeOut + }); + if (parsed?.json !== true && parsed?.ndjson !== true) writeErr(helpHint); + return 2; + } + const usage = error instanceof CliUsageError || error instanceof CliInputError; + writeErr(`${error instanceof Error ? error.message : String(error)}\n`); + if (usage) writeErr(helpHint); + return usage ? 2 : 1; + } +}; +const writeInputIssues = (report)=>{ + const usage = commandUsage(report.name, report.command); + switch(report.mode){ + case 'json': + report.writeErr(`${(0,_667_1_js__rspack_import_0/* .stableJson */._Y)({ + error: { + code: cliInputInvalidCode, + issues: report.issues, + usage + } + })}\n`); + return; + case 'ndjson': + report.writeOut(`${(0,_667_1_js__rspack_import_0/* .stableJson */._Y)({ + error: { + code: cliInputInvalidCode, + issues: report.issues, + message: report.issues.map(cliInputIssueLine).join('\n'), + usage + }, + sequence: 0, + type: 'error' + })}\n`); + return; + case 'text': + for (const issue of report.issues)report.writeErr(`${cliInputIssueLine(issue)}\n`); + report.writeErr(`${usage}\n`); + return; + default: + { + const unreachable = report.mode; + throw new TypeError(`Unsupported output mode ${String(unreachable)}.`); + } + } +}; +const runGeneratedRenderedScript = async (options)=>{ + const writeOut = options.writeOut ?? ((text)=>void process.stdout.write(text)); + const writeErr = options.writeErr ?? ((text)=>void process.stderr.write(text)); + const signal = options.signal ?? new AbortController().signal; + const terminator = options.argv.indexOf('--'); + const visible = -1 === terminator ? options.argv : options.argv.slice(0, terminator); + const json = visible.includes('--json'); + const ndjson = visible.includes('--ndjson'); + if (json && ndjson) { + writeErr('Use either --json or --ndjson, not both.\n'); + return 2; + } + const argv = options.argv.filter((argument, index)=>-1 !== terminator && index > terminator || '--json' !== argument && '--ndjson' !== argument); + const terminal = resolveTerminal("script", options); + const mode = ndjson ? 'ndjson' : json ? 'json' : 'tty' === terminal.stdout.kind ? 'tty' : 'markdown'; + const session = options.createSession(argv, { + signal, + terminal + }); + try { + return await runRenderedInvocation({ + exitCode: 'zero', + mode, + session, + signal, + writeErr, + writeOut + }); + } finally{ + await session.close(); + } +}; +const wireProcessSignals = ()=>{ + const controller = new AbortController(); + let signalExitCode; + const onSignal = (exitCode)=>{ + signalExitCode = exitCode; + controller.abort(new DOMException('The process received a termination signal', 'AbortError')); + }; + process.once('SIGINT', ()=>onSignal(130)); + process.once('SIGTERM', ()=>onSignal(143)); + return { + exitCode: ()=>signalExitCode, + signal: controller.signal + }; +}; +const runGeneratedCliProcess = async (options)=>{ + const wiring = wireProcessSignals(); + const code = await runGeneratedCliEntry({ + ...options, + argv: process.argv.slice(2), + signal: wiring.signal + }); + process.exitCode = wiring.exitCode() ?? code; +}; +const runGeneratedRenderedScriptProcess = async (options)=>{ + const wiring = wireProcessSignals(); + const code = await runGeneratedRenderedScript({ + ...options, + argv: process.argv.slice(2), + signal: wiring.signal + }); + process.exitCode = wiring.exitCode() ?? code; +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + $u: parseGeneratedCliArgv, + WU: mapGeneratedCliInput, + iU: renderedDocumentExitCode, + yA: runGeneratedCliProcess +}); + + +}, +"./node_modules/agent-bundle/dist/launch-env.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_fs__rspack_import_0 = __webpack_require__("node:fs"); +/* import */ var node_path__rspack_import_1 = __webpack_require__("node:path"); + + +const OPERATOR_ENV_FILE_VARIABLE = 'AGENT_BUNDLE_ENV_FILE'; +const OPERATOR_ENV_FILE_NONE = 'none'; +const OPERATOR_ENV_FILE_NAMES = Object.freeze([ + '.env', + '.env.local' +]); +const unexpandedToken = /\$\{[^}]*\}/u; +const operatorEnvPluginRoot = (fallback, env = process.env)=>{ + const declared = env['AGENT_BUNDLE_PLUGIN_ROOT'] ?? ''; + return '' === declared.trim() || unexpandedToken.test(declared) ? (0,node_path__rspack_import_1.resolve)(fallback) : (0,node_path__rspack_import_1.resolve)(declared); +}; +const operatorEnvFilePaths = (pluginRoot, env = process.env)=>{ + const explicit = env[OPERATOR_ENV_FILE_VARIABLE]?.trim() ?? ''; + if (explicit === OPERATOR_ENV_FILE_NONE) return Object.freeze([]); + if ('' !== explicit) return Object.freeze(explicit.split(node_path__rspack_import_1.delimiter).map((path)=>path.trim()).filter((path)=>'' !== path).map((path)=>(0,node_path__rspack_import_1.resolve)(path))); + return Object.freeze(OPERATOR_ENV_FILE_NAMES.map((name)=>(0,node_path__rspack_import_1.join)(pluginRoot, name))); +}; +const closingQuoteIndex = (raw, quote)=>{ + for(let index = 1; index < raw.length; index += 1){ + if ('\\' === raw[index]) { + index += 1; + continue; + } + if (raw[index] === quote) return index; + } + return -1; +}; +const unquotedValue = (raw)=>{ + const value = raw.trim(); + const comment = value.search(/\s#/u); + return (-1 === comment ? value : value.slice(0, comment)).trim(); +}; +const quotedValue = (quote, inner)=>'"' === quote ? inner.replace(/\\n/gu, '\n').replace(/\\r/gu, '\r').replace(/\\"/gu, '"') : inner; +const parseOperatorEnv = (contents)=>{ + const parsed = {}; + const lines = contents.replace(/\r\n?/gu, '\n').split('\n'); + for(let index = 0; index < lines.length; index += 1){ + const line = lines[index].trim(); + if ('' === line || line.startsWith('#')) continue; + const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/u.exec(line); + if (null === match) continue; + const key = match[1]; + let raw = match[2].trim(); + const quote = raw[0]; + if ('"' === quote || "'" === quote || '`' === quote) { + let end = closingQuoteIndex(raw, quote); + while(-1 === end && '`' !== quote && index + 1 < lines.length){ + index += 1; + raw += `\n${lines[index]}`; + end = closingQuoteIndex(raw, quote); + } + if (-1 !== end) { + const trailer = raw.slice(end + 1).trim(); + if ('' === trailer || trailer.startsWith('#')) { + parsed[key] = quotedValue(quote, raw.slice(1, end)); + continue; + } + } + } + parsed[key] = unquotedValue(raw); + } + return parsed; +}; +const readOptional = (path)=>{ + try { + return (0,node_fs__rspack_import_0.readFileSync)(path, 'utf8'); + } catch (error) { + return 'ENOENT' === error.code ? void 0 : null; + } +}; +const applyOperatorEnv = (options)=>{ + const env = options.env ?? process.env; + const reservedKey = (options.platform ?? process.platform) === 'win32' ? (key)=>key.toUpperCase() : (key)=>key; + const manifestDefaults = new Map(Object.entries(options.manifestEnv ?? {}).map(([key, value])=>[ + reservedKey(key), + value + ])); + const reserved = new Set(Object.keys(env).filter((key)=>void 0 !== env[key] && manifestDefaults.get(reservedKey(key)) !== env[key]).map(reservedKey)); + const files = []; + const applied = new Set(); + for (const path of operatorEnvFilePaths(options.pluginRoot, env)){ + const contents = readOptional(path); + if (void 0 === contents) { + files.push({ + path, + state: 'absent' + }); + continue; + } + if (null === contents) { + files.push({ + path, + state: 'unreadable' + }); + continue; + } + let count = 0; + for (const [key, value] of Object.entries(parseOperatorEnv(contents)))if (!reserved.has(reservedKey(key))) { + env[key] = value; + applied.add(key); + count += 1; + } + files.push({ + applied: count, + path, + state: 'loaded' + }); + } + return Object.freeze({ + applied: Object.freeze([ + ...applied + ].sort((left, right)=>left.localeCompare(right))), + files: Object.freeze(files) + }); +}; + + +__webpack_require__.d(__webpack_exports__, { +}, { + FF: operatorEnvPluginRoot, + OJ: applyOperatorEnv +}); + + +}, +"./node_modules/agent-bundle/dist/terminal-capability.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var node_fs__rspack_import_0 = __webpack_require__("node:fs"); + +const isSet = (value)=>void 0 !== value && '' !== value; +const isOn = (value)=>'0' !== value && 'false' !== value.toLowerCase(); +const terminalDepth = (env)=>{ + const colorterm = env.COLORTERM?.toLowerCase(); + if ('truecolor' === colorterm || '24bit' === colorterm) return 'truecolor'; + if (/-256(?:color)?$/u.test(env.TERM ?? '')) return '256'; + return 'basic'; +}; +const terminalColor = (env, isTty)=>{ + const forceColor = env.FORCE_COLOR; + if (void 0 !== forceColor) switch(forceColor){ + case '': + case '1': + case 'true': + return 'basic'; + case '2': + return '256'; + case '3': + return 'truecolor'; + default: + return 'none'; + } + const clicolorForce = env.CLICOLOR_FORCE; + if (isSet(clicolorForce) && isOn(clicolorForce)) return terminalDepth(env); + if (isSet(env.NO_COLOR)) return 'none'; + if ('0' === env.CLICOLOR) return 'none'; + if ('dumb' === env.TERM) return 'none'; + return isTty ? terminalDepth(env) : 'none'; +}; +const dimensionOverride = (value)=>{ + if (!isSet(value) || !/^\d+$/u.test(value)) return; + const parsed = Number(value); + return parsed > 0 ? parsed : void 0; +}; +const dimension = (override, reported, isTty)=>{ + const overridden = dimensionOverride(override); + if (void 0 !== overridden) return overridden; + return isTty && 'number' == typeof reported && reported > 0 ? reported : void 0; +}; +const streamKind = (probe)=>{ + if (true === probe.isTTY) return 'tty'; + try { + (0,node_fs__rspack_import_0.fstatSync)(probe.fd); + return 'pipe'; + } catch { + return 'none'; + } +}; +const probeStream = (probe, env)=>{ + const kind = streamKind(probe); + const isTty = 'tty' === kind; + const columns = dimension(env.COLUMNS, probe.columns, isTty); + const rows = dimension(env.LINES, probe.rows, isTty); + return Object.freeze({ + color: 'none' === kind ? 'none' : terminalColor(env, isTty), + kind, + ...void 0 === columns ? {} : { + columns + }, + ...void 0 === rows ? {} : { + rows + } + }); +}; +const sharesOutputTarget = (stdoutFd, stderrFd)=>{ + try { + const out = (0,node_fs__rspack_import_0.fstatSync)(stdoutFd); + const err = (0,node_fs__rspack_import_0.fstatSync)(stderrFd); + return 0 !== out.ino && out.dev === err.dev && out.ino === err.ino; + } catch { + return false; + } +}; +const processProbe = (stream, fd)=>({ + columns: stream.columns, + fd, + isTTY: stream.isTTY, + rows: stream.rows + }); +const detectProcessTerminal = (hostSurface, options = {})=>{ + const env = options.env ?? process.env; + const stdout = options.stdout ?? processProbe(process.stdout, 1); + const stderr = options.stderr ?? processProbe(process.stderr, 2); + return Object.freeze({ + hostSurface, + sharesTarget: sharesOutputTarget(stdout.fd, stderr.fd), + stderr: probeStream(stderr, env), + stdout: probeStream(stdout, env) + }); +}; +const closedStream = Object.freeze({ + color: 'none', + kind: 'none' +}); +const noTerminal = (hostSurface)=>Object.freeze({ + hostSurface, + sharesTarget: false, + stderr: closedStream, + stdout: closedStream + }); + + +__webpack_require__.d(__webpack_exports__, { +}, { + JH: detectProcessTerminal +}); + + +}, +"./node_modules/effect/dist/Array.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Equivalence_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Equivalence.js"); +/* import */ var _Function_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_array_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/array.js"); +/* import */ var _Iterable_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Option_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Order_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Record_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Record.js"); +/* import */ var _Result_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/** + * Works with JavaScript arrays, readonly arrays, and non-empty arrays. + * + * The helpers cover common collection work such as creating arrays, reading + * elements, transforming values, sorting, grouping, splitting, combining, and + * reducing many values to one result. Helpers that change contents return new + * arrays and preserve non-empty array types when the result is guaranteed to + * contain values. + * + * @since 2.0.0 + */ + + + + + + + + + + + + + + +/** + * 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 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const Array = globalThis.Array; +/** + * Creates a `NonEmptyArray` from one or more elements. + * + * **When to use** + * + * Use when you need to create a typed non-empty array from literal values. + * + * **Details** + * + * The element type is inferred as the union of all arguments. Because at least + * one argument is required, this always returns a `NonEmptyArray`. + * + * **Example** (Creating an array from values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.make(1, 2, 3) // => [1, 2, 3] + * ``` + * + * @see {@link of} — create a single-element array + * @see {@link fromIterable} — create from any iterable + * + * @category constructors + * @since 2.0.0 + */ +const make = (...elements) => elements; +/** + * Creates a new `Array` of the specified length with all slots uninitialized. + * + * **When to use** + * + * Use when you need a pre-sized array that will be filled imperatively. + * + * **Details** + * + * Elements are typed as `A | undefined` because the slots are empty. + * + * **Example** (Allocating a fixed-size array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.allocate(3).length // => 3 + * ``` + * + * @see {@link makeBy} — create an array by computing each element + * + * @category constructors + * @since 2.0.0 + */ +const allocate = n => new Array(n); +/** + * Creates a `NonEmptyArray` of length `n` where element `i` is computed by `f(i)`. + * + * **When to use** + * + * Use when you need to compute each array element from its index. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to 1, so this function + * always returns at least one element. Supports both data-first and data-last + * usage. + * + * **Example** (Generating values from indices) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.makeBy(5, (n) => n * 2) // => [0, 2, 4, 6, 8] + * ``` + * + * @see {@link range} — create a range of integers + * @see {@link replicate} — repeat a single value + * + * @category constructors + * @since 2.0.0 + */ +const makeBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (n, f) => { + const max = Math.max(1, Math.floor(n)); + const out = new Array(max); + for (let i = 0; i < max; i++) { + out[i] = f(i); + } + return out; +}))); +/** + * Creates a `NonEmptyArray` containing a range of integers, inclusive on both + * ends. + * + * **When to use** + * + * Use when you need a non-empty sequence of consecutive integers. + * + * **Details** + * + * If `start > end`, returns `[start]`. + * + * **Example** (Creating a range) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.range(1, 3) // => [1, 2, 3] + * ``` + * + * @see {@link makeBy} — generate values from a function + * + * @category constructors + * @since 2.0.0 + */ +const range = (start, end) => start <= end ? makeBy(end - start + 1, i => start + i) : [start]; +/** + * Creates a `NonEmptyArray` containing a value repeated `n` times. + * + * **When to use** + * + * Use when you need a non-empty array containing repeated copies of one value. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to 1, so this function + * always returns at least one element. Supports both data-first and data-last + * usage. + * + * **Example** (Repeating a value) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.replicate("a", 3) // => ["a", "a", "a"] + * ``` + * + * @see {@link makeBy} — vary values based on index + * + * @category constructors + * @since 2.0.0 + */ +const replicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (a, n) => makeBy(n, () => a)))); +/** + * 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 + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = collection => Array.isArray(collection) ? collection : Array.from(collection); +/** + * Normalizes a value that is either a single element or an array into an array. + * + * **When to use** + * + * Use to normalize input that may be a single value or an array into a consistent + * array. + * + * **Details** + * + * If the input is already an array, this returns it by reference. If the input + * is a single value, this wraps it in a one-element array. This is useful for + * APIs that accept `A | Array`. + * + * **Example** (Normalizing input) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.ensure("a") // => ["a"] + * Array.ensure(["a", "b", "c"]) // => ["a", "b", "c"] + * ``` + * + * @see {@link of} — always wrap in a single-element array + * @see {@link fromIterable} — convert any iterable + * + * @category constructors + * @since 3.3.0 + */ +const ensure = self => Array.isArray(self) ? self : [self]; +/** + * Converts a record into an array of `[key, value]` tuples. + * + * **When to use** + * + * Use to convert a record into an array of key-value tuples for iteration or + * transformation. + * + * **Details** + * + * Key order follows `Object.entries` semantics. Empty records produce an empty + * array. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromRecord({ a: 1, b: 2, c: 3 }) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @see {@link Record.toEntries} the equivalent function from the Record module + * @see {@link Record.fromEntries} to build a record from an array of tuples + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = _Record_js__rspack_import_0/* .toEntries */.Wo; +/** + * Converts an `Option` to an array: `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use to convert a single `Option` into an array for downstream array operations. + * + * **Example** (Converting an Option to an array) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.fromOption(Option.some(1)) // => [1] + * Array.fromOption(Option.none()) // => [] + * ``` + * + * @see {@link getSomes} — extract `Some` values from an array of Options + * + * @category converting + * @since 2.0.0 + */ +const fromOption = _Option_js__rspack_import_1.toArray; +/** + * Pattern-matches on an array, handling empty and non-empty cases separately. + * + * **When to use** + * + * Use when you need to branch on whether an array is empty. + * + * **Details** + * + * `onNonEmpty` receives a `NonEmptyReadonlyArray`. Supports both data-first and + * data-last usage. + * + * **Example** (Branching on emptiness) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const describe = Array.match({ + * onEmpty: () => "empty", + * onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}` + * }) + * + * describe([]) // => "empty" + * describe([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link matchLeft} — destructures into head + tail + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(self) : onEmpty()))); +/** + * Pattern-matches on an array from the left, providing the first element and + * the remaining elements separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * first element plus the remaining elements. + * + * **Details** + * + * `onNonEmpty` receives `(head, tail)` where `tail` is the rest of the array. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchLeft = Array.matchLeft({ + * onEmpty: () => "empty", + * onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}` + * }) + * + * matchLeft([]) // => "empty" + * matchLeft([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const matchLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(headNonEmpty(self), tailNonEmpty(self)) : onEmpty()))); +/** + * Pattern-matches on an array from the right, providing all elements except the + * last and the last element separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * elements before the last plus the last element. + * + * **Details** + * + * `onNonEmpty` receives `(init, last)` where `init` is everything but the last element. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchRight = Array.matchRight({ + * onEmpty: () => "empty", + * onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}` + * }) + * + * matchRight([]) // => "empty" + * matchRight([1, 2, 3]) // => "init: 2, last: 3" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchLeft} — destructures into head + tail + * + * @category pattern matching + * @since 2.0.0 + */ +const matchRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self)) : onEmpty()))); +/** + * Adds a single element to the front of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * leading value. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prepend([2, 3, 4], 1) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add to the end + * @see {@link prependAll} — prepend multiple elements + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => [head, ...self]))); +/** + * Prepends all elements from a prefix iterable to the front of an array. + * + * **When to use** + * + * Use to prepend multiple elements from an iterable to the front of an array. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Prepending multiple elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prependAll([2, 3], [0, 1]) // => [0, 1, 2, 3] + * ``` + * + * @see {@link prepend} — add a single element to the front + * @see {@link appendAll} — add elements to the end + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromIterable(that).concat(fromIterable(self))))); +/** + * Adds a single element to the end of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * trailing value. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.append([1, 2, 3], 4) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} — add to the front + * @see {@link appendAll} — append multiple elements + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => [...self, last]))); +/** + * Concatenates two iterables into a single array. + * + * **When to use** + * + * Use to combine two iterable inputs into a new array with the second input's + * elements after the first. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Concatenating arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.appendAll([1, 2], [3, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add a single element to the end + * @see {@link prependAll} — add elements to the front + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => fromIterable(self).concat(fromIterable(that))); +/** + * Folds left-to-right while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator where each intermediate value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it starts with the initial + * value. The result is always a `NonEmptyArray`. Use `reduce` if you only need + * the final accumulated value. + * + * **Example** (Running totals) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [0, 1, 3, 6, 10] + * ``` + * + * @see {@link scanRight} — right-to-left scan + * @see {@link reduce} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const out = [b]; + let i = 0; + for (const a of self) { + out[i + 1] = f(out[i], a); + i++; + } + return out; +}))); +/** + * Folds right-to-left while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator from right to left where each intermediate + * value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it ends with the initial + * value. The result is always a `NonEmptyArray`. + * + * **Example** (Scanning running totals in reverse) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [10, 9, 7, 4, 0] + * ``` + * + * @see {@link scan} — left-to-right scan + * @see {@link reduceRight} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scanRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const input = fromIterable(self); + const out = new Array(input.length + 1); + out[input.length] = b; + for (let i = input.length - 1; i >= 0; i--) { + out[i] = f(out[i + 1], input[i]); + } + return out; +}))); +/** + * Checks whether a value is an `Array`. + * + * **When to use** + * + * Use to verify a value is a mutable array, narrowing its type to `Array`. + * + * **Details** + * + * Acts as a type guard narrowing the input to `Array` and delegates to + * `globalThis.Array.isArray`. + * + * **Example** (Type-guarding an unknown value) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArray(null) // => false + * Array.isArray([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayEmpty} — check for an empty array + * @see {@link isArrayNonEmpty} — check for a non-empty array + * + * @category guards + * @since 2.0.0 + */ +const isArray = Array.isArray; +/** + * Checks whether a mutable `Array` is empty, narrowing the type to `[]`. + * + * **Example** (Checking for an empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayEmpty([]) // => true + * Array.isArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isReadonlyArrayEmpty} — readonly variant + * @see {@link isArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayEmpty = self => self.length === 0; +/** + * Checks whether a `ReadonlyArray` is empty, narrowing the type to `readonly []`. + * + * **Example** (Checking for an empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayEmpty([]) // => true + * Array.isReadonlyArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isArrayEmpty} — mutable variant + * @see {@link isReadonlyArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayEmpty = (/* unused pure expression or super */ null && (isArrayEmpty)); +/** + * Checks whether a mutable `Array` is non-empty, narrowing the type to + * `NonEmptyArray`. + * + * **When to use** + * + * Use when you need the narrowed value to remain a mutable `Array` after proving + * it has at least one element. + * + * **Example** (Checking for a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayNonEmpty([]) // => false + * Array.isArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isReadonlyArrayNonEmpty} — readonly variant + * @see {@link isArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Checks whether a `ReadonlyArray` is non-empty, narrowing the type to + * `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use when you need to prove a readonly array has at least one element without + * requiring mutable array methods afterward. + * + * **Example** (Checking for a non-empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayNonEmpty([]) // => false + * Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayNonEmpty} — mutable variant + * @see {@link isReadonlyArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Returns the number of elements in a `ReadonlyArray`. + * + * **When to use** + * + * Use when you need length as a composable function rather than a property access. + * + * **Example** (Getting the length) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.length([1, 2, 3]) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const length = self => self.length; +/** @internal */ +function isOutOfBounds(i, as) { + return !Number.isFinite(i) || i < 0 || i >= as.length; +} +const clamp = (i, as) => Math.floor(Math.min(Math.max(0, i), as.length)); +/** + * Reads an element at the given index safely, returning `Option.some` or + * `Option.none` if the index is out of bounds. + * + * **When to use** + * + * Use when you need to read an array element by index and handle an + * out-of-bounds index as `Option.none`. + * + * **Details** + * + * The index is floored to an integer. This never throws. + * + * **Example** (Accessing indexes safely) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.get([1, 2, 3], 1) // => Option.some(2) + * Array.get([1, 2, 3], 10) // => Option.none() + * ``` + * + * @see {@link getUnsafe} for indexed access that throws when the index is out of bounds + * @see {@link head} for reading the first element as an `Option` + * @see {@link last} for reading the last element as an `Option` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + return isOutOfBounds(i, self) ? Option.none() : Option.some(self[i]); +}))); +/** + * Reads an element at the given index, throwing if the index is out of bounds. + * + * **When to use** + * + * Use to read an array element at a known valid index when out-of-bounds would + * be a programming error. + * + * **Details** + * + * Throws an `Error` with the message `"Index out of bounds: "`. Prefer + * `get` for safe access. + * + * **Example** (Accessing indexes unsafely) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.getUnsafe([1, 2, 3], 1) // => 2 + * // Array.getUnsafe([1, 2, 3], 10) // throws Error + * ``` + * + * @see {@link get} — safe version returning `Option` + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + if (isOutOfBounds(i, self)) { + throw new Error(`Index out of bounds: ${i}`); + } + return self[i]; +}))); +/** + * Splits a non-empty array into its first element and the remaining elements. + * + * **When to use** + * + * Use when you have a `NonEmptyReadonlyArray` and need both its first element + * and the remaining elements as separate values. + * + * **Details** + * + * Returns a tuple `[head, tail]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unprepend([1, 2, 3, 4]) // => [1, [2, 3, 4]] + * ``` + * + * @see {@link unappend} for splitting a non-empty array into init and last + * @see {@link headNonEmpty} for getting only the first element + * @see {@link tailNonEmpty} for getting only the elements after the first + * + * @category splitting + * @since 2.0.0 + */ +const unprepend = self => [headNonEmpty(self), tailNonEmpty(self)]; +/** + * Splits a non-empty array into all elements except the last, and the last + * element. + * + * **When to use** + * + * Use when you need to split a non-empty array into the elements before the + * last element and the last element. + * + * **Details** + * + * Returns a tuple `[init, last]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unappend([1, 2, 3, 4]) // => [[1, 2, 3], 4] + * ``` + * + * @see {@link unprepend} for splitting a non-empty array into head and tail + * @see {@link initNonEmpty} for getting only the elements before the last + * @see {@link lastNonEmpty} for getting only the last element + * + * @category splitting + * @since 2.0.0 + */ +const unappend = self => [initNonEmpty(self), lastNonEmpty(self)]; +/** + * Returns the first element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the first element of an array that may be empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.head([1, 2, 3]) // => Option.some(1) + * Array.head([]) // => Option.none() + * ``` + * + * @see {@link headNonEmpty} — direct access when array is known non-empty + * @see {@link last} — get the last element + * + * @category getters + * @since 2.0.0 + */ +const head = /*#__PURE__*/(/* unused pure expression or super */ null && (get(0))); +/** + * Returns the first element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the first element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the head of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.headNonEmpty([1, 2, 3, 4]) // => 1 + * ``` + * + * @see {@link head} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const headNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (getUnsafe(0))); +/** + * Returns the last element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the last element of an array that may be empty. + * + * **Example** (Getting the last element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.last([1, 2, 3]) // => Option.some(3) + * Array.last([]) // => Option.none() + * ``` + * + * @see {@link lastNonEmpty} — direct access when array is known non-empty + * @see {@link head} — get the first element + * + * @category getters + * @since 2.0.0 + */ +const last = self => isReadonlyArrayNonEmpty(self) ? Option.some(lastNonEmpty(self)) : Option.none(); +/** + * Returns the last element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the last element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the last of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.lastNonEmpty([1, 2, 3, 4]) // => 4 + * ``` + * + * @see {@link last} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const lastNonEmpty = self => self[self.length - 1]; +/** + * Returns all elements except the first safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements after the first when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(1)`. Empty inputs return `Option.none()`. + * + * **Example** (Getting the tail) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.tail([1, 2, 3, 4]) // => Option.some([2, 3, 4]) + * Array.tail([]) // => Option.none() + * ``` + * + * @see {@link tailNonEmpty} — when the array is known non-empty + * @see {@link init} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +function tail(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(tailNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the first of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements after the first when the array is known to be non-empty. + * + * **Example** (Getting the tail of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.tailNonEmpty([1, 2, 3, 4]) // => [2, 3, 4] + * ``` + * + * @see {@link tail} — safe version for possibly-empty arrays + * @see {@link initNonEmpty} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +const tailNonEmpty = self => self.slice(1); +/** + * Returns all elements except the last safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements before the last when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(0, -1)`. Empty inputs return + * `Option.none()`. + * + * **Example** (Getting init) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.init([1, 2, 3, 4]) // => Option.some([1, 2, 3]) + * Array.init([]) // => Option.none() + * ``` + * + * @see {@link initNonEmpty} — when the array is known non-empty + * @see {@link tail} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +function init(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(initNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the last of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements before the last when the array is known to be non-empty. + * + * **Example** (Getting init of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.initNonEmpty([1, 2, 3, 4]) // => [1, 2, 3] + * ``` + * + * @see {@link init} — safe version for possibly-empty arrays + * @see {@link tailNonEmpty} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +const initNonEmpty = self => self.slice(0, -1); +/** + * Keeps the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep up to the first `n` elements from an iterable as a new array. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.take([1, 2, 3, 4, 5], 3) // => [1, 2, 3] + * ``` + * + * @see {@link takeRight} for keeping elements from the end + * @see {@link takeWhile} for keeping an initial prefix while a predicate holds + * @see {@link drop} for removing elements from the start + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, clamp(n, input)); +}))); +/** + * Keeps the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the last `n` elements of an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeRight([1, 2, 3, 4, 5], 3) // => [3, 4, 5] + * ``` + * + * @see {@link take} — keep from the start + * @see {@link dropRight} — remove from the end + * + * @category getters + * @since 2.0.0 + */ +const takeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + const i = clamp(n, input); + return i === 0 ? [] : input.slice(-i); +}))); +/** + * Takes elements from the start while the predicate holds, stopping at the + * first element that fails. + * + * **When to use** + * + * Use to keep the leading elements of an iterable while each element satisfies + * a predicate, returning the retained prefix as an array. + * + * **Details** + * + * Supports refinements for type narrowing. The predicate receives + * `(element, index)`. + * + * **Example** (Taking while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4) // => [1, 3, 2] + * ``` + * + * @see {@link take} for keeping a fixed number of leading elements + * @see {@link dropWhile} for removing the matching prefix and keeping the rest + * @see {@link span} for splitting the matching prefix from the remaining elements + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + const out = []; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + out.push(a); + i++; + } + return out; +}))); +/** + * Takes elements from the start while a `Filter` succeeds, collecting transformed values. + * + * **When to use** + * + * Use when you need to take a prefix from an iterable while a function can + * successfully extract or transform elements, stopping at the first element + * that produces a failure result. + * + * **Details** + * + * The filter receives `(element, index)` and processing stops at the first + * filter failure. + * + * @see {@link takeWhile} for taking a prefix based on a boolean predicate + * + * @category getters + * @since 4.0.0 + */ +const takeWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + const out = []; + for (const a of self) { + const result = f(a, i); + if (Result.isFailure(result)) { + break; + } + out.push(result.success); + i++; + } + return out; +}))); +const spanIndex = (self, predicate) => { + let i = 0; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + i++; + } + return i; +}; +/** + * Splits an iterable into two arrays: the longest prefix where the predicate + * holds, and the remaining elements. + * + * **When to use** + * + * Use when you need both the longest predicate-matching prefix and the + * remaining elements. + * + * **Details** + * + * Equivalent to `[takeWhile(pred), dropWhile(pred)]`, but more efficient + * because it runs in a single pass. Supports refinements for type narrowing of + * the prefix. + * + * **Example** (Splitting at predicate boundary) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.span([1, 3, 2, 4, 5], (x) => x % 2 === 1) // => [[1, 3], [2, 4, 5]] + * ``` + * + * @see {@link takeWhile} for keeping only the matching prefix + * @see {@link dropWhile} for keeping only the elements after the matching prefix + * @see {@link splitWhere} for splitting at the first element that satisfies a predicate + * + * @category splitting + * @since 2.0.0 + */ +const span = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + return splitAt(input, spanIndex(input, predicate)); +}))); +/** + * Removes the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the suffix of an iterable after skipping a fixed number of + * leading elements. + * + * **Details** + * + * `n` is clamped to `[0, length]`. When `n <= 0`, this returns a copy of the + * full array. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.drop([1, 2, 3, 4, 5], 2) // => [3, 4, 5] + * ``` + * + * @see {@link dropRight} for removing a fixed number of elements from the end + * @see {@link dropWhile} for removing a prefix based on a predicate instead of a fixed count + * @see {@link take} for keeping a fixed number of elements from the start + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(clamp(n, input), input.length); +}))); +/** + * Removes the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to remove the last `n` elements from an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. + * + * **Example** (Dropping from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropRight([1, 2, 3, 4, 5], 2) // => [1, 2, 3] + * ``` + * + * @see {@link drop} — remove from the start + * @see {@link takeRight} — keep from the end + * + * @category getters + * @since 2.0.0 + */ +const dropRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, input.length - clamp(n, input)); +}))); +/** + * Drops elements from the start while the predicate holds, returning the rest. + * + * **When to use** + * + * Use to remove a leading prefix of elements that satisfy a predicate. + * + * **Details** + * + * The predicate receives `(element, index)`. + * + * **Example** (Dropping while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) // => [4, 5] + * ``` + * + * @see {@link takeWhile} — keep the matching prefix instead + * @see {@link drop} — drop a fixed count + * + * @category getters + * @since 2.0.0 + */ +const dropWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (!predicate(input[i], i)) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Drops elements from the start while a `Filter` succeeds. + * + * **When to use** + * + * Use when you need to drop a prefix from an iterable by computing a `Result` + * per element instead of using a simple boolean predicate. + * + * **Details** + * + * The filter receives `(element, index)`. The result contains the remaining + * original elements after the first filter failure. + * + * @see {@link dropWhile} for dropping a prefix with a simple boolean predicate + * @see {@link takeWhileFilter} for keeping only the matching prefix + * + * @category getters + * @since 4.0.0 + */ +const dropWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (Result.isFailure(f(input[i], i))) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Returns the index of the first element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the first matching element from the start of an + * iterable. + * + * **Example** (Finding an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstIndex([5, 3, 8, 9], (x) => x > 5) // => Option.some(2) + * ``` + * + * @see {@link findLastIndex} — search from the end + * @see {@link findFirst} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findFirstIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i)) { + return Option.some(i); + } + i++; + } + return Option.none(); +}))); +/** + * Returns the index of the last element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the last matching element from the end of an array. + * + * **Example** (Finding the last matching index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLastIndex([1, 3, 8, 9], (x) => x < 5) // => Option.some(1) + * ``` + * + * @see {@link findFirstIndex} — search from the start + * @see {@link findLast} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findLastIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + if (predicate(input[i], i)) { + return Option.some(i); + } + } + return Option.none(); +}))); +/** + * Returns the first element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to scan an iterable in iteration order and return the first selected + * element or mapped value as an `Option`. + * + * **Details** + * + * Accepts a predicate `(a, i) => boolean`, a refinement, or a function + * `(a, i) => Option` for simultaneous find-and-transform. If no element + * matches, this returns `Option.none()`. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some(4) + * ``` + * + * @see {@link findLast} — search from the end + * @see {@link findFirstIndex} — get the index instead + * @see {@link findFirstWithIndex} — get both element and index + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _Iterable_js__rspack_import_4/* .findFirst */.i8; +/** + * Returns the first selected value together with its index, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find both the first matching element and its index in one pass. + * + * **Details** + * + * Accepts a predicate, a refinement, or a function returning `Option`. For an + * `Option`-returning function, returns `[mappedValue, index]` for the first + * `Some`, or `Option.none()` if no element is selected. + * + * **Example** (Finding element with its index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some([4, 3]) + * ``` + * + * @see {@link findFirst} — get only the element + * @see {@link findFirstIndex} — get only the index + * + * @category searching + * @since 3.17.0 + */ +const findFirstWithIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some([a, i]); + } + } else { + if (Option.isSome(o)) { + return Option.some([o.value, i]); + } + } + i++; + } + return Option.none(); +}))); +/** + * Returns the last element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to find the last matching element from the end of an array. + * + * **Details** + * + * Searches from the end of the array. If no element matches, this returns + * `Option.none()`. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => Option.some(4) + * ``` + * + * @see {@link findFirst} — search from the start + * @see {@link findLastIndex} — get the index instead + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + const a = input[i]; + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some(a); + } + } else { + if (Option.isSome(o)) { + return o; + } + } + } + return Option.none(); +}))); +/** + * Inserts an element at the specified index safely, returning a new `NonEmptyArray` + * wrapped in an `Option`. + * + * **When to use** + * + * Use to insert a single element at a specific position in an array. + * + * **Details** + * + * Valid indices are `0` to `length`, inclusive. Inserting at `length` appends. + * + * **Example** (Inserting at an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.insertAt(["a", "b", "c", "e"], 3, "d") // => Option.some(["a", "b", "c", "d", "e"]) + * ``` + * + * @see {@link replace} — replace an existing element + * @see {@link modify} — transform an element at an index + * + * @category transforming + * @since 2.0.0 + */ +const insertAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => { + const out = Array.from(self); // copy because `splice` mutates the array + const index = Math.floor(i); + if (index !== out.length && isOutOfBounds(index, out)) { + return Option.none(); + } + out.splice(index, 0, b); + return Option.some(out); +}))); +/** + * Replaces the element at the specified index safely with a new value, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to set a fixed replacement value at a specific index. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Replacing an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.replace([1, 2, 3], 1, 4) // => Option.some([1, 4, 3]) + * ``` + * + * @see {@link modify} — transform an element with a function + * @see {@link insertAt} — insert without removing + * + * @category transforming + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => modify(self, i, () => b)))); +/** + * Applies a function to the element at the specified index safely, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to derive a replacement value from an array element at a specific index + * while leaving the other elements unchanged. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Modifying an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const values = [1, 2, 3, 4] + * const double = (n: number) => n * 2 + * + * Array.modify(values, 2, double) // => Option.some([1, 2, 6, 4]) + * Array.modify(values, 5, double) // => Option.none() + * ``` + * + * @see {@link replace} — set a fixed value at an index + * @see {@link modifyHeadNonEmpty} — modify the first element + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, f) => { + const arr = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, arr)) { + return Option.none(); + } + const out = arr; + const b = f(arr[index]); + out[index] = b; + return Option.some(out); +}))); +/** + * Removes the element at the specified index, returning a new array. If the + * index is out of bounds, returns a copy of the original. + * + * **When to use** + * + * Use when you want a missing index to be a no-op and need a fresh array result + * instead of an optional failure. + * + * **Example** (Removing an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.remove([1, 2, 3, 4], 2) // => [1, 2, 4] + * Array.remove([1, 2, 3, 4], 5) // => [1, 2, 3, 4] + * ``` + * + * @see {@link insertAt} — insert an element + * @see {@link filter} — remove elements by predicate + * + * @category transforming + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, i) => { + const out = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, out)) { + return out; + } + out.splice(index, 1); + return out; +}))); +/** + * Reverses an iterable into a new array. + * + * **When to use** + * + * Use to reverse an iterable into a new array without mutating the original + * input. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. + * + * **Example** (Reversing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reverse([1, 2, 3, 4]) // => [4, 3, 2, 1] + * ``` + * + * @category transforming + * @since 2.0.0 + */ +const reverse = self => Array.from(self).reverse(); +/** + * Sorts an array by the given `Order`, returning a new array. + * + * **When to use** + * + * Use to sort an array using a single `Order` comparator. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. Use `sortWith` to sort by a + * derived key, or `sortBy` for multi-key sorting. + * + * **Example** (Sorting numbers) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sort([3, 1, 4, 1, 5], Order.Number) // => [1, 1, 3, 4, 5] + * ``` + * + * @see {@link sortWith} — sort by a mapping function + * @see {@link sortBy} — sort by multiple orders + * + * @category sorting + * @since 2.0.0 + */ +const sort = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => { + const out = Array.from(self); + out.sort(O); + return out; +}))); +/** + * Sorts an array by a derived key using a mapping function and an `Order` for + * that key. + * + * **When to use** + * + * Use when you need to sort values by a derived key, such as a string length or + * object field, while keeping the original values. + * + * **Details** + * + * Equivalent to `sort(Order.mapInput(order, f))`, but more convenient. + * + * **Example** (Sorting strings by length) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sortWith(["aaa", "b", "cc"], (s) => s.length, Order.Number) // => ["b", "cc", "aaa"] + * ``` + * + * @see {@link sort} for sorting with an `Order` that compares the elements directly + * @see {@link sortBy} for sorting with multiple `Order`s applied in sequence + * + * @category sorting + * @since 2.0.0 + */ +const sortWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, f, order) => Array.from(self).map(a => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _)))); +/** + * Sorts an array by multiple `Order`s applied in sequence: the first order is + * used first; ties are broken by the second order, and so on. + * + * **When to use** + * + * Use to sort by multiple criteria where later orders break ties from earlier + * ones. + * + * **Details** + * + * This is data-last only and returns a function. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Sorting by multiple keys) + * + * ```ts import.meta.vitest + * import { Array, Order, pipe } from "effect" + * + * const users = [ + * { name: "Alice", age: 30 }, + * { name: "Bob", age: 25 }, + * { name: "Charlie", age: 30 } + * ] + * + * const sortedUsers = pipe( + * users, + * Array.sortBy( + * Order.mapInput(Order.Number, (user: (typeof users)[number]) => user.age), + * Order.mapInput(Order.String, (user: (typeof users)[number]) => user.name) + * ) + * ) + * + * sortedUsers.map((user) => user.name).join(",") // => "Bob,Alice,Charlie" + * ``` + * + * @see {@link sort} — sort by a single `Order` + * @see {@link sortWith} — sort by a derived key + * + * @category sorting + * @since 2.0.0 + */ +const sortBy = (...orders) => { + const sortByAll = sort(Order.combineAll(orders)); + return self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return sortByAll(input); + } + return []; + }; +}; +/** + * Pairs elements from two iterables by position. If the iterables differ in + * length, the extra elements from the longer one are discarded. + * + * **When to use** + * + * Use when you need simple pairs of corresponding elements from two iterables. + * + * **Details** + * + * Returns `NonEmptyArray` when both inputs are non-empty. + * + * **Example** (Zipping two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zip([1, 2, 3], ["a", "b"]) // => [[1, "a"], [2, "b"]] + * ``` + * + * @see {@link zipWith} — zip with a combiner function + * @see {@link unzip} — inverse operation + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Combines elements from two iterables pairwise using a function. If the + * iterables differ in length, extra elements are discarded. + * + * **When to use** + * + * Use when zipping two iterables in an array pipeline and each pair should + * become a computed array element instead of a tuple. + * + * **Example** (Zipping with addition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b) // => [5, 7, 9] + * ``` + * + * @see {@link zip} — zip into tuples + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => { + const as = fromIterable(self); + const bs = fromIterable(that); + if (isReadonlyArrayNonEmpty(as) && isReadonlyArrayNonEmpty(bs)) { + const out = [f(headNonEmpty(as), headNonEmpty(bs))]; + const len = Math.min(as.length, bs.length); + for (let i = 1; i < len; i++) { + out[i] = f(as[i], bs[i]); + } + return out; + } + return []; +}))); +/** + * Splits an array of pairs into two arrays. Inverse of {@link zip}. + * + * **Example** (Unzipping pairs) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unzip([[1, "a"], [2, "b"], [3, "c"]]) // => [[1, 2, 3], ["a", "b", "c"]] + * ``` + * + * @see {@link zip} — combine two arrays into pairs + * + * @category zipping + * @since 2.0.0 + */ +const unzip = self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const fa = [input[0][0]]; + const fb = [input[0][1]]; + for (let i = 1; i < input.length; i++) { + fa[i] = input[i][0]; + fb[i] = input[i][1]; + } + return [fa, fb]; + } + return [[], []]; +}; +/** + * Places a separator element between every pair of elements. + * + * **When to use** + * + * Use to insert a separator between elements, for example when preparing data for display or concatenation. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Empty inputs produce an empty + * result. + * + * **Example** (Interspersing a separator) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersperse([1, 2, 3], 0) // => [1, 0, 2, 0, 3] + * ``` + * + * @see {@link join} — intersperse and join into a string + * + * @category transforming + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const tail = tailNonEmpty(input); + for (let i = 0; i < tail.length; i++) { + if (i < tail.length) { + out.push(middle); + } + out.push(tail[i]); + } + return out; + } + return []; +}))); +/** + * Applies a function to the first element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use to transform the first element of a non-empty array while preserving the rest. + * + * **Example** (Modifying the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyHeadNonEmpty([1, 2, 3], (n) => n * 10) // => [10, 2, 3] + * ``` + * + * @see {@link setHeadNonEmpty} — replace with a fixed value + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 4.0.0 + */ +const modifyHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => [f(headNonEmpty(self)), ...tailNonEmpty(self)]))); +/** + * Replaces the first element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current first element. + * + * **Example** (Setting the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setHeadNonEmpty([1, 2, 3], 10) // => [10, 2, 3] + * ``` + * + * @see {@link modifyHeadNonEmpty} — transform the head with a function + * @see {@link setLastNonEmpty} — replace the last element + * + * @category transforming + * @since 4.0.0 + */ +const setHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyHeadNonEmpty(self, () => b)))); +/** + * Applies a function to the last element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use when you already know the array is non-empty and the new last element + * depends on the current last element. + * + * **Example** (Modifying the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyLastNonEmpty([1, 2, 3], (n) => n * 2) // => [1, 2, 6] + * ``` + * + * @see {@link setLastNonEmpty} — replace with a fixed value + * @see {@link modifyHeadNonEmpty} — modify the first element + * + * @category transforming + * @since 4.0.0 + */ +const modifyLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => append(initNonEmpty(self), f(lastNonEmpty(self)))))); +/** + * Replaces the last element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current last element. + * + * **Example** (Setting the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setLastNonEmpty([1, 2, 3], 4) // => [1, 2, 4] + * ``` + * + * @see {@link modifyLastNonEmpty} — transform the last element with a function + * @see {@link setHeadNonEmpty} — replace the first element + * + * @category transforming + * @since 4.0.0 + */ +const setLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyLastNonEmpty(self, () => b)))); +/** + * Transforms an array by rotating it `n` steps. Positive `n` rotates right; negative `n` + * rotates left. + * + * **When to use** + * + * Use when elements should wrap around the end of the array rather than being + * dropped. + * + * **Details** + * + * `n` is rounded to the nearest integer before rotating. The return type + * preserves `NonEmptyArray`. Empty arrays, or rotations normalized to `0`, + * return a copy. + * + * **Example** (Rotating elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.rotate(["a", "b", "c", "d"], 2) // => ["c", "d", "a", "b"] + * ``` + * + * @see {@link take} for taking a fixed number of elements from the start + * @see {@link drop} for dropping a fixed number of elements from the start + * + * @category transforming + * @since 2.0.0 + */ +const rotate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const len = input.length; + const m = Math.round(n) % len; + if (isOutOfBounds(Math.abs(m), input) || m === 0) { + return copy(input); + } + if (m < 0) { + const [f, s] = splitAtNonEmpty(input, -m); + return appendAll(s, f); + } else { + return rotate(input, m - len); + } + } + return []; +}))); +/** + * Returns a membership-test function using a custom equivalence. + * + * **When to use** + * + * Use when checking membership with caller-provided equality instead of + * `Equal.equivalence()`. + * + * **Example** (Checking with custom equality) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * const containsNumber = Array.containsWith((a: number, b: number) => a === b) + * + * pipe([1, 2, 3, 4], containsNumber(3)) // => true + * ``` + * + * @see {@link contains} for the `Equal.equivalence()` variant + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an array contains a value, using `Equal.equivalence()` for + * comparison. + * + * **When to use** + * + * Use to check whether an iterable contains a value using Effect's default + * equality instead of providing a comparison function. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe(["a", "b", "c", "d"], Array.contains("c")) // => true + * ``` + * + * @see {@link containsWith} — use custom equality + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Applies a function repeatedly to consume prefixes of the array and collect + * the values it produces. + * + * **When to use** + * + * Use when you need custom grouping logic where each step returns both a value + * and the remaining input. + * + * **Details** + * + * The function receives a `NonEmptyReadonlyArray` and returns `[value, rest]`. + * Processing continues until the remaining array is empty. + * + * **Example** (Chopping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chop([1, 2, 3, 4, 5], (as): [number, Array] => [as[0] * 2, as.slice(1)]) // => [2, 4, 6, 8, 10] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * @see {@link splitAt} — split at an index + * + * @category splitting + * @since 2.0.0 + */ +const chop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const [b, rest] = f(input); + const out = [b]; + let next = rest; + while (internalArray.isArrayNonEmpty(next)) { + const [b, rest] = f(next); + out.push(b); + next = rest; + } + return out; + } + return []; +}))); +/** + * Splits an iterable into two arrays at the given index. + * + * **When to use** + * + * Use to divide an array into a prefix and suffix at a specific position. + * + * **Details** + * + * `n` can be `0`, in which case all elements are placed in the second array. + * The index is floored to an integer. + * + * **Example** (Splitting at an index) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAt([1, 2, 3, 4, 5], 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link splitAtNonEmpty} — for non-empty arrays + * @see {@link splitWhere} — split at a predicate boundary + * + * @category splitting + * @since 2.0.0 + */ +const splitAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = Array.from(self); + const _n = Math.floor(n); + if (isReadonlyArrayNonEmpty(input)) { + if (_n >= 1) { + return splitAtNonEmpty(input, _n); + } + return [[], input]; + } + return [input, []]; +}))); +/** + * Splits a non-empty array into two parts at the given index. The first part + * is guaranteed to be non-empty (`n` is clamped to >= 1). + * + * **When to use** + * + * Use when downstream code requires the left side of the split to contain at + * least one element. + * + * **Example** (Splitting a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAtNonEmpty(["a", "b", "c", "d", "e"], 3) // => [["a", "b", "c"], ["d", "e"]] + * ``` + * + * @see {@link splitAt} — for possibly-empty arrays + * + * @category splitting + * @since 4.0.0 + */ +const splitAtNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const _n = Math.max(1, Math.floor(n)); + return _n >= self.length ? [copy(self), []] : [prepend(self.slice(1, _n), headNonEmpty(self)), self.slice(_n)]; +}))); +/** + * Splits an iterable into `n` roughly equal-sized chunks. + * + * **When to use** + * + * Use to distribute elements across a fixed number of groups, such as when splitting work across threads. + * + * **Details** + * + * Uses `chunksOf(ceil(length / n))` internally. The last chunk may be shorter. + * + * **Example** (Splitting into groups) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3) // => [[1, 2, 3], [4, 5, 6], [7, 8]] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * + * @category splitting + * @since 2.0.0 + */ +const split = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return chunksOf(input, Math.ceil(input.length / Math.floor(n))); +}))); +/** + * Splits an iterable at the first element matching the predicate. The matching + * element is included in the second array. + * + * **When to use** + * + * Use when you need to split an array at the first element that marks a + * condition boundary. + * + * **Example** (Splitting at a condition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link span} — splits at the first element that fails the predicate + * @see {@link splitAt} — split at a fixed index + * + * @category splitting + * @since 2.0.0 + */ +const splitWhere = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => span(self, (a, i) => !predicate(a, i))))); +/** + * Creates a shallow copy of an array. + * + * **When to use** + * + * Use to create a distinct array reference for an existing array, for example + * before mutating the returned array. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Use this when you need a distinct + * reference, for example before mutating the returned array. + * + * **Example** (Copying an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const original = [1, 2, 3] + * const copied = Array.copy(original) + * + * copied // => [1, 2, 3] + * original === copied // => false + * ``` + * + * @see {@link fromIterable} — returns the same reference for arrays + * + * @category transforming + * @since 2.0.0 + */ +const copy = self => self.slice(); +/** + * Pads or truncates an array to exactly `n` elements, filling with `fill` + * if the array is shorter, or slicing if longer. + * + * **When to use** + * + * Use to ensure an array has a specific length, padding with a fill value or truncating as needed. + * + * **Details** + * + * Returns an empty array when `n <= 0`. + * + * **Example** (Padding an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.pad([1, 2, 3], 6, 0) // => [1, 2, 3, 0, 0, 0] + * ``` + * + * @see {@link take} — truncate without padding + * @see {@link replicate} — create an array of a single repeated value + * + * @category transforming + * @since 3.8.4 + */ +const pad = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, n, fill) => { + if (self.length >= n) { + return take(self, n); + } + return appendAll(self, makeBy(n - self.length, () => fill)); +}))); +/** + * Splits an iterable into chunks of length `n`. The last chunk may be shorter + * if `n` does not evenly divide the length. + * + * **When to use** + * + * Use to divide an iterable into a new array of non-overlapping chunks with a + * maximum chunk size. + * + * **Details** + * + * `chunksOf(n)([])` is `[]`, not `[[]]`. Each chunk is a `NonEmptyArray`, and + * the outer return type preserves `NonEmptyArray`. + * + * **Example** (Chunking an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chunksOf([1, 2, 3, 4, 5], 2) // => [[1, 2], [3, 4], [5]] + * ``` + * + * @see {@link split} — split into a given number of groups + * @see {@link window} — sliding windows + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return chop(input, splitAtNonEmpty(n)); + } + return []; +}))); +/** + * Creates overlapping sliding windows of size `n`. + * + * **When to use** + * + * Use to process sequences with a moving window, such as for computing running averages or detecting patterns. + * + * **Details** + * + * Returns an empty array if `n <= 0` or the array has fewer than `n` elements. + * Each window is a tuple of exactly `n` elements. + * + * **Example** (Creating sliding windows) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const values = [1, 2, 3, 4, 5] + * + * Array.window(values, 3) // => [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + * Array.window(values, 6) // => [] + * ``` + * + * @see {@link chunksOf} — non-overlapping chunks + * + * @category splitting + * @since 3.13.2 + */ +const window = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (n > 0 && isReadonlyArrayNonEmpty(input)) { + return Array.from({ + length: input.length - (n - 1) + }, (_, index) => input.slice(index, index + n)); + } + return []; +}))); +/** + * Groups consecutive equal elements using a custom equivalence function. + * + * **When to use** + * + * Use when you already have a non-empty array arranged so matching elements are + * adjacent and need a custom equivalence function. + * + * **Details** + * + * Only adjacent elements are grouped. Non-adjacent duplicates stay separate. + * Requires a `NonEmptyReadonlyArray`. + * + * **Example** (Grouping consecutive equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.groupWith( + * ["a", "a", "b", "b", "b", "c", "a"], + * (x, y) => x === y + * ) // => [["a", "a"], ["b", "b", "b"], ["c"], ["a"]] + * ``` + * + * @see {@link group} for grouping adjacent elements with `Equal.equivalence()` + * @see {@link groupBy} for grouping all elements into a record by key, regardless of adjacency + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => chop(self, as => { + const h = headNonEmpty(as); + const out = [h]; + let i = 1; + for (; i < as.length; i++) { + const a = as[i]; + if (isEquivalent(a, h)) { + out.push(a); + } else { + break; + } + } + return [out, as.slice(i)]; +})))); +/** + * Groups consecutive equal elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you already have adjacent equal values and Effect's default equality + * is the right comparison. + * + * **Details** + * + * Only adjacent elements are grouped. + * + * **Example** (Grouping adjacent equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.group([1, 1, 2, 2, 2, 3, 1]) // => [[1, 1], [2, 2, 2], [3], [1]] + * ``` + * + * @see {@link groupWith} — use custom equality + * @see {@link groupBy} — group by a key function into a record + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups elements into a record by a key-returning function. Each key maps + * to a `NonEmptyArray` of elements that produced that key. + * + * **When to use** + * + * Use to build buckets of elements indexed by a computed string or symbol key. + * + * **Details** + * + * Unlike `group` and `groupWith`, elements do not need to be adjacent to be + * grouped together. The key function must return a `string` or `symbol`. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a property) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const people = [ + * { name: "Alice", group: "A" }, + * { name: "Bob", group: "B" }, + * { name: "Charlie", group: "A" } + * ] + * + * Object.keys(Array.groupBy(people, (person) => person.group)).join(",") // => "A,B" + * ``` + * + * @see {@link group} — group adjacent equal elements + * @see {@link groupWith} — group adjacent elements by custom equality + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const hashBucketsAdd = (buckets, value) => { + const hash = _Hash_js__rspack_import_5/* .hash */.tW(value); + const bucket = buckets.get(hash); + if (bucket === undefined) { + buckets.set(hash, [value]); + return true; + } + // Hash collisions still require an Effect equality check. + for (const previous of bucket) { + if (_Equal_js__rspack_import_6/* .equals */.aI(previous, value)) { + return false; + } + } + bucket.push(value); + return true; +}; +const makeHashBuckets = values => { + const buckets = new Map(); + for (const value of values) { + hashBucketsAdd(buckets, value); + } + return buckets; +}; +const hashBucketsHas = (buckets, value) => { + const bucket = buckets.get(Hash.hash(value)); + if (bucket === undefined) { + return false; + } + for (const candidate of bucket) { + if (Equal.equals(candidate, value)) { + return true; + } + } + return false; +}; +/** + * Computes the union of two arrays using a custom equivalence, removing + * duplicates. + * + * **When to use** + * + * Use when you need the union of two arrays but duplicate detection must use a + * custom equivalence instead of the default `Equal.equivalence()`. + * + * **Example** (Computing unions with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unionWith([1, 2], [2, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link union} for the `Equal.equivalence()` variant + * @see {@link intersectionWith} for keeping elements present in both arrays + * @see {@link differenceWith} for keeping elements present only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const unionWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, isEquivalent) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + if (isReadonlyArrayNonEmpty(b)) { + const dedupe = dedupeWith(isEquivalent); + return dedupe(appendAll(a, b)); + } + return a; + } + return b; +}))); +/** + * Computes the union of two arrays, removing duplicates using + * `Equal.equivalence()`. + * + * **Example** (Computing array unions) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.union([1, 2], [2, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link unionWith} — use custom equality + * @see {@link intersection} — elements in both arrays + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const union = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + return isReadonlyArrayNonEmpty(b) ? dedupe(appendAll(a, b)) : a; + } + return b; +}); +/** + * Computes the intersection of two arrays using a custom equivalence. Order is + * determined by the first array. + * + * **When to use** + * + * Use when you need to keep only values present in both arrays and equality + * must be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing intersections with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }] + * const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }] + * const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id + * + * Array.intersectionWith(isEquivalent)(array2)(array1) // => [{ id: 1 }, { id: 3 }] + * ``` + * + * @see {@link intersection} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link differenceWith} for keeping values only from the first array with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const intersectionWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => has(thatArray, a)); + }); +}; +/** + * Computes the intersection of two arrays using `Equal.equivalence()`. Order is + * determined by the first array. + * + * **When to use** + * + * Use when Effect equality is the right membership test and you want to keep + * values present in both inputs while preserving the first input's order. + * + * **Example** (Computing array intersections) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersection([1, 2, 3], [3, 4, 1]) // => [1, 3] + * ``` + * + * @see {@link intersectionWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0 || thatArray.length === 0) { + return []; + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => hashBucketsHas(buckets, value)); +}))); +/** + * Computes elements in the first array that are not in the second, using a + * custom equivalence. + * + * **When to use** + * + * Use when you need to keep only values from the first array and equality must + * be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing differences with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.differenceWith((a, b) => a === b)([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link difference} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link intersectionWith} for keeping values present in both arrays with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const differenceWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => !has(thatArray, a)); + }); +}; +/** + * Computes elements in the first array that are not in the second, using + * `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to keep values from the first array that are absent from + * the second and the default `Equal.equivalence()` comparison is appropriate. + * + * **Example** (Computing array differences) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.difference([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link differenceWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link intersection} — elements in both arrays + * + * @category set operations + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0) { + return []; + } + if (thatArray.length === 0) { + return selfArray.filter(() => true); + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => !hashBucketsHas(buckets, value)); +}))); +/** + * 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 + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => []; +/** + * Wraps a single value in a `NonEmptyArray`. + * + * **Example** (Creating a single-element array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.of(1) // => [1] + * ``` + * + * @see {@link make} — create from multiple values + * @see {@link empty} — create an empty array + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element using a function, returning a new array. + * + * **When to use** + * + * Use to transform each element independently while preserving the array shape. + * + * **Details** + * + * The function receives `(element, index)`. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Doubling values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6] + * ``` + * + * @see {@link flatMap} — map and flatten + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map(f)))); +/** + * Maps each element to an array and flattens the results into a single array. + * + * **When to use** + * + * Use to map each array element to zero or more values and concatenate the + * results in one pass. + * + * **Details** + * + * The function receives `(element, index)`. This returns `NonEmptyArray` when + * both the input and mapped arrays are non-empty. + * + * **Example** (Flat mapping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMap([1, 2, 3], (x) => [x, x * 2]) // => [1, 2, 2, 4, 3, 6] + * ``` + * + * @see {@link map} — transform without flattening + * @see {@link flatten} — flatten without mapping + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isReadonlyArrayEmpty(self)) { + return []; + } + const out = []; + for (let i = 0; i < self.length; i++) { + const inner = f(self[i], i); + for (let j = 0; j < inner.length; j++) { + out.push(inner[j]); + } + } + return out; +}))); +/** + * Flattens a nested array of arrays into a single array. + * + * **When to use** + * + * Use to collapse one level of nested arrays when no per-element mapping is + * needed. + * + * **Example** (Flattening nested arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatten([[1, 2], [], [3, 4], [], [5, 6]]) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @see {@link flatMap} — map then flatten in one step + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(identity))); +/** + * Extracts all `Some` values from an iterable of `Option`s, discarding `None`s. + * + * **When to use** + * + * Use to collect only present values from an iterable of `Option` values while + * discarding `None` values. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.getSomes([Option.some(1), Option.none(), Option.some(2)]) // => [1, 2] + * ``` + * + * @see {@link fromOption} — convert a single Option + * @see {@link getSuccesses} — extract successes from Results + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = []; + for (const a of self) { + if (Option.isSome(a)) { + out.push(a.value); + } + } + return out; +}; +/** + * Extracts all failure values from an iterable of `Result`s, discarding + * successes. + * + * **When to use** + * + * Use when you can drop the success channel and only need the failure + * payloads, not the original result wrappers. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getFailures([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => ["err"] + * ``` + * + * @see {@link getSuccesses} — extract success values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = []; + for (const a of self) { + if (Result.isFailure(a)) { + out.push(a.failure); + } + } + return out; +}; +/** + * Extracts all success values from an iterable of `Result`s, discarding + * failures. + * + * **When to use** + * + * Use when you can drop the failure channel and only need the success + * payloads, not the original result wrappers. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getSuccesses([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => [1, 2] + * ``` + * + * @see {@link getFailures} — extract failure values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = []; + for (const a of self) { + if (Result.isSuccess(a)) { + out.push(a.success); + } + } + return out; +}; +/** + * Keeps transformed values for elements where a `Filter` succeeds. + * + * **When to use** + * + * Use to filter an iterable with a `Result`-returning transformation while + * discarding failures. + * + * **Details** + * + * The filter receives `(element, index)`. Failures are discarded. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.filterMap([1, 2, 3, 4], (n) => n % 2 === 0 ? Result.succeed(n * 10) : Result.failVoid) // => [20, 40] + * ``` + * + * @see {@link filter} — keep original elements matching a predicate + * @see {@link partition} for keeping both failures and successes + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + const result = f(as[i], i); + if (Result.isSuccess(result)) { + out.push(result.success); + } + } + return out; +}))); +/** + * Keeps only elements satisfying a predicate (or refinement). + * + * **When to use** + * + * Use to filter an iterable into a new array of original elements that satisfy + * a boolean predicate or refinement. + * + * **Details** + * + * The predicate receives `(element, index)`. Refinements are supported for type + * narrowing. + * + * **Example** (Filtering even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.filter([1, 2, 3, 4], (x) => x % 2 === 0) // => [2, 4] + * ``` + * + * @see {@link partition} — split into matching and non-matching + * @see {@link filterMap} for transforming while filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + if (predicate(as[i], i)) { + out.push(as[i]); + } + } + return out; +}))); +/** + * Splits an iterable using a `Filter` into failures and successes. + * + * **When to use** + * + * Use to partition an iterable by evaluating each element with a + * `Result`-returning filter and keeping both failure and success values. + * + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a filter) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.partition([1, -2, 3], (n, i) => + * n > 0 ? Result.succeed(n + i) : Result.fail(`negative:${n}`) + * ) // => [["negative:-2"], [1, 5]] + * ``` + * + * @see {@link filter} — keep only matching elements + * @see {@link filterMap} for discarding failures + * @see {@link separate} — split an iterable of `Result` values + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, f) => { + const excluded = []; + const satisfying = []; + let i = 0; + for (const a of self) { + const result = f(a, i++); + if (_Result_js__rspack_import_7/* .isSuccess */.oJ(result)) { + satisfying.push(result.success); + } else { + excluded.push(result.failure); + } + } + return [excluded, satisfying]; +}); +/** + * Separates an iterable of `Result`s into failure values and success values. + * + * **When to use** + * + * Use to split an iterable of `Result` values into failure and success arrays. + * + * **Details** + * + * Returns `[failures, successes]`. This is equivalent to + * `partition(identity)`. + * + * **Example** (Separating Results) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.separate([Result.succeed(1), Result.fail("error"), Result.succeed(2)]) // => [["error"], [1, 2]] + * ``` + * + * @see {@link getFailures} — extract only failures + * @see {@link getSuccesses} — extract only successes + * @see {@link partition} for computing `Result` values while splitting + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Folds an iterable from left to right into a single value. + * + * **When to use** + * + * Use to combine all elements into one accumulated value from left to right. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Summing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduce([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduceRight} — fold from right to left + * @see {@link scan} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduce((b, a, i) => f(b, a, i), b)))); +/** + * Folds an iterable from right to left into a single value. + * + * **When to use** + * + * Use when you need to fold values from right to left. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Folding from right to left) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduce} — fold from left to right + * @see {@link scanRight} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduceRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduceRight((b, a, i) => f(b, a, i), b)))); +/** + * Lifts a predicate into an array: returns `[value]` if the predicate holds, + * `[]` otherwise. + * + * **Example** (Wrapping values conditionally) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const fromEven = Array.liftPredicate((n: number) => n % 2 === 0) + * + * fromEven(1) // => [] + * fromEven(2) // => [2] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = predicate => b => predicate(b) ? [b] : []; +/** + * Lifts an `Option`-returning function into one that returns an array: + * `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use when an optional parser or lookup should participate in array pipelines + * as zero-or-one results. + * + * **Example** (Lifting an Option function) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const parseNumber = Array.liftOption((s: string) => { + * const n = Number(s) + * return isNaN(n) ? Option.none() : Option.some(n) + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link liftPredicate} — lift a boolean predicate + * @see {@link liftResult} — lift a Result-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftOption = f => (...a) => fromOption(f(...a)); +/** + * Converts a nullable value to an array: `null`/`undefined` becomes `[]`, + * anything else becomes `[value]`. + * + * **When to use** + * + * Use to treat a nullable single value as zero or one array element. + * + * **Example** (Converting nullable values to an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromNullishOr(1) // => [1] + * Array.fromNullishOr(null) // => [] + * Array.fromNullishOr(undefined) // => [] + * ``` + * + * @see {@link liftNullishOr} — lift a nullable-returning function + * @see {@link fromOption} — convert from Option + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? empty() : [a]; +/** + * Lifts a nullable-returning function into one that returns an array: + * `null`/`undefined` becomes `[]`, anything else becomes `[value]`. + * + * **Example** (Lifting a nullable function) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const parseNumber = Array.liftNullishOr((s: string) => { + * const n = Number(s) + * return isNaN(n) ? null : n + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link fromNullishOr} — convert a single nullable value + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Maps each element with a nullable-returning function, keeping only non-null / + * non-undefined results. + * + * **When to use** + * + * Use when you need to map and filter in one step, where the mapper can return + * `null` or `undefined` to skip elements. + * + * **Example** (Flat mapping with nullable values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMapNullishOr([1, 2, 3], (n) => (n % 2 === 0 ? null : n)) // => [1, 3] + * ``` + * + * @see {@link flatMap} for mapping each element to an array and flattening + * @see {@link fromNullishOr} for converting a single nullable value to an array + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => fromNullishOr(f(a)))))); +/** + * Lifts a `Result`-returning function into one that returns an array: failures + * produce `[]`, successes produce `[value]`. + * + * **When to use** + * + * Use when a fallible parser or lookup should participate in array pipelines as + * zero-or-one results and the failure value should be discarded. + * + * **Example** (Lifting a Result function) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => + * isNaN(Number(s)) + * ? Result.fail(new Error("Not a number")) + * : Result.succeed(Number(s)) + * + * const liftedParseNumber = Array.liftResult(parseNumber) + * + * liftedParseNumber("42") // => [42] + * liftedParseNumber("not a number") // => [] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * @see {@link liftPredicate} — lift a boolean predicate + * + * @category lifting + * @since 4.0.0 + */ +const liftResult = f => (...a) => { + const e = f(...a); + return Result.isFailure(e) ? [] : [e.success]; +}; +/** + * Checks whether all elements satisfy the predicate. Supports refinements for + * type narrowing. + * + * **When to use** + * + * Use to check whether every array element satisfies a predicate, including + * refinement-based type narrowing. + * + * **Example** (Testing all elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.every([2, 4, 6], (x) => x % 2 === 0) // => true + * Array.every([2, 3, 6], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link some} — test if any element matches + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => self.every(refinement)))); +/** + * Checks whether at least one element satisfies the predicate. Narrows the type + * to `NonEmptyReadonlyArray` on success. + * + * **Example** (Testing for any match) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.some([1, 3, 4], (x) => x % 2 === 0) // => true + * Array.some([1, 3, 5], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link every} — test if all elements match + * @see {@link contains} — test for a specific value + * + * @category guards + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => self.some(predicate)))); +/** + * Applies a function to each suffix of the array (starting from each index), + * collecting the results. + * + * **When to use** + * + * Use when you need to compute a result from every suffix of an array, such as + * cumulative aggregations from each position. + * + * **Details** + * + * For index `i`, the function receives `self.slice(i)`. + * + * **Example** (Computing suffix lengths) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.extend([1, 2, 3], (as) => as.length) // => [3, 2, 1] + * ``` + * + * @see {@link scan} for keeping intermediate accumulator values during a fold + * + * @category mapping + * @since 2.0.0 + */ +const extend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map((_, i, as) => f(as.slice(i)))))); +/** + * Returns the minimum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the minimum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.min([3, 1, 2], Order.Number) // => 1 + * ``` + * + * @see {@link max} — find the maximum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.min(O))))); +/** + * Returns the maximum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the maximum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.max([3, 1, 2], Order.Number) // => 3 + * ``` + * + * @see {@link min} — find the minimum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.max(O))))); +/** + * Builds an array by repeatedly applying a function to a seed value. The + * function returns `Option.some([element, nextSeed])` to continue, or + * `Option.none()` to stop. + * + * **Example** (Generating a sequence) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.unfold(1, (n) => n <= 5 ? Option.some([n, n + 1]) : Option.none()) // => [1, 2, 3, 4, 5] + * ``` + * + * @see {@link makeBy} — generate from index + * @see {@link range} — generate a numeric range + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => { + const out = []; + let next = b; + while (true) { + const o = f(next); + if (Option.isNone(o)) { + break; + } + const [a, b] = o.value; + out.push(a); + next = b; + } + return out; +}; +/** + * Creates an `Order` for arrays based on an element `Order`. Arrays are + * compared element-wise; if all compared elements are equal, shorter arrays + * come first. + * + * **Example** (Comparing arrays) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * const arrayOrder = Array.makeOrder(Order.Number) + * + * arrayOrder([1, 2], [1, 3]) // => -1 + * ``` + * + * @see {@link makeEquivalence} — create an equivalence for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeOrder = _Order_js__rspack_import_8/* .Array */.O3; +/** + * Creates an `Equivalence` for arrays based on an element `Equivalence`. Two + * arrays are equivalent when they have the same length and all elements are + * pairwise equivalent. + * + * **Example** (Comparing arrays for equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const eq = Array.makeEquivalence((a, b) => a === b) + * + * eq([1, 2, 3], [1, 2, 3]) // => true + * ``` + * + * @see {@link makeOrder} — create an ordering for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = _Equivalence_js__rspack_import_9/* .Array */.O3; +/** + * Runs a side-effect for each element. The callback receives `(element, index)`. + * + * **When to use** + * + * Use to iterate over an array for side-effects only, when no transformed + * result is needed. + * + * **Example** (Iterating with side-effects) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const visited: Array = [] + * Array.forEach([1, 2, 3], (n) => visited.push(n)) + * + * visited // => [1, 2, 3] + * ``` + * + * @see {@link map} for transforming each element into a new array + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromIterable(self).forEach((a, i) => f(a, i))))); +/** + * Removes duplicates using a custom equivalence, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove all duplicate elements with a custom equivalence when default + * equality is not appropriate. + * + * **Example** (Deduplicating with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupe} — uses default equality + * @see {@link dedupeAdjacentWith} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const rest = tailNonEmpty(input); + for (const r of rest) { + if (out.every(a => !isEquivalent(r, a))) { + out.push(r); + } + } + return out; + } + return []; +}))); +/** + * Removes duplicates using `Equal.equivalence()`, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove repeated values from an iterable when Effect's default equality + * is the right comparison, preserving the first occurrence. + * + * **Example** (Removing duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupe([1, 2, 1, 3, 2, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link dedupeWith} — use custom equality + * @see {@link dedupeAdjacent} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupe = self => { + const input = fromIterable(self); + if (input.length < 2) { + return [...input]; + } + const buckets = new Map(); + const out = []; + for (const value of input) { + if (hashBucketsAdd(buckets, value)) { + out.push(value); + } + } + return out; +}; +/** + * Removes consecutive duplicate elements using a custom equivalence. + * + * **When to use** + * + * Use when consecutive duplicates should be collapsed using a custom + * equivalence, while equivalent values that appear later should remain in the + * result. + * + * **Details** + * + * Non-adjacent duplicates are preserved. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacent} — uses default equality + * @see {@link dedupeWith} — dedupes all duplicates, not just adjacent + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const out = []; + let lastA = Option.none(); + for (const a of self) { + if (Option.isNone(lastA) || !isEquivalent(a, lastA.value)) { + out.push(a); + lastA = Option.some(a); + } + } + return out; +}))); +/** + * Removes consecutive duplicate elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to collapse consecutive duplicates while preserving later + * non-consecutive repeats, and the default equality is sufficient. + * + * **Example** (Removing adjacent duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacent([1, 1, 2, 2, 3, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacentWith} — use custom equality + * @see {@link dedupe} — remove all duplicates + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Joins string elements with a separator. + * + * **Example** (Joining strings) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.join(["a", "b", "c"], "-") // => "a-b-c" + * ``` + * + * @see {@link intersperse} — insert separator elements without joining + * + * @category folding + * @since 2.0.0 + */ +const join = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sep) => fromIterable(self).join(sep)))); +/** + * Maps over an array while threading an accumulator through each step, returning both the final state and the mapped array. + * + * **When to use** + * + * Use when you need to map while threading state through each element and keep + * the final state. + * + * **Details** + * + * Combines `map` and `reduce` in a single pass. The callback receives the + * current state, element, and index, and returns `[nextState, mappedValue]`. + * The result is `[finalState, mappedArray]`. This can be used in both + * data-first and data-last style. + * + * **Example** (Running sum alongside mapped values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n]) // => [6, [1, 3, 6]] + * ``` + * + * @see {@link scan} — when you only need the accumulated results (not the final state) + * @see {@link reduce} — when you only need the final accumulated value + * + * @category folding + * @since 2.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, s, f) => { + let i = 0; + let s1 = s; + const out = []; + for (const a of self) { + const r = f(s1, a, i); + s1 = r[0]; + out.push(r[1]); + i++; + } + return [s1, out]; +}))); +/** + * Computes the cartesian product of two arrays, applying a combiner to each pair. + * + * **When to use** + * + * Use to compute every combination from two arrays and immediately transform + * each pair into a custom result. + * + * **Details** + * + * Produces every combination of an element from `self` with an element from + * `that`, so the result length is `self.length * that.length`. Iteration visits + * every element of `that` for each element of `self`. + * + * **Example** (Combining numbers and letters) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesianWith([1, 2], ["a", "b"], (a, b) => `${a}-${b}`) // => ["1-a", "1-b", "2-a", "2-b"] + * ``` + * + * @see {@link cartesian} for returning tuples instead of applying a combiner + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => flatMap(self, a => map(that, b => f(a, b)))))); +/** + * Computes the cartesian product of two arrays, returning all pairs as tuples. + * + * **When to use** + * + * Use when you need every `[a, b]` pair from two arrays as tuples. + * + * **Details** + * + * Produces every `[a, b]` combination of an element from `self` with an element + * from `that`, so the result length is `self.length * that.length`. + * + * **Example** (Generating all pairs from two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesian([1, 2], ["a", "b"]) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"]] + * ``` + * + * @see {@link cartesianWith} — apply a combiner to each pair + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do simulation" — an array comprehension pattern. + * + * **When to use** + * + * Use when you want array-comprehension style code with do notation. + * + * **Details** + * + * Use {@link bind} to introduce array variables and {@link let_ let} for plain + * values. Each `bind` produces the cartesian product of all bound variables, + * like nested loops. Use `filter` and `map` in the pipeline to add conditions + * and transformations. + * + * **Example** (Building array comprehensions with do notation) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 3, 5]), + * Array.bind("y", () => [2, 4, 6]), + * Array.filter(({ x, y }) => x < y), + * Array.map(({ x, y }) => [x, y] as const) + * ) // => [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]] + * ``` + * + * @see {@link bind} — introduce an array variable into the scope + * @see {@link bindTo} — start a pipeline by naming the first array + * @see {@link let_ let} — introduce a plain computed value + * + * @category constructors + * @since 3.2.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (of({}))); +/** + * Adds a new array variable to a do-notation scope, producing the cartesian product with all previous bindings. + * + * **When to use** + * + * Use to add another array-producing binding to an `Array.Do` pipeline, pairing + * each existing scope with every value returned by the callback. + * + * **Details** + * + * Each `bind` call adds a named property to the accumulated object. The + * callback receives the current scope and must return an array. This is + * equivalent to `flatMap` plus merging the new value into the scope object. + * + * **Example** (Binding two arrays) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 2]), + * Array.bind("y", () => ["a", "b"]) + * ) // => [{ x: 1, y: "a" }, { x: 1, y: "b" }, { x: 2, y: "a" }, { x: 2, y: "b" }] + * ``` + * + * @see {@link Do} — start a do-notation pipeline + * @see {@link bindTo} — name the first array in a pipeline + * @see {@link let_ let} — add a plain computed value + * + * @category sequencing + * @since 3.2.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bind(map, flatMap))); +/** + * Wraps each array element in an object with the given key, starting a do-notation scope. + * + * **When to use** + * + * Use when you already have an array and want to start a do-notation pipeline + * by naming each element. + * + * **Details** + * + * Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. This is an + * alternative to starting with `Do` plus `bind` when you already have an array. + * + * **Example** (Naming an existing array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.bindTo([1, 2, 3], "x") // => [{ x: 1 }, { x: 2 }, { x: 3 }] + * ``` + * + * @see {@link Do} — start with an empty scope + * @see {@link bind} — add another array variable to the scope + * + * @category mapping + * @since 3.2.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.let_(map))); + +const reducer = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make((a, b) => a.concat(b), []))); +/** + * Returns a `Reducer` that combines `ReadonlyArray` values by concatenation. + * + * @see {@link makeReducerConcat} — mutable `Array` variant + * + * @category folding + * @since 4.0.0 + */ +function getReadonlyReducerConcat() { + return reducer; +} +/** + * Returns a `Reducer` that combines `Array` values by concatenation. + * + * @see {@link getReadonlyReducerConcat} — readonly variant + * + * @category folding + * @since 4.0.0 + */ +function makeReducerConcat() { + return reducer; +} +/** + * Computes the number of elements in an iterable that satisfy a predicate. + * + * **When to use** + * + * Use when you need to count how many elements of an iterable satisfy a + * predicate. + * + * **Details** + * + * The predicate receives both the element and its index. Empty iterables return + * `0`. + * + * **Example** (Counting even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @see {@link filter} — when you need the matching elements, not just the count + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + const as = fromIterable(self); + for (let i = 0; i < as.length; i++) { + const a = as[i]; + if (f(a, i)) { + count++; + } + } + return count; +}))); +//# sourceMappingURL=Array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + CZ: isArrayNonEmpty, + ET: isReadonlyArrayNonEmpty, + Ie: empty, + KC: union, + Ts: fromIterable, + jB: partition, + of: of +}); + + +}, +"./node_modules/effect/dist/Cause.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/** + * Records the full reason an `Effect` failed. + * + * A `Cause` can contain typed failures, unexpected defects, interruptions, + * and annotations. Keeping those details together lets code inspect or format + * failures without first collapsing them to a single error value. This module + * includes the `Cause` and `Reason` data types, helpers for building and + * checking causes, and small error types used by several Effect APIs. + * + * @since 2.0.0 + */ + + + +/** + * Unique brand for `Cause` values, used for runtime type checks via {@link isCause}. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .CauseTypeId */.PX; +/** + * Unique brand for `Reason` values, used for runtime type checks via {@link isReason}. + * + * @category type IDs + * @since 4.0.0 + */ +const ReasonTypeId = _internal_core_js__rspack_import_0/* .CauseReasonTypeId */.B4; +/** + * Checks whether an arbitrary value is a `Cause`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isCause(Cause.fail("error")) // => true + * Cause.isCause("not a cause") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isCause = _internal_core_js__rspack_import_0/* .isCause */.Aj; +/** + * Checks whether an arbitrary value is a `Reason` (`Fail`, `Die`, or `Interrupt`). + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reason = Cause.fail("error").reasons[0] + * Cause.isReason(reason) // => true + * Cause.isReason("not a reason") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isReason = _internal_core_js__rspack_import_0/* .isCauseReason */.Wg; +/** + * Narrows a `Reason` to `Fail`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering fail reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const fails = cause.reasons.filter(Cause.isFailReason) + * fails[0].error // => "error" + * ``` + * + * @see {@link isDieReason} — narrow to `Die` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isFailReason = _internal_core_js__rspack_import_0/* .isFailReason */.lC; +/** + * Narrows a `Reason` to `Die`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Die` (defect) reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering die reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.die("defect") + * const dies = cause.reasons.filter(Cause.isDieReason) + * dies[0].defect // => "defect" + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isDieReason = _internal_core_js__rspack_import_0/* .isDieReason */.Xb; +/** + * Narrows a `Reason` to `Interrupt`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Interrupt` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering interrupt reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.interrupt(123) + * const interrupts = cause.reasons.filter(Cause.isInterruptReason) + * interrupts[0].fiberId // => 123 + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isDieReason} — narrow to `Die` + * + * @category guards + * @since 4.0.0 + */ +const isInterruptReason = _internal_core_js__rspack_import_0/* .isInterruptReason */.ik; +/** + * Creates a `Cause` from an array of `Reason` values. + * + * **When to use** + * + * Use when you already have individual reasons (e.g. from filtering or + * transforming another cause's `reasons` array) and need to wrap them back + * into a `Cause`. + * + * **Details** + * + * - Returns a new `Cause`. + * - An empty array produces a cause equivalent to `empty`. + * + * **Gotchas** + * + * The `reasons` array is stored as provided. Treat the array as immutable + * after passing it to this function. + * + * **Example** (Building a cause from reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reasons = [ + * Cause.makeFailReason("err1"), + * Cause.makeFailReason("err2") + * ] + * Cause.fromReasons(reasons) // => Cause.combine(Cause.fail("err1"), Cause.fail("err2")) + * ``` + * + * @see {@link combine} — merge two existing causes + * + * @category constructors + * @since 4.0.0 + */ +const fromReasons = _internal_core_js__rspack_import_0/* .causeFromReasons */.b5; +/** + * Represents a `Cause` with an empty `reasons` array. + * + * **When to use** + * + * Use to represent the absence of failure when constructing or combining + * causes. + * + * **Details** + * + * Represents the absence of failure. Combining any cause with `empty` via + * {@link combine} returns the original cause unchanged. + * + * **Example** (Combining with the empty cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.combine(Cause.empty, Cause.fail("boom")) // => Cause.fail("boom") + * ``` + * + * @see {@link combine} for merging causes where `empty` acts as the identity + * + * @category constructors + * @since 2.0.0 + */ +const empty = _internal_core_js__rspack_import_0/* .causeEmpty */.DH; +/** + * Creates a `Cause` containing a single `Fail` reason with the + * given typed error. + * + * **When to use** + * + * Use to construct a cause from an expected typed error. + * + * **Example** (Creating a fail cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.fail("Something went wrong") // => Cause.fromReasons([Cause.makeFailReason("Something went wrong")]) + * ``` + * + * @see {@link die} — for untyped defects + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .causeFail */.OE; +/** + * Creates a `Cause` containing a single `Die` reason with the + * given defect. + * + * **When to use** + * + * Use to construct a cause from an untyped defect or unexpected thrown value. + * + * **Example** (Creating a die cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .causeDie */.Iu; +/** + * Creates a `Cause` containing a single `Interrupt` reason, + * optionally carrying the interrupting fiber's ID. + * + * **Example** (Creating an interrupt cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.interrupt(123) // => Cause.fromReasons([Cause.makeInterruptReason(123)]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link die} — for untyped defects + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .causeInterrupt */.nIy; +/** + * Creates a standalone `Fail` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone typed failure reason for + * {@link fromReasons} or direct comparison. + * + * **Example** (Creating a Fail reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeFailReason("error") // => Cause.fail("error").reasons[0] + * ``` + * + * @see {@link makeDieReason} — create a `Die` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeFailReason = error => new core.Fail(error); +/** + * Creates a standalone `Die` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone defect reason for {@link fromReasons} or + * direct comparison. + * + * **Example** (Creating a Die reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeDieReason("bug") // => Cause.die("bug").reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeDieReason = defect => new core.Die(defect); +/** + * Creates a standalone `Interrupt` reason (not wrapped in a `Cause`), + * optionally carrying the interrupting fiber's ID. + * + * **When to use** + * + * Use when constructing a standalone interrupt reason for {@link fromReasons} + * or direct comparison. + * + * **Example** (Creating an Interrupt reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeInterruptReason(42) // => Cause.interrupt(42).reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeDieReason} — create a `Die` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeInterruptReason = _internal_effect_js__rspack_import_1/* .makeInterruptReason */.ORc; +/** + * Returns `true` if every reason in the cause is an `Interrupt` (and + * there is at least one reason). + * + * **When to use** + * + * Use when you need to detect failures caused only by interruption. + * + * **Example** (Checking interrupt-only causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterruptsOnly(Cause.interrupt(123)) // => true + * Cause.hasInterruptsOnly(Cause.fail("error")) // => false + * Cause.hasInterruptsOnly(Cause.empty) // => false + * ``` + * + * @see {@link hasInterrupts} — `true` if the cause contains *any* interrupts + * + * @category predicates + * @since 4.0.0 + */ +const hasInterruptsOnly = _internal_effect_js__rspack_import_1/* .hasInterruptsOnly */.nn5; +/** + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** + * + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. + * + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. + * + * **Example** (Mapping errors to uppercase) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const mapped = Cause.map(cause, (e) => e.toUpperCase()) + * const reason = mapped.reasons[0] + * if (Cause.isFailReason(reason)) { + * reason.error // => "ERROR" + * } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .causeMap */.O$X; +/** + * Merges two causes into a single cause whose `reasons` array is the union + * of both inputs (de-duplicated by value equality). + * + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. + * - If the result is structurally equal to `self`, `self` is returned + * (referential shortcut). + * + * **Example** (Combining two causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const combined = Cause.combine(Cause.fail("error1"), Cause.fail("error2")) + * combined // => Cause.fromReasons([Cause.makeFailReason("error1"), Cause.makeFailReason("error2")]) + * ``` + * + * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining + * + * @category combining + * @since 4.0.0 + */ +const combine = _internal_effect_js__rspack_import_1/* .causeCombine */.h2c; +/** + * Collapses a `Cause` into a single `unknown` value, picking the "most + * important" failure in this order: + * + * **When to use** + * + * Use to collapse a structured cause to the single value that synchronous and + * promise runners would throw. + * + * **Details** + * + * 1. First `Fail` error (the `E` value) + * 2. First `Die` defect + * 3. A generic `Error("All fibers interrupted without error")` for interrupt-only causes + * 4. A generic `Error("Empty cause")` for `empty` + * + * This is the function used by `Effect.runPromise` and `Effect.runSync` to + * decide what to throw. + * + * **Gotchas** + * + * This function is lossy. Use {@link prettyErrors} or iterate `cause.reasons` + * when you need all failures. + * + * **Example** (Squashing a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.squash(Cause.fail("error")) // => "error" + * Cause.squash(Cause.die("defect")) // => "defect" + * ``` + * + * @see {@link prettyErrors} — non-lossy conversion to `Array` + * @see {@link pretty} — human-readable string rendering + * + * @category destructors + * @since 2.0.0 + */ +const squash = _internal_effect_js__rspack_import_1/* .causeSquash */.ReC; +/** + * Returns `true` if the cause contains at least one `Fail` reason. + * + * **When to use** + * + * Use to check whether a cause includes typed failures before extracting, + * mapping, or rendering them. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasFails(Cause.fail("error")) // => true + * Cause.hasFails(Cause.die("defect")) // => false + * ``` + * + * @see {@link hasDies} — check for defects + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .hasFails */.myX; +/** + * Returns a `Result` whose success value is the first `Fail` reason in + * the cause, including its annotations. If the cause has no `Fail` reason, the + * failure value is the original cause narrowed to `Cause`, because it + * contains no typed error reasons. + * + * **When to use** + * + * Use when you need the full `Fail` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Fail reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findFail(Cause.fail("error")) // => Result.succeed(Cause.makeFailReason("error")) + * ``` + * + * @see {@link findError} — extract the unwrapped `E` value + * @see {@link findDie} — extract the first `Die` reason + * + * @category filtering + * @since 4.0.0 + */ +const findFail = _internal_effect_js__rspack_import_1/* .findFail */.QE5; +/** + * Returns a `Result` whose success value is the first typed error value `E` + * from a `Fail` reason in the cause. If the cause has no `Fail` reason, + * the failure value is the original cause narrowed to `Cause`, because + * it contains no typed error reasons. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as a `Result` + * that preserves the original cause when no match is found. + * + * **Example** (Extracting the first error value) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findError(Cause.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link findFail} — extract the full `Fail` reason + * @see {@link findErrorOption} — `Option`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .findError */.khU; +/** + * Returns the first typed error value `E` from a cause wrapped in + * `Option.some`, or `Option.none` if no `Fail` reason exists. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as an `Option`, + * discarding the original cause. + * + * **Example** (Extracting an error as Option) + * + * ```ts import.meta.vitest + * import { Cause, Option } from "effect" + * + * Cause.findErrorOption(Cause.fail("error")) // => Option.some("error") + * Cause.findErrorOption(Cause.die("defect")) // => Option.none() + * ``` + * + * @see {@link findError} — `Result`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .findErrorOption */.L$u; +/** + * Returns `true` if the cause contains at least one `Die` reason. + * + * **When to use** + * + * Use to check whether a cause includes defects before extracting or rendering + * them. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasDies(Cause.die("defect")) // => true + * Cause.hasDies(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasFails} — check for typed errors + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .hasDies */.gpn; +/** + * Returns a `Result` whose success value is the first `Die` reason in + * the cause, including its annotations. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the full `Die` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Die reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDie(Cause.die("defect")) // => Result.succeed(Cause.makeDieReason("defect")) + * ``` + * + * @see {@link findDefect} — extract the unwrapped defect value + * @see {@link findFail} — extract the first `Fail` reason + * + * @category filtering + * @since 4.0.0 + */ +const findDie = _internal_effect_js__rspack_import_1/* .findDie */.k7S; +/** + * Returns a `Result` whose success value is the first defect value from a + * `Die` reason in the cause. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the first defect value from a `Cause` as a `Result`, + * without the full `Die` reason. + * + * **Example** (Extracting the first defect) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDefect(Cause.die("defect")) // => Result.succeed("defect") + * ``` + * + * @see {@link findDie} — extract the full `Die` reason + * @see {@link findError} — extract the first typed error + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .findDefect */.BbX; +/** + * Returns `true` if the cause contains at least one `Interrupt` reason. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterrupts(Cause.interrupt(123)) // => true + * Cause.hasInterrupts(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasInterruptsOnly} — `true` only when *all* reasons are interrupts + * @see {@link hasFails} — check for typed errors + * @see {@link hasDies} — check for defects + * + * @category predicates + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .hasInterrupts */.prj; +/** + * Returns a `Result` whose success value is the first `Interrupt` reason + * in the cause, including its annotations. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need the first `Interrupt` reason from a `Cause`, including the + * fiber ID and annotations. + * + * **Example** (Extracting the first interrupt) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findInterrupt(Cause.interrupt(42)) // => Result.succeed(Cause.makeInterruptReason(42)) + * ``` + * + * @see {@link interruptors} — collect all interrupting fiber IDs as a `Set` + * + * @category filtering + * @since 4.0.0 + */ +const findInterrupt = _internal_effect_js__rspack_import_1/* .findInterrupt */.tU5; +/** + * Collects the defined fiber IDs from all `Interrupt` reasons in the + * cause into a `ReadonlySet`. Interrupt reasons without a `fiberId` are + * ignored. Returns an empty set when the cause has no interrupting fiber IDs. + * + * **When to use** + * + * Use when you need interrupting fiber IDs as a set, with absence represented + * as an empty set. + * + * **Example** (Collecting interruptors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.combine( + * Cause.interrupt(1), + * Cause.interrupt(2) + * ) + * + * Cause.interruptors(cause) // => new Set([1, 2]) + * ``` + * + * @see {@link filterInterruptors} — `Result`-based variant + * + * @category getters + * @since 2.0.0 + */ +const interruptors = _internal_effect_js__rspack_import_1/* .causeInterruptors */.h74; +/** + * Returns a `Result` whose success value is the set of defined fiber IDs from + * the cause's `Interrupt` reasons. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need absence of interrupt reasons to fail with the original + * cause. + * + * **Gotchas** + * + * Interrupt reasons without a `fiberId` still count as interrupts, so the + * function succeeds with an empty `Set` when every interrupt reason has an + * undefined fiber ID. + * + * **Example** (Extracting interruptors with Result) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.filterInterruptors(Cause.interrupt(1)) // => Result.succeed(new Set([1])) + * ``` + * + * @see {@link interruptors} — always-succeeding variant + * + * @category filtering + * @since 4.0.0 + */ +const filterInterruptors = _internal_effect_js__rspack_import_1/* .causeFilterInterruptors */.Bou; +/** + * Converts a `Cause` into an `Array` suitable for logging or + * rethrowing. + * + * **When to use** + * + * Use to convert every renderable failure in a cause into individual `Error` + * values before logging or rethrowing. + * + * **Details** + * + * Each `Fail` and `Die` reason is converted into a standard + * `Error`: + * + * - **Objects / Error instances** — `message`, `name`, `stack`, and `cause` + * are preserved. Extra enumerable properties are copied. Stack traces are + * cleaned up and enriched with span annotations when available. + * - **Strings** — used directly as the `Error` message. + * - **Other primitives** (`null`, `undefined`, numbers, …) — wrapped in an + * `Error` with message `"Unknown error: "`. + * + * `Interrupt` reasons are collected separately. If the cause contains + * **only** interrupts (no `Fail` or `Die`), a single `InterruptError` is + * returned whose `cause` lists the interrupting fiber IDs. + * + * An empty cause returns an empty array. + * + * **Example** (Converting a cause to errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.prettyErrors(Cause.fail(new Error("boom")))[0].message // => "boom" + * ``` + * + * @see {@link pretty} — renders the cause as a single string + * @see {@link squash} — lossy collapse to a single thrown value + * + * @category formatting + * @since 3.2.0 + */ +const prettyErrors = _internal_effect_js__rspack_import_1/* .causePrettyErrors */.RJ6; +/** + * Formats a `Cause` as a human-readable string for logging or debugging. + * + * **When to use** + * + * Use to render a whole cause as one human-readable string for logs or + * diagnostics. + * + * **Details** + * + * Delegates to {@link prettyErrors} to convert each reason to an `Error`, + * then joins their stack traces with newlines. Nested `Error.cause` chains + * are rendered inline with indentation: + * + * ```text + * ErrorName: message + * at ... + * at ... { + * [cause]: NestedError: message + * at ... + * } + * ``` + * + * Span annotations are appended to the relevant stack frames when available. + * + * **Gotchas** + * + * Rendering an empty cause produces an empty string because there are no + * errors to render. + * + * **Example** (Rendering a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.pretty(Cause.fail("something went wrong")).includes("something went wrong") // => true + * ``` + * + * @see {@link prettyErrors} — get the individual `Error` instances + * + * @category formatting + * @since 2.0.0 + */ +const pretty = _internal_effect_js__rspack_import_1/* .causePretty */.GyP; +/** + * Checks whether an arbitrary value is a `NoSuchElementError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isNoSuchElementError(new Cause.NoSuchElementError()) // => true + * Cause.isNoSuchElementError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isNoSuchElementError = _internal_core_js__rspack_import_0/* .isNoSuchElementError */.PW; +/** + * Unique brand for `NoSuchElementError`. + * + * @category type IDs + * @since 4.0.0 + */ +const NoSuchElementErrorTypeId = _internal_core_js__rspack_import_0/* .NoSuchElementErrorTypeId */.qB; +/** + * Constructs a `NoSuchElementError` with an optional message. + * + * **When to use** + * + * Use to create the error value for APIs that intentionally fail when an + * expected element is absent. + * + * **Example** (Creating a NoSuchElementError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.NoSuchElementError("Element not found").message // => "Element not found" + * ``` + * + * @see {@link isNoSuchElementError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const NoSuchElementError = _internal_core_js__rspack_import_0/* .NoSuchElementError */.Xm; +/** + * Checks whether an arbitrary value is a `Done` signal. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isDone(Cause.Done()) // => true + * Cause.isDone("not done") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isDone = _internal_core_js__rspack_import_0/* .isDone */.$L; +/** + * Unique brand for `Done` values. + * + * @category type IDs + * @since 4.0.0 + */ +const DoneTypeId = _internal_core_js__rspack_import_0/* .DoneTypeId */.q_; +/** + * Creates a `Done` signal with an optional value. + * + * **When to use** + * + * Use when you need to construct a low-level pull completion signal directly. + * + * @see {@link done} — create a failing `Effect` with `Done` + * + * @category constructors + * @since 4.0.0 + */ +const Done = _internal_core_js__rspack_import_0/* .Done */.RS; +/** + * Creates an Effect that fails with a `Done` error. Shorthand for + * `Effect.fail(Cause.Done(value))`. + * + * **When to use** + * + * Use when you model stream or queue completion through the error channel. + * + * **Example** (Failing with Done) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const program = Cause.done("finished") + * + * await Effect.runPromiseExit(program) // => Exit.fail(Cause.Done("finished")) + * ``` + * + * @see {@link Done} — create the signal value without an Effect + * + * @category constructors + * @since 4.0.0 + */ +const done = _internal_core_js__rspack_import_0/* .done */.Vw; +/** + * Unique brand for `TimeoutError`. + * + * @category type IDs + * @since 4.0.0 + */ +const TimeoutErrorTypeId = _internal_effect_js__rspack_import_1/* .TimeoutErrorTypeId */.DQo; +/** + * Checks whether an arbitrary value is a `TimeoutError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isTimeoutError(new Cause.TimeoutError()) // => true + * Cause.isTimeoutError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isTimeoutError = _internal_effect_js__rspack_import_1/* .isTimeoutError */.c8t; +/** + * Constructs a `TimeoutError` with an optional message. + * + * **Example** (Creating a TimeoutError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.TimeoutError("Operation timed out").message // => "Operation timed out" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const TimeoutError = _internal_effect_js__rspack_import_1/* .TimeoutError */.MUS; +/** + * Unique brand for `IllegalArgumentError`. + * + * @category type IDs + * @since 4.0.0 + */ +const IllegalArgumentErrorTypeId = _internal_effect_js__rspack_import_1/* .IllegalArgumentErrorTypeId */.t8c; +/** + * Checks whether an arbitrary value is an `IllegalArgumentError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isIllegalArgumentError(new Cause.IllegalArgumentError()) // => true + * Cause.isIllegalArgumentError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isIllegalArgumentError = _internal_effect_js__rspack_import_1/* .isIllegalArgumentError */._y; +/** + * Constructs an `IllegalArgumentError` with an optional message. + * + * **Example** (Creating an IllegalArgumentError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.IllegalArgumentError("Invalid argument").message // => "Invalid argument" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const IllegalArgumentError = _internal_effect_js__rspack_import_1/* .IllegalArgumentError */.qwd; +/** + * Checks whether an arbitrary value is an `ExceededCapacityError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isExceededCapacityError(new Cause.ExceededCapacityError()) // => true + * Cause.isExceededCapacityError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isExceededCapacityError = _internal_effect_js__rspack_import_1/* .isExceededCapacityError */.ASO; +/** + * Unique brand for `ExceededCapacityError`. + * + * @category type IDs + * @since 4.0.0 + */ +const ExceededCapacityErrorTypeId = _internal_effect_js__rspack_import_1/* .ExceededCapacityErrorTypeId */.F7W; +/** + * Constructs an `ExceededCapacityError` with an optional message. + * + * **When to use** + * + * Use to create the error value for bounded-resource capacity failures. + * + * **Example** (Creating an ExceededCapacityError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.ExceededCapacityError("Queue full").message // => "Queue full" + * ``` + * + * @see {@link isExceededCapacityError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const ExceededCapacityError = _internal_effect_js__rspack_import_1/* .ExceededCapacityError */.Aub; +/** + * Unique brand present on `AsyncFiberError` values and used by + * `isAsyncFiberError` for runtime checks. + * + * @category type IDs + * @since 4.0.0 + */ +const AsyncFiberErrorTypeId = _internal_effect_js__rspack_import_1/* .AsyncFiberErrorTypeId */.cOF; +/** + * Checks whether an arbitrary value is an `AsyncFiberError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * const error = new Cause.AsyncFiberError(fiber) + * Cause.isAsyncFiberError(error) // => true + * Cause.isAsyncFiberError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isAsyncFiberError = _internal_effect_js__rspack_import_1/* .isAsyncFiberError */.Rft; +/** + * Constructs an `AsyncFiberError` for a fiber that could not be resolved + * synchronously. + * + * **When to use** + * + * Use to create the error value for a fiber that could not be completed by a + * synchronous runner. + * + * **Example** (Creating an AsyncFiberError) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * new Cause.AsyncFiberError(fiber).message // => "An asynchronous Effect was executed with Effect.runSync" + * ``` + * + * @see {@link isAsyncFiberError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const AsyncFiberError = _internal_effect_js__rspack_import_1/* .AsyncFiberError */.RD4; +/** + * Unique brand for `UnknownError`. + * + * @category type IDs + * @since 4.0.0 + */ +const UnknownErrorTypeId = _internal_effect_js__rspack_import_1/* .UnknownErrorTypeId */.Kkt; +/** + * Checks whether an arbitrary value is an `UnknownError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isUnknownError(new Cause.UnknownError("x")) // => true + * Cause.isUnknownError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isUnknownError = _internal_effect_js__rspack_import_1/* .isUnknownError */.PnV; +/** + * Constructs an `UnknownError`. The first argument is the original + * cause (stored in `Error.cause`); the second is an optional human-readable + * message. + * + * **Example** (Creating an UnknownError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.UnknownError({ raw: true }, "Unexpected value").message // => "Unexpected value" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const UnknownError = _internal_effect_js__rspack_import_1/* .UnknownError */.Bk6; +/** + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** + * + * Annotations are stored as a `Context` on each reason and can be + * retrieved later via {@link reasonAnnotations} or {@link annotations}. + * The runtime uses this to attach stack traces and spans. + * + * - Returns a new `Cause`. + * - By default, existing keys are preserved. Pass `{ overwrite: true }` to + * replace them. + * + * **Example** (Annotating a cause) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const annotated = Cause.annotate(Cause.fail("error"), Context.make(RequestId, "req-1")) + * Context.getOrUndefined(Cause.annotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotate = _internal_core_js__rspack_import_0/* .causeAnnotate */.Eh; +/** + * Reads the annotations from a single `Reason` as a `Context`. + * + * **When to use** + * + * Use when you need tracing metadata (e.g. `StackTrace`) from + * a specific reason rather than the whole cause. + * + * **Example** (Reading reason annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const reason = Cause.makeFailReason("error") + * const annotated = reason.annotate(Context.make(RequestId, "req-1")) + * + * Context.getOrUndefined(Cause.reasonAnnotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} — merged annotations from all reasons in a cause + * + * @category annotations + * @since 4.0.0 + */ +const reasonAnnotations = _internal_effect_js__rspack_import_1/* .reasonAnnotations */.tQ6; +/** + * Reads the merged annotations from all reasons in a `Cause`. + * + * **When to use** + * + * Use to read diagnostic metadata merged from the whole cause. + * + * **Gotchas** + * + * When multiple reasons contain the same annotation key, the value from the + * later reason wins. + * + * **Example** (Reading merged annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const cause = Cause.annotate( + * Cause.fail("error"), + * Context.make(RequestId, "req-1") + * ) + * + * Context.getOrUndefined(Cause.annotations(cause), RequestId) // => "req-1" + * ``` + * + * @see {@link reasonAnnotations} — annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotations = _internal_effect_js__rspack_import_1/* .causeAnnotations */.On5; +/** + * Context annotation used to store the stack frame captured at the point of failure. + * + * **When to use** + * + * Use to read the failure stack-frame annotation from a `Reason` when building + * diagnostics, logging, or custom cause renderers. + * + * **Details** + * + * The runtime annotates every reason with this when a stack frame is + * available. Retrieve it via + * `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`. + * + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link InterruptorStackTrace} for the interrupt-specific stack-frame annotation + * + * @category services + * @since 4.0.0 + */ +class StackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/StackTrace"))) {} +/** + * Context annotation used to store the stack frame captured at the point of + * interruption. + * + * **When to use** + * + * Use when you need the stack-frame annotation used by interrupt-only cause + * rendering. + * + * **Details** + * + * Similar to `StackTrace` but specific to `Interrupt` reasons. + * + * @see {@link StackTrace} for stack frames attached to failures + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotate} for attaching annotations to a cause + * + * @category services + * @since 4.0.0 + */ +class InterruptorStackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/InterruptorStackTrace"))) {} +//# sourceMappingURL=Cause.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + $L: isDone, + Vw: done, + iw: squash, + kO: fromReasons, + nn: hasInterruptsOnly +}); + + +}, +"./node_modules/effect/dist/Channel.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var _Exit_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var _Fiber_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/Fiber.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Iterable_js__rspack_import_13 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Latch_js__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Latch.js"); +/* import */ var _Pipeable_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Pull_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Pull.js"); +/* import */ var _Queue_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Queue.js"); +/* import */ var _Result_js__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/* import */ var _Scope_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Scope.js"); +/* import */ var _Semaphore_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Semaphore.js"); +/** + * Provides low-level building blocks for streaming data through Effect. + * + * A `Channel` can read input elements, write output elements, fail with a typed + * error, and finish with a typed result while managing resources safely. + * Streams and sinks are built on channels, so most application code uses those + * higher-level modules instead. This module is useful when implementing stream + * operators or specialized streaming workflows. + * + * @since 2.0.0 + */ +// @effect-diagnostics returnEffectInGen:off + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * Runtime identifier stored on `Channel` values and used by `isChannel` to + * recognize them. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = "~effect/Channel"; +/** + * Checks whether a value is a `Channel`. + * + * **Example** (Checking for channels) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * const channel = Channel.succeed(42) + * Channel.isChannel(channel) // => true + * Channel.isChannel("not a channel") // => false + * ``` + * + * @category guards + * @since 3.5.4 + */ +const isChannel = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +const ChannelProto = { + [TypeId]: { + _Env: _Function_js__rspack_import_1/* .identity */.D_, + _InErr: _Function_js__rspack_import_1/* .identity */.D_, + _InElem: _Function_js__rspack_import_1/* .identity */.D_, + _OutErr: _Function_js__rspack_import_1/* .identity */.D_, + _OutElem: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_2/* .pipeArguments */.tT)(this, arguments); + } +}; +// ----------------------------------------------------------------------------- +// Constructors +// ----------------------------------------------------------------------------- +/** + * Creates a `Channel` from a transformation function that operates on upstream pulls. + * + * **Example** (Creating channels from transforms) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromTransform((upstream, scope) => + * Effect.succeed(upstream) + * ) + * await Effect.runPromise(Channel.runCollect(channel)) // => [] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromTransform = transform => { + const self = Object.create(ChannelProto); + self.transform = (upstream, scope) => _Effect_js__rspack_import_3/* .catchCause */.Tyx(transform(upstream, scope), cause => _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .failCause */.ATB(cause))); + return self; +}; +/** + * Transforms a Channel by applying a function to its Pull implementation. + * + * **Example** (Transforming pull behavior) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Transform a channel by modifying its pull behavior + * const originalChannel = Channel.fromIterable([1, 2, 3]) + * + * const transformedChannel = Channel.transformPull( + * originalChannel, + * (pull, scope) => + * Effect.succeed( + * Effect.map(pull, (value) => value * 2) + * ) + * ) + * await Effect.runPromise(Channel.runCollect(transformedChannel)) // => [2, 4, 6] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPull = (self, f) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .flatMap */.qIB(toTransform(self)(upstream, scope), pull => f(pull, scope))); +/** + * Creates a `Channel` from an `Effect` that produces a `Pull`. + * + * **Example** (Creating channels from pulls) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect } from "effect" + * + * const channel = Channel.fromPull(Effect.sync(() => { + * let emitted = false + * return Effect.suspend(() => { + * if (emitted) return Cause.done() + * emitted = true + * return Effect.succeed(42) + * }) + * })) + * await Effect.runPromise(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPull = effect => fromTransform((_, __) => effect); +/** + * Creates a `Channel` from a transformation function that operates on upstream + * pulls, but also provides a forked scope that closes when the resulting + * Channel completes. + * + * **When to use** + * + * Use when building channels that require scoped resource lifecycle management, + * providing both the channel scope and a forked scope that automatically closes + * when the channel completes. + * + * @see {@link fromTransform} for a simpler transformation without a forked scope + * @category constructors + * @since 4.0.0 + */ +const fromTransformBracket = f => fromTransform(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope) { + const closableScope = _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(scope); + const onCause = cause => _Scope_js__rspack_import_4/* .close */.VN(closableScope, _Pull_js__rspack_import_5/* .doneExitFromCause */.aU(cause)); + const pull = yield* _Effect_js__rspack_import_3/* .onError */.S5A(f(upstream, scope, closableScope), onCause); + return _Effect_js__rspack_import_3/* .onError */.S5A(pull, onCause); +})); +/** + * Converts a `Channel` back to its underlying transformation function. + * + * **Example** (Extracting channel transforms) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.succeed(42) + * const transform = Channel.toTransform(channel) + * typeof transform // => "function" + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toTransform = channel => channel.transform; +/** + * The default chunk size used by channels for batching operations. + * + * **Example** (Reading the default chunk size) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * Channel.DefaultChunkSize // => 4096 + * ``` + * + * @category constants + * @since 4.0.0 + */ +const DefaultChunkSize = 4096; +const asyncQueue = (scope, f, options) => Queue.make({ + capacity: options?.bufferSize, + strategy: options?.strategy +}).pipe(Effect.tap(queue => Scope.addFinalizer(scope, Queue.shutdown(queue))), Effect.tap(queue => Effect.forkIn(Scope.provide(f(queue), scope), scope))); +/** + * Creates a `Channel` that interacts with a callback function using a queue. + * + * **Example** (Creating channels from callbacks) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Queue } from "effect" + * + * const channel = Channel.callback((queue) => + * Effect.gen(function*() { + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * yield* Queue.end(queue) + * }) + * ) + * await Effect.runPromise(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.take)); +/** + * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays. + * + * **Example** (Creating array channels from callbacks) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Queue } from "effect" + * + * const channel = Channel.callbackArray(Effect.fn(function*(queue) { + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.end(queue) + * })) + * await Effect.runPromise(Channel.runCollect(channel)) // => [[1, 2]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callbackArray = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.takeAll)); +/** + * Creates a `Channel` that lazily evaluates to another channel. + * + * **Example** (Suspending channel creation) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.suspend(() => Channel.succeed(42)) + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = evaluate => fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope))); +/** + * Acquires a resource, uses it to build a `Channel`, and guarantees that + * `release` runs with the channel's `Exit` when the channel completes, fails, + * or is interrupted. + * + * **Details** + * + * Acquisition is uninterruptible. If acquisition fails, `use` is not run and + * `release` is not registered. + * + * **Example** (Managing resources with acquire-use-release) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const released: Array = [] + * const channel = Channel.acquireUseRelease( + * Effect.succeed("resource"), + * (resource) => Channel.succeed(resource.toUpperCase()), + * (resource, exit) => Effect.sync(() => released.push(resource)) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [["RESOURCE"], ["resource"]] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const acquireUseRelease = (acquire, use, release) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) { + let option = Option.none(); + yield* Scope.addFinalizerExit(forkedScope, exit => Option.isSome(option) ? release(option.value, exit) : Effect.void); + const value = yield* Effect.uninterruptible(acquire); + option = Option.some(value); + return yield* toTransform(use(value))(upstream, scope); +})); +/** + * Acquires a resource, emits the acquired value as a single channel element, + * and registers `release` in the channel scope. + * + * **Details** + * + * The release action runs when the channel scope closes and receives the scope + * exit. If acquisition fails, no element is emitted and `release` is not + * registered. + * + * **Example** (Managing resources with acquire-release) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const released: Array = [] + * const channel = Channel.acquireRelease( + * Effect.succeed("resource"), + * (resource, exit) => Effect.sync(() => released.push(resource)) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [["resource"], ["resource"]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const acquireRelease = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, release) => unwrap(Effect.map(Effect.acquireRelease(self, release), succeed))))); +/** + * Creates a `Channel` from an iterator. + * + * **Example** (Creating channels from iterators) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const channel = Channel.fromIterator(() => numbers[Symbol.iterator]()) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterator = iterator => fromPull(Effect.sync(() => { + const iter = iterator(); + return Effect.suspend(() => { + const state = iter.next(); + return state.done ? Cause.done(state.value) : Effect.succeed(state.value); + }); +})); +/** + * Creates a `Channel` that emits all elements from an array. + * + * **Example** (Creating channels from arrays) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromArray([1, 2, 3, 4, 5]) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArray = array => fromPull(Effect.sync(() => { + let index = 0; + return Effect.suspend(() => index >= array.length ? Cause.done() : Effect.succeed(array[index++])); +})); +/** + * Creates a `Channel` that emits all elements from a chunk. + * + * **Example** (Creating channels from chunks) + * + * ```ts import.meta.vitest + * import { Channel, Chunk, Effect } from "effect" + * + * const chunk = Chunk.make(1, 2, 3) + * const channel = Channel.fromChunk(chunk) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk)); +/** + * Creates a `Channel` from an iterator that emits arrays of elements. + * + * **Example** (Batching iterator output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel from a simple iterator + * const numberIterator = (): Iterator => { + * let count = 0 + * return { + * next: () => { + * if (count < 3) { + * return { value: count++, done: false } + * } + * return { value: "finished", done: true } + * } + * } + * } + * + * const channel = Channel.fromIteratorArray(() => numberIterator(), 2) + * Effect.runSync(Channel.runCollect(channel)) // => [[0, 1], [2]] + * ``` + * + * **Example** (Batching generator output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create channel from a generator function + * function* fibonacci(): Generator { + * let a = 0, b = 1 + * for (let i = 0; i < 5; i++) { + * yield a + * ;[a, b] = [b, a + b] + * } + * } + * + * const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3) + * Effect.runSync(Channel.runCollect(fibChannel)) // => [[0, 1, 1], [2, 3]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => fromPull(Effect.sync(() => { + const iter = iterator(); + let done = Option.none(); + return Effect.suspend(() => { + if (done._tag === "Some") return Cause.done(done.value); + const buffer = []; + while (buffer.length < chunkSize) { + const state = iter.next(); + if (state.done) { + if (buffer.length === 0) { + return Cause.done(state.value); + } + done = Option.some(state.value); + break; + } + buffer.push(state.value); + } + return Effect.succeed(buffer); + }); +})); +/** + * Creates a `Channel` that emits all elements from an iterable. + * + * **Example** (Creating channels from iterables) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const set = new Set([1, 2, 3]) + * const channel = Channel.fromIterable(set) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterable = iterable => fromIterator(() => iterable[Symbol.iterator]()); +/** + * Creates a `Channel` that emits arrays of elements from an iterable. + * + * **Example** (Batching iterable output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const channel = Channel.fromIterableArray(numbers, 4) + * Effect.runSync(Channel.runCollect(channel)) // => [[1, 2, 3, 4], [5]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterableArray = (iterable, chunkSize = DefaultChunkSize) => fromIteratorArray(() => iterable[Symbol.iterator](), chunkSize); +/** + * Creates a `Channel` that emits a single value and then ends. + * + * **Example** (Creating channels that succeed) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.succeed(42) + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeed = value => fromEffect(_Effect_js__rspack_import_3/* .succeed */.PyW(value)); +/** + * Creates a `Channel` that immediately ends with the specified value. + * + * **Example** (Ending with a value) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.end("done") + * Effect.runSync(Channel.runCollect(channel)) // => [] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const end = value => fromPull(Effect.succeed(Cause.done(value))); +/** + * Creates a `Channel` that immediately ends with the lazily evaluated value. + * + * @category constructors + * @since 4.0.0 + */ +const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluate()))); +/** + * Creates a `Channel` that emits a single value computed by a lazy evaluation. + * + * **Example** (Computing values lazily) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * let requests = 0 + * + * const channel = Channel.sync(() => { + * requests += 1 + * return `request-${requests}` + * }) + * Effect.runSync(Channel.runCollect(channel)) // => ["request-1"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sync = evaluate => fromEffect(Effect.sync(evaluate)); +/** + * Represents a `Channel` that emits no elements. + * + * **Example** (Creating empty channels) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create an empty channel + * const emptyChannel = Channel.empty + * + * // Use empty channel in composition + * const combined = Channel.concatWith(emptyChannel, () => Channel.succeed(42)) + * // Will immediately provide the second channel's output + * + * // Empty channel can be used as a no-op in conditional logic + * const conditionalChannel = (shouldEmit: boolean) => + * shouldEmit ? Channel.succeed("data") : Channel.empty + * + * Effect.runSync(Channel.runCollect(conditionalChannel(true))) // => ["data"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const empty = /*#__PURE__*/fromPull(/*#__PURE__*/_Effect_js__rspack_import_3/* .succeed */.PyW(/*#__PURE__*/_Cause_js__rspack_import_6/* .done */.Vw())); +/** + * Represents a `Channel` that never completes. + * + * **Example** (Creating non-terminating channels) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * // Create a channel that never completes + * const neverChannel = Channel.never + * + * // Use in conditional logic + * const withFallback = Channel.concatWith( + * neverChannel, + * () => Channel.succeed("fallback") + * ) + * + * // Never channel is useful for testing or as a placeholder + * const conditionalChannel = (shouldComplete: boolean) => + * shouldComplete ? Channel.succeed("done") : Channel.never + * + * Channel.isChannel(conditionalChannel(false)) // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = /*#__PURE__*/fromPull(/*#__PURE__*/_Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .never */.ZmZ)); +/** + * Constructs a channel that fails immediately with the specified error. + * + * **Example** (Failing with an error) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Exit } from "effect" + * + * const failedChannel = Channel.fail("Something went wrong") + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.fail("Something went wrong") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fail = error => fromPull(Effect.succeed(Effect.fail(error))); +/** + * Constructs a channel that fails immediately with the specified lazily + * evaluated error. + * + * **When to use** + * + * Use when the error value should be computed each time the channel runs instead + * of when the channel is constructed. + * + * **Example** (Failing with a lazy error) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Exit } from "effect" + * + * let attempts = 0 + * const conditionalError = Channel.failSync(() => { + * attempts += 1 + * return `Error after attempt ${attempts}` + * }) + * const observed = [ + * Effect.runSync(Effect.exit(Channel.runCollect(conditionalError))), + * attempts + * ] // => [Exit.fail("Error after attempt 1"), 1] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = evaluate => fromPull(Effect.failSync(evaluate)); +/** + * Constructs a channel that fails immediately with the specified `Cause`. + * + * **When to use** + * + * Use when the channel failure must preserve a full `Cause`, such as defects, + * interruptions, or combined failures. + * + * **Example** (Failing with causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * const simpleCause = Cause.fail("Simple error") + * const failedChannel = Channel.failCause(simpleCause) + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.failCause(simpleCause) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = cause => fromPull(Effect.failCause(cause)); +/** + * Constructs a channel that fails immediately with the specified lazily + * evaluated `Cause`. + * + * **Example** (Failing with lazy causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * // Create a channel that fails with a lazily computed cause + * let attempts = 0 + * const failedChannel = Channel.failCauseSync(() => { + * attempts += 1 + * return Cause.fail(`Runtime error after attempt ${attempts}`) + * }) + * + * const observed = [ + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))), + * attempts + * ] // => [Exit.fail("Runtime error after attempt 1"), 1] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate)); +/** + * Constructs a channel that fails immediately with the specified defect. + * + * **Example** (Dying with defects) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * const defect = "Unrecoverable error" + * const diedChannel = Channel.die(defect) + * Effect.runSync(Effect.exit(Channel.runCollect(diedChannel))) // => Exit.failCause(Cause.die(defect)) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const die = defect => failCause(Cause.die(defect)); +/** + * Uses an effect to write a single value to the channel. + * + * **Example** (Creating channels from effects) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const successChannel = Channel.fromEffect( + * Effect.succeed("Hello from effect!") + * ) + * Effect.runSync(Channel.runCollect(successChannel)) // => ["Hello from effect!"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEffect = effect => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let done = false; + return _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (done) return _Cause_js__rspack_import_6/* .done */.Vw(); + done = true; + return effect; + }); +})); +/** + * Creates a channel that evaluates an effect and uses its successful value as + * the channel's done value without emitting any output elements. + * + * **Details** + * + * If the effect fails, the channel fails with the effect's error. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDone = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))); +/** + * Uses an effect and discards its result. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDrain = effect => fromPull(Effect.flatMap(effect, () => Cause.done())); +/** + * Creates a channel from an effect that produces a `Take`. + * + * **Details** + * + * A successful `Take` emits a non-empty array of output elements. A failed + * `Take` fails the channel. A done `Take` completes the channel with its done + * value. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull))); +/** + * Creates a channel from a queue. + * + * **Example** (Creating channels from queues) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * yield* Queue.offerAll(queue, ["item1", "item2", "item3"]) + * yield* Queue.end(queue) + * const channel = Channel.fromQueue(queue) + * return yield* Channel.runCollect(channel) + * }) + * await Effect.runPromise(program) // => ["item1", "item2", "item3"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue))); +/** + * Creates a channel from a queue that emits arrays of elements. + * + * **Example** (Creating batched channels from queues) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(4) + * yield* Queue.offerAll(queue, [1, 2, 3, 4]) + * yield* Queue.end(queue) + * const arrayChannel = Channel.fromQueueArray(queue) + * return yield* Channel.runCollect(arrayChannel) + * }) + * await Effect.runPromise(program) // => [[1, 2, 3, 4]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromQueueArray = queue => fromPull(Effect.succeed(Queue.takeAll(queue))); +/** + * Creates a channel that forwards upstream input elements, input errors, and + * the upstream done value unchanged. + * + * @category constructors + * @since 2.0.0 + */ +const identity = () => fromTransform((upstream, _scope) => Effect.succeed(upstream)); +/** + * Creates a channel from a PubSub subscription. + * + * **Example** (Creating channels from subscriptions) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class SubscriptionError extends Data.TaggedError("SubscriptionError")<{ + * readonly reason: string + * }> {} + * + * const program = Effect.gen(function*() { + * // Create a PubSub + * const pubsub = yield* PubSub.bounded(32) + * + * // Create a subscription + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Publish some messages + * yield* PubSub.publish(pubsub, "Hello") + * yield* PubSub.publish(pubsub, "World") + * yield* PubSub.publish(pubsub, "from") + * yield* PubSub.publish(pubsub, "PubSub") + * + * // Create a channel from the subscription + * const channel = Channel.fromSubscription(subscription) + * + * // The channel will receive all published messages + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some("Hello") + * + * // Real-time notifications example + * const notificationChannel = Effect.gen(function*() { + * const eventBus = yield* PubSub.unbounded<{ type: string; payload: any }>() + * const userSubscription = yield* PubSub.subscribe(eventBus) + * + * return Channel.fromSubscription(userSubscription) + * }) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscription = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done()))); +/** + * Creates a channel from a PubSub subscription that outputs arrays of values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub subscription and outputs + * arrays of values in chunks. It's useful when you want to process multiple values at once + * for better performance. + * + * **Example** (Batching subscription values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.bounded(16) + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Create a channel that reads arrays of values + * const channel = Channel.fromSubscriptionArray(subscription) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * yield* PubSub.publish(pubsub, 4) + * + * // The channel will output arrays like [1, 2, 3] and [4] + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4]) + * ``` + * + * **Example** (Processing subscription values in batches) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class BatchProcessingError extends Data.TaggedError("BatchProcessingError")<{ + * readonly reason: string + * }> {} + * + * const batchProcessor = Effect.gen(function*() { + * const pubsub = yield* PubSub.bounded(32) + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Create a channel that processes items in batches + * const batchChannel = Channel.fromSubscriptionArray(subscription) + * + * // Transform to process each batch + * const processedChannel = Channel.map(batchChannel, (batch) => + * batch.map((item) => item.toUpperCase()) + * ) + * + * yield* PubSub.publishAll(pubsub, ["one", "two"]) + * return processedChannel + * }) + * const batch = Effect.scoped(Effect.flatMap(batchProcessor, Channel.runHead)) + * await Effect.runPromise(batch) // => Option.some(["ONE", "TWO"]) + * ``` + * + * **Example** (Aggregating subscription metrics) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * const metricsAggregator = Effect.gen(function*() { + * const metricsPubSub = yield* PubSub.bounded< + * { timestamp: number; value: number } + * >(100) + * const subscription = yield* PubSub.subscribe(metricsPubSub) + * + * // Create a channel that collects metrics in chunks + * const metricsChannel = Channel.fromSubscriptionArray(subscription) + * + * // Transform to calculate aggregate statistics + * const aggregatedChannel = Channel.map(metricsChannel, (metrics) => { + * const values = metrics.map((m) => m.value) + * const sum = values.reduce((a, b) => a + b, 0) + * const avg = sum / values.length + * const min = Math.min(...values) + * const max = Math.max(...values) + * + * return { + * count: values.length, + * sum, + * average: avg, + * min, + * max, + * firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)), + * lastTimestamp: Math.max(...metrics.map((m) => m.timestamp)) + * } + * }) + * + * yield* PubSub.publish(metricsPubSub, { timestamp: 1, value: 10 }) + * return aggregatedChannel + * }) + * const metric = Effect.scoped(Effect.flatMap(metricsAggregator, Channel.runHead)) + * const result = await Effect.runPromise(metric) + * Option.map(result, ({ count, sum, average, min, max }) => ({ count, sum, average, min, max })) // => Option.some({ count: 1, sum: 10, average: 10, min: 10, max: 10 }) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done()))); +/** + * Creates a channel from a PubSub that outputs individual values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub by automatically + * subscribing to it. The channel outputs individual values as they are published + * to the PubSub, making it ideal for real-time streaming scenarios. + * + * **Example** (Creating channels from PubSubs) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 3 }) + * + * // Create a channel that reads individual values + * const channel = Channel.fromPubSub(pubsub) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * + * // The channel will output: 1, 2, 3 (individual values) + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some(1) + * ``` + * + * **Example** (Streaming PubSub notifications) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * const notificationService = Effect.gen(function*() { + * const notificationPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel for real-time notifications + * const notificationChannel = Channel.fromPubSub(notificationPubSub) + * + * // Transform notifications to add timestamps + * const receivedAt = "2024-01-01T00:00:00.000Z" + * const timestampedChannel = Channel.map(notificationChannel, (message) => ({ + * message, + * receivedAt, + * id: `notification:${message}` + * })) + * + * yield* PubSub.publish(notificationPubSub, "ready") + * return timestampedChannel + * }) + * const notification = Effect.scoped(Effect.flatMap(notificationService, Channel.runHead)) + * await Effect.runPromise(notification) // => Option.some({ message: "ready", receivedAt: "2024-01-01T00:00:00.000Z", id: "notification:ready" }) + * ``` + * + * **Example** (Processing PubSub events) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface DomainEvent { + * readonly type: string + * readonly payload: unknown + * readonly timestamp: number + * } + * + * const eventProcessor = Effect.gen(function*() { + * const eventPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel for processing domain events + * const eventChannel = Channel.fromPubSub(eventPubSub) + * + * // Filter and transform events + * const processedChannel = Channel.map(eventChannel, (event) => { + * if (event.type === "user.created") { + * return { + * ...event, + * processed: true, + * processedAt: event.timestamp + 1 + * } + * } + * return event + * }) + * + * yield* PubSub.publish(eventPubSub, { type: "user.created", payload: {}, timestamp: 1 }) + * return processedChannel + * }) + * const event = Effect.scoped(Effect.flatMap(eventProcessor, Channel.runHead)) + * const result = await Effect.runPromise(event) // => Option.some({ type: "user.created", payload: {}, timestamp: 1, processed: true, processedAt: 2 }) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription)); +/** + * Creates a channel from a PubSub that outputs arrays of values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub by automatically + * subscribing to it and collecting values into arrays. The channel outputs + * arrays of values in chunks, making it ideal for batch processing scenarios. + * + * **Example** (Batching PubSub values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class BatchError extends Data.TaggedError("BatchError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 4 }) + * + * // Create a channel that reads arrays of values + * const channel = Channel.fromPubSubArray(pubsub) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * yield* PubSub.publish(pubsub, 4) + * + * // The channel will output arrays like [1, 2, 3] and [4] + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4]) + * ``` + * + * **Example** (Processing PubSub orders in batches) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface Order { + * readonly id: string + * readonly customerId: string + * readonly items: ReadonlyArray + * readonly total: number + * readonly submittedAt: number + * } + * + * const orderBatchProcessor = Effect.gen(function*() { + * const orderPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel that processes orders in batches + * const orderChannel = Channel.fromPubSubArray(orderPubSub) + * + * // Transform to process each batch of orders + * const processedChannel = Channel.map(orderChannel, (orderBatch) => { + * const totalRevenue = orderBatch.reduce((sum, order) => sum + order.total, 0) + * const customerCount = new Set(orderBatch.map((order) => + * order.customerId + * )).size + * + * return { + * batchSize: orderBatch.length, + * totalRevenue, + * uniqueCustomers: customerCount, + * firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)), + * orders: orderBatch + * } + * }) + * + * yield* PubSub.publish(orderPubSub, { + * id: "1", customerId: "a", items: ["book"], total: 10, submittedAt: 1 + * }) + * return processedChannel + * }) + * const order = Effect.scoped(Effect.flatMap(orderBatchProcessor, Channel.runHead)) + * const result = await Effect.runPromise(order) + * Option.map(result, (batch) => [batch.batchSize, batch.totalRevenue, batch.uniqueCustomers]) // => Option.some([1, 10, 1]) + * ``` + * + * **Example** (Processing PubSub logs in batches) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface LogEntry { + * readonly timestamp: number + * readonly level: "info" | "warn" | "error" + * readonly message: string + * readonly source: string + * } + * + * const logAggregator = Effect.gen(function*() { + * const logPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel that collects logs in batches + * const logChannel = Channel.fromPubSubArray(logPubSub) + * + * // Transform to analyze log batches + * const analysisChannel = Channel.map(logChannel, (logBatch) => { + * const errorCount = logBatch.filter((log) => log.level === "error").length + * const warnCount = logBatch.filter((log) => log.level === "warn").length + * const infoCount = logBatch.filter((log) => log.level === "info").length + * + * const timeRange = { + * start: Math.min(...logBatch.map((log) => log.timestamp)), + * end: Math.max(...logBatch.map((log) => log.timestamp)) + * } + * + * return { + * batchId: `${timeRange.start}-${timeRange.end}`, + * totalEntries: logBatch.length, + * errorCount, + * warnCount, + * infoCount, + * timeRange, + * sources: [...new Set(logBatch.map((log) => log.source))] + * } + * }) + * + * yield* PubSub.publish(logPubSub, { + * timestamp: 1, + * level: "info", + * message: "ready", + * source: "app" + * } satisfies LogEntry) + * return analysisChannel + * }) + * const log = Effect.scoped(Effect.flatMap(logAggregator, Channel.runHead)) + * const result = await Effect.runPromise(log) + * Option.map(result, (batch) => [batch.batchId, batch.totalEntries, batch.infoCount]) // => Option.some(["1-1", 1, 1]) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubArray = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray)); +/** + * Subscribes to a `PubSub` of `Take` values and exposes them as a channel. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the channel. Done `Take` values complete the channel. + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubTake = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), sub => fromEffectTake(PubSub.take(sub)))); +/** + * Creates a Channel from a Schedule. + * + * @category constructors + * @since 4.0.0 + */ +const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => step(void 0))); +/** + * Creates a channel from a lazily supplied Web `ReadableStream`. + * + * **Example** (Reading from a Web stream) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromReadableStream({ + * evaluate: () => new ReadableStream({ + * start(controller) { + * controller.enqueue(1) + * controller.close() + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * await Effect.runPromise(Channel.runCollect(channel)) // => [[1]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromReadableStream = options => fromTransform((_, scope) => readableStreamToPullUnsafe({ + scope, + readable: options.evaluate(), + onError: options.onError, + releaseLockOnEnd: options.releaseLockOnEnd +})); +/** @internal */ +const pullIntoWritableStream = options => Effect.acquireUseRelease(Effect.sync(() => options.writable.getWriter()), writer => { + const loop = options.pull.pipe(Effect.flatMap(chunk => Effect.forEach(chunk, value => Effect.tryPromise({ + try: () => writer.ready.then(() => writer.write(value)), + catch: options.onError + }), { + discard: true + })), Effect.forever({ + disableYield: true + })); + const withClose = options.closeOnDone !== false ? Pull.catchDone(loop, done => Effect.andThen(Effect.tryPromise({ + try: () => writer.close(), + catch: options.onError + }), Cause.done(done))) : loop; + return Effect.onError(withClose, cause => Pull.isDoneCause(cause) ? Effect.void : Effect.promise(() => writer.abort(cause).catch(constVoid))); +}, writer => Effect.sync(() => writer.releaseLock())); +/** + * Creates a channel that writes upstream values to a lazily supplied Web + * `WritableStream`. + * + * **Example** (Writing channel input) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const written: Array = [] + * const sink = Channel.fromWritableStream({ + * evaluate: () => new WritableStream({ + * write(value) { + * written.push(value) + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe( + * Channel.pipeTo(sink), + * Channel.runDrain + * ) + * + * await Effect.runPromise(program) + * written // => [1, 2] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromWritableStream = options => fromTransform(pull => { + const writable = options.evaluate(); + return Effect.succeed(pullIntoWritableStream({ + ...options, + writable, + pull + })); +}); +/** + * Creates a channel backed by a Web `TransformStream`, writing upstream values + * while emitting transformed values from its readable side. + * + * **Example** (Transforming channel input) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const transform = Channel.fromTransformStream({ + * evaluate: () => new TransformStream({ + * transform(value, controller) { + * controller.enqueue(value * 2) + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe( + * Channel.pipeTo(transform), + * Channel.runCollect + * ) + * + * await Effect.runPromise(program) // => [[2], [4]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromTransformStream = options => fromTransform((upstream, scope) => { + const transform = options.evaluate(); + const exit = MutableRef.make(undefined); + return pullIntoWritableStream({ + pull: upstream, + writable: transform.writable, + onError: options.onError, + closeOnDone: options.closeOnDone + }).pipe(Effect.catchCause(cause => { + if (!Pull.isDoneCause(cause)) { + exit.current = Exit.failCause(cause); + } + return Effect.void; + }), Effect.forkIn(scope), Effect.flatMap(() => readableStreamToPullUnsafe({ + scope, + exit, + readable: transform.readable, + onError: options.onError, + releaseLockOnEnd: options.releaseLockOnEnd + }))); +}); +const readableStreamToPullUnsafe = options => { + const reader = options.readable.getReader(); + const exit = options.exit ?? MutableRef.make(undefined); + const pull = Effect.suspend(() => { + if (exit.current) return exit.current; + return Effect.matchCauseEffect(Effect.tryPromise({ + try: () => reader.read(), + catch: options.onError + }), { + onFailure: cause => exit.current ?? Effect.failCause(cause), + onSuccess: ({ + done, + value + }) => { + if (exit.current) return exit.current; + return done ? Cause.done() : Effect.succeed(Arr.of(value)); + } + }); + }); + return Effect.as(Scope.addFinalizer(options.scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel().catch(constVoid))), pull); +}; +/** + * Creates a channel that pulls values from an `AsyncIterable`. + * + * **Details** + * + * Each yielded value is emitted as an output element. The iterator's return + * value becomes the channel's done value. Thrown or rejected iterator errors + * are converted with `onError`. If the channel scope closes early and the + * iterator has a `return` method, that method is called. + * + * @category constructors + * @since 4.0.0 + */ +const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnUntraced(function* (_, scope) { + const iter = iterable[Symbol.asyncIterator](); + if (iter.return) { + yield* Scope.addFinalizer(scope, Effect.promise(() => iter.return())); + } + return Effect.flatMap(Effect.tryPromise({ + try: () => iter.next(), + catch: onError + }), result => result.done ? Cause.done(result.value) : Effect.succeed(result.value)); +})); +/** + * Creates a channel from an `AsyncIterable`, emitting each yielded value as a + * single-element non-empty array. + * + * **Details** + * + * The iterator's return value becomes the channel's done value. Thrown or + * rejected iterator errors are converted with `onError`. If the channel scope + * closes early and the iterator has a `return` method, that method is called. + * + * @category constructors + * @since 4.0.0 + */ +const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterable(iterable, onError), Arr.of); +/** + * Maps the output of this channel using the specified function. + * + * **Example** (Mapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class TransformError extends Data.TaggedError("TransformError")<{ + * readonly reason: string + * }> {} + * + * // Basic mapping of channel values + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * const doubledChannel = Channel.map(numbersChannel, (n) => n * 2) + * Effect.runSync(Channel.runCollect(doubledChannel)) // => [2, 4, 6, 8, 10] + * + * // Transform string data + * const wordsChannel = Channel.fromIterable(["hello", "world", "effect"]) + * const upperCaseChannel = Channel.map(wordsChannel, (word) => word.toUpperCase()) + * Effect.runSync(Channel.runCollect(upperCaseChannel)) // => ["HELLO", "WORLD", "EFFECT"] + * + * // Complex object transformation + * type User = { id: number; name: string } + * type UserDisplay = { displayName: string; isActive: boolean } + * + * const usersChannel = Channel.fromIterable([ + * { id: 1, name: "Alice" }, + * { id: 2, name: "Bob" } + * ]) + * const displayChannel = Channel.map(usersChannel, (user): UserDisplay => ({ + * displayName: `User: ${user.name}`, + * isActive: true + * })) + * Effect.runSync(Channel.runCollect(displayChannel)) // => [{ displayName: "User: Alice", isActive: true }, { displayName: "User: Bob", isActive: true }] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => transformPull(self, pull => _Effect_js__rspack_import_3/* .sync */.OH5(() => { + let i = 0; + return _Effect_js__rspack_import_3/* .map */.TjK(pull, o => f(o, i++)); +}))); +/** + * Maps the done value of this channel using the specified function. + * + * @category sequencing + * @since 4.0.0 + */ +const mapDone = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => mapDoneEffect(self, o => Effect.succeed(f(o)))))); +/** + * Maps the done value of this channel using the specified effectful function. + * + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 + */ +const mapDoneEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, done => Effect.flatMap(f(done), Cause.done))))))); +const concurrencyIsSequential = concurrency => concurrency === undefined || concurrency !== "unbounded" && concurrency <= 1; +/** + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * const processedChannel = Channel.mapEffect( + * numbersChannel, + * (n) => Effect.succeed(n * n) + * ) + * await Effect.runPromise(Channel.runCollect(processedChannel)) // => [1, 4, 9, 16, 25] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const mapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? mapEffectSequential(self, f) : mapEffectConcurrent(self, f, options)); +const mapEffectSequential = (self, f) => fromTransform((upstream, scope) => { + let i = 0; + return _Effect_js__rspack_import_3/* .map */.TjK(toTransform(self)(upstream, scope), _Effect_js__rspack_import_3/* .flatMap */.qIB(o => f(o, i++))); +}); +const mapEffectConcurrent = (self, f, options) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope, forkedScope) { + let i = 0; + const pull = yield* toTransform(self)(upstream, scope); + const concurrencyN = options.concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : options.concurrency; + const queue = yield* _Queue_js__rspack_import_7/* .bounded */.Mm(0); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_7/* .shutdown */.n_(queue)); + const runFork = _Effect_js__rspack_import_3/* .runForkWith */.eJC(yield* _Effect_js__rspack_import_3/* .context */._OA()); + const trackFiber = _Fiber_js__rspack_import_8/* .runIn */.VO(forkedScope); + if (options.unordered) { + const semaphore = _Semaphore_js__rspack_import_9/* .makeUnsafe */.LZ(concurrencyN); + const release = (0,_Function_js__rspack_import_1/* .constant */.dY)(semaphore.release(1)); + const handle = _Effect_js__rspack_import_3/* .matchCauseEffect */.khu({ + onFailure: cause => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Queue_js__rspack_import_7/* .failCause */.AT(queue, cause), release), + onSuccess: value => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Queue_js__rspack_import_7/* .offer */.x(queue, value), release) + }); + yield* semaphore.take(1).pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(() => pull), _Effect_js__rspack_import_3/* .flatMap */.qIB(value => { + trackFiber(runFork(handle(f(value, i++)))); + return _Effect_js__rspack_import_3/* ["void"] */.rIH; + }), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => semaphore.withPermits(concurrencyN - 1)(_Queue_js__rspack_import_7/* .failCause */.AT(queue, cause))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + } else { + // capacity is n - 2 because + // - 1 for the offer *after* starting a fiber + // - 1 for the current processing fiber + const effects = yield* _Queue_js__rspack_import_7/* .bounded */.Mm(concurrencyN - 2); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_7/* .shutdown */.n_(effects)); + yield* _Queue_js__rspack_import_7/* .take */.s(effects).pipe(_Effect_js__rspack_import_3/* .flatten */.Bqz, _Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_7/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause)), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + let errorCause; + const onExit = exit => { + if (exit._tag === "Success") return; + errorCause = exit.cause; + _Queue_js__rspack_import_7/* .failCauseUnsafe */._1(queue, exit.cause); + }; + yield* pull.pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(value => { + if (errorCause) return _Effect_js__rspack_import_3/* .failCause */.ATB(errorCause); + const fiber = runFork(f(value, i++)); + trackFiber(fiber); + fiber.addObserver(onExit); + return _Queue_js__rspack_import_7/* .offer */.x(effects, _Fiber_js__rspack_import_8/* .join */.fj(fiber)); + }), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => _Queue_js__rspack_import_7/* .offer */.x(effects, _Exit_js__rspack_import_10/* .failCause */.AT(cause)).pipe(_Effect_js__rspack_import_3/* .andThen */.hgn(_Queue_js__rspack_import_7/* .failCause */.AT(effects, cause)))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + } + return _Queue_js__rspack_import_7/* .take */.s(queue); +})); +/** + * Returns a new channel which is the same as this one but applies the given + * function to the input channel’s input elements. + * + * @category sequencing + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.flatMap(upstream, el => f(el)), scope))))); +/** + * Returns a new channel which is the same as this one but applies the given + * function to the input errors. + * + * @category sequencing + * @since 2.0.0 + */ +const mapInputError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.catch(upstream, err => { + if (Cause.isDone(err)) return Effect.fail(err); + return Effect.flatMap(f(err), Effect.fail); +}), scope))))); +/** + * Applies a side effect function to each output element of the channel, + * returning a new channel that emits the same elements. + * + * **Details** + * + * The `tap` function allows you to perform side effects (like logging or + * debugging) on each element emitted by a channel without modifying the + * elements themselves. + * + * **Example** (Tapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class LogError extends Data.TaggedError("LogError")<{ + * readonly message: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // Tap into each output element to perform side effects + * const processed: Array = [] + * const tappedChannel = Channel.tap( + * numberChannel, + * (n) => Effect.sync(() => processed.push(n)) + * ) + * + * const observed = [await Effect.runPromise(Channel.runCollect(tappedChannel)), processed] // => [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options)))); +/** + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (Flat mapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ProcessError extends Data.TaggedError("ProcessError")<{ + * readonly cause: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // FlatMap each number to create new channels + * const flatMappedChannel = Channel.flatMap( + * numberChannel, + * (n) => + * Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`)) + * ) + * + * Effect.runSync(Channel.runCollect(flatMappedChannel)) // => ["item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? flatMapSequential(self, f) : flatMapConcurrent(self, f, options)); +const flatMapSequential = (self, f) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .map */.TjK(toTransform(self)(upstream, scope), pull => { + let childPull; + let childScope; + const makePull = _Effect_js__rspack_import_3/* .flatMap */.qIB(pull, value => { + childScope ??= _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(scope); + return _Effect_js__rspack_import_3/* .flatMapEager */.Ab9(toTransform(f(value))(upstream, childScope), pull => { + childPull = catchHalt(pull); + return childPull; + }); + }); + const catchHalt = _Pull_js__rspack_import_5/* .catchDone */.m8(_ => { + childPull = undefined; + // we can reuse the scope if the only finalizer is the "fork" one + if (childScope.state._tag === "Open" && (0,_internal_effect_js__rspack_import_11/* .scopeFinalizerCountUnsafe */.q7)(childScope) === 1) { + return makePull; + } + const close = _Scope_js__rspack_import_4/* .close */.VN(childScope, _Exit_js__rspack_import_10/* ["void"] */.rI); + childScope = undefined; + return _Effect_js__rspack_import_3/* .flatMap */.qIB(close, () => makePull); + }); + return _Effect_js__rspack_import_3/* .suspend */.DYE(() => childPull ?? makePull); +})); +const flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(options)); +/** + * Concatenates this channel with another channel created from the terminal value + * of this channel. The new channel is created using the provided function. + * + * **Example** (Concatenating with completion values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ConcatError extends Data.TaggedError("ConcatError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel that outputs numbers and terminates with sum + * const numberChannel = Channel.fromIterable([1, 2, 3]).pipe( + * Channel.concatWith((sum: void) => Channel.succeed(`Completed processing`)) + * ) + * + * Effect.runSync(Channel.runCollect(numberChannel)) // => [1, 2, 3, "Completed processing"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concatWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { + let currentPull; + const forkedScope = Scope.forkUnsafe(scope); + const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => { + currentPull = Pull.catchDone(pull, leftover => { + return Scope.close(forkedScope, Exit.void).pipe(Effect.flatMap(() => toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => { + currentPull = pull; + return pull; + })); + }); + return currentPull; + }); + return Effect.suspend(() => currentPull ?? makePull); +}))))); +/** + * Concatenates this channel with another channel, so that the second channel + * starts emitting values after the first channel has completed. + * + * **Example** (Concatenating channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ConcatError extends Data.TaggedError("ConcatError")<{ + * readonly reason: string + * }> {} + * + * // Create two channels + * const firstChannel = Channel.fromIterable([1, 2, 3]) + * const secondChannel = Channel.fromIterable(["a", "b", "c"]) + * + * // Concatenate them + * const concatenatedChannel = Channel.concat(firstChannel, secondChannel) + * + * Effect.runSync(Channel.runCollect(concatenatedChannel)) // => [1, 2, 3, "a", "b", "c"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => concatWith(self, _ => that)))); +/** + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. + * + * @category sequencing + * @since 4.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const leftPull = yield* toTransform(self)(upstream, scope); + const rightPull = yield* toTransform(that)(upstream, scope); + let state = s(); + return Effect.suspend(() => { + const combinedPull = f(state, leftPull, rightPull); + return Effect.map(combinedPull, ([a, s1]) => { + state = s1; + return a; + }); + }); +}))))); +/** + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * + * @category sequencing + * @since 4.0.0 + */ +const orElseIfEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { + let currentPull; + const forkedScope = Scope.forkUnsafe(scope); + const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => { + const next = pull.pipe(Effect.tap(() => { + currentPull = pull; + return Effect.void; + }), Pull.catchDone(leftover => Scope.close(forkedScope, Exit.succeed(leftover)).pipe(Effect.andThen(toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => { + currentPull = pull; + return pull; + })))); + currentPull = next; + return next; + }); + return Effect.suspend(() => currentPull ?? makePull); +}))))); +/** + * Flattens a channel of channels. + * + * **Example** (Flattening nested channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FlattenError extends Data.TaggedError("FlattenError")<{ + * readonly cause: string + * }> {} + * + * // Create a channel that outputs channels + * const nestedChannels = Channel.fromIterable([ + * Channel.fromIterable([1, 2]), + * Channel.fromIterable([3, 4]), + * Channel.fromIterable([5, 6]) + * ]) + * + * // Flatten the nested channels + * const flattenedChannel = Channel.flatten(nestedChannels) + * + * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const flatten = channels => flatMap(channels, identity_); +/** + * Flattens a channel that outputs arrays into a channel that outputs individual elements. + * + * **Example** (Flattening arrays of channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FlattenError extends Data.TaggedError("FlattenError")<{ + * readonly message: string + * }> {} + * + * // Create a channel that outputs arrays + * const arrayChannel = Channel.fromIterable([ + * [1, 2, 3], + * [4, 5], + * [6, 7, 8, 9] + * ]) + * + * // Flatten the arrays into individual elements + * const flattenedChannel = Channel.flattenArray(arrayChannel) + * + * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6, 7, 8, 9] + * ``` + * + * @category transforming + * @since 4.0.0 + */ +const flattenArray = self => transformPull(self, pull => { + let array; + let index = 0; + const pump = _Effect_js__rspack_import_3/* .suspend */.DYE(function loop() { + if (array === undefined) { + return _Effect_js__rspack_import_3/* .flatMap */.qIB(pull, array_ => { + switch (array_.length) { + case 0: + return loop(); + case 1: + return _Effect_js__rspack_import_3/* .succeed */.PyW(array_[0]); + default: + { + array = array_; + return _Effect_js__rspack_import_3/* .succeed */.PyW(array_[index++]); + } + } + }); + } + const next = array[index++]; + if (index >= array.length) { + array = undefined; + index = 0; + } + return _Effect_js__rspack_import_3/* .succeed */.PyW(next); + }); + return _Effect_js__rspack_import_3/* .succeed */.PyW(pump); +}); +/** + * Flattens a channel that emits `Take` values into a channel that emits the + * `Take` outputs directly. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the returned channel. Done `Take` values complete the returned channel. + * + * @category transforming + * @since 4.0.0 + */ +const flattenTake = self => mapEffectSequential(self, Take.toPull); +/** + * Creates a new channel that consumes all output from the source channel + * but emits nothing, preserving only the completion value. + * + * **Example** (Draining channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel that outputs values + * const sourceChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Drain all output, keeping only the completion + * const drainedChannel = Channel.drain(sourceChannel) + * + * Effect.runSync(Channel.runCollect(drainedChannel)) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const drain = self => transformPull(self, pull => Effect.succeed(Effect.forever(pull, { + disableYield: true +}))); +/** + * Repeats this channel according to the provided schedule. + * + * @category repetition + * @since 4.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => Schedule.toStepWithMetadata(typeof schedule === "function" ? schedule(identity_) : schedule).pipe(Effect.map(step => { + let meta = Schedule.CurrentMetadata.defaultValue(); + const loop = concatWith(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), done => step(done).pipe(Effect.map(meta_ => { + meta = meta_; + return loop; + }), Pull.catchDone(() => Effect.succeed(end(done))), unwrap)); + return loop; +}), unwrap)))); +/** + * Repeats this channel forever. + * + * @category repetition + * @since 4.0.0 + */ +const forever = self => concatWith(self, () => forever(self)); +/** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing + * @since 4.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => transformPull(self, (pull, _scope) => Effect.map(Schedule.toStepWithSleep(schedule), step => { + const pullWithStep = Effect.tap(pull, step); + return pullWithStep; +}))))); +/** + * Filters the output elements of a channel using a predicate function. + * Elements that don't match the predicate are discarded. + * + * **Example** (Filtering channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with mixed numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5, 6, 7, 8]) + * + * // Filter to keep only even numbers + * const evenChannel = Channel.filter(numbersChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(evenChannel)) // => [2, 4, 6, 8] + * + * // Filter with type refinement + * const mixedChannel = Channel.fromIterable([1, "hello", 2, "world", 3]) + * const numbersOnlyChannel = Channel.filter( + * mixedChannel, + * (value): value is number => typeof value === "number" + * ) + * Effect.runSync(Channel.runCollect(numbersOnlyChannel)) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return predicate(elem) ? Effect.succeed(elem) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering + * @since 4.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + const result = filter(elem); + return Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success); +})))))); +/** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return Effect.flatMap(predicate(elem), passes => passes ? Effect.succeed(elem) : Effect.flatMap(pull, loop)); +})))))); +/** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering + * @since 4.0.0 + */ +const filterMapEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return Effect.flatMap(filter(elem), result => Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success)); +})))))); +/** + * Filters arrays of elements emitted by a channel, applying the filter + * to each element within the arrays and only emitting non-empty filtered arrays. + * + * **Example** (Filtering array output) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect } from "effect" + * + * const nonEmptyArrayPredicate = Array.isReadonlyArrayNonEmpty + * + * // Create a channel that outputs arrays of mixed data + * const arrayChannel = Channel.fromIterable([ + * Array.make(1, 2, 3, 4, 5), + * Array.make(6, 7, 8, 9, 10), + * Array.make(11, 12, 13, 14, 15) + * ]).pipe(Channel.filter(nonEmptyArrayPredicate)) + * + * // Filter arrays to keep only even numbers + * const evenArraysChannel = Channel.filterArray(arrayChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(evenArraysChannel)) // => [[2, 4], [6, 8, 10], [12, 14]] + * // Note: Only non-empty filtered arrays are emitted + * + * // Arrays that would become empty after filtering are discarded entirely + * const oddChannel = Channel.fromIterable([ + * Array.make(1, 3, 5), + * Array.make(2, 4), + * Array.make(7, 9) + * ]).pipe(Channel.filter(nonEmptyArrayPredicate)) + * const filteredOddChannel = Channel.filterArray(oddChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(filteredOddChannel)) // => [[2, 4]] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const filterArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + const passes = []; + for (let i = 0; i < arr.length; i++) { + if (predicate(arr[i])) { + passes.push(arr[i]); + } + } + return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering + * @since 4.0.0 + */ +const filterMapArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + const passes = []; + for (let i = 0; i < arr.length; i++) { + const result = filter(arr[i]); + if (Result.isSuccess(result)) { + passes.push(result.success); + } + } + return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, pull => { + const f = Effect.flatMap(pull, arr => Effect.filter(arr, predicate)); + return Effect.succeed(Effect.flatMap(f, function loop(arr) { + return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Effect.flatMap(f, loop); + })); +})))); +/** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterMapArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + return Effect.flatMap(Effect.filterMapEffect(arr, filter), passes => Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop)); +})))))); +/** + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4]) + * + * // Use mapAccum to create running sums and emit both current and sum + * const runningSum = Channel.mapAccum( + * numbersChannel, + * () => 0, // initial accumulator state + * (sum, current) => { + * const newSum = sum + current + * // Return [newState, outputValues] + * return [newSum, [current, newSum]] as const + * } + * ) + * // Using with Effect for async processing + * const asyncMapAccum = Channel.mapAccum( + * numbersChannel, + * () => "", + * (acc, value) => + * Effect.gen(function*() { + * const newAcc = acc + value.toString() + * return [newAcc, [`${value}-processed`, newAcc]] as const + * }) + * ) + * Effect.runSync(Channel.runCollect(runningSum)) // => [1, 1, 2, 3, 3, 6, 4, 10] + * Effect.runSync(Channel.runCollect(asyncMapAccum)) // => ["1-processed", "1", "2-processed", "12", "3-processed", "123", "4-processed", "1234"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, initial, f, options) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { + let state = initial(); + let current; + let index = 0; + let cause; + const pullNext = Effect.matchCauseEffect(pull, { + onFailure(cause_) { + cause = cause_; + const b = options?.onHalt && options.onHalt(state); + return b && b.length > 0 ? Effect.succeed([state, b]) : Effect.failCause(cause_); + }, + onSuccess(a) { + const b = f(state, a); + return Arr.isArray(b) ? Effect.succeed(b) : b; + } + }); + const pump = Effect.suspend(function loop() { + if (current === undefined) { + if (cause) return Effect.failCause(cause); + return Effect.flatMap(pullNext, ([newState, values]) => { + state = newState; + if (values.length === 0) { + return loop(); + } else if (values.length === 1) { + return Effect.succeed(values[0]); + } + current = values; + return loop(); + }); + } + const next = current[index++]; + if (index >= current.length) { + current = undefined; + index = 0; + } + return Effect.succeed(next); + }); + return pump; +}))))); +/** + * Transforms a channel statefully by scanning over its output with an accumulator function. + * Emits the intermediate results of the scan operation. + * + * **Example** (Scanning channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Scan to create running sum + * const runningSumChannel = Channel.scan(numbersChannel, 0, (sum, n) => sum + n) + * Effect.runSync(Channel.runCollect(runningSumChannel)) // => [0, 1, 3, 6, 10, 15] + * // Note: emits the initial value and each intermediate result + * + * // Scan with string concatenation + * const wordsChannel = Channel.fromIterable(["hello", "world", "from", "effect"]) + * const sentenceChannel = Channel.scan( + * wordsChannel, + * "", + * (sentence, word) => sentence === "" ? word : `${sentence} ${word}` + * ) + * Effect.runSync(Channel.runCollect(sentenceChannel)) // => ["", "hello", "hello world", "hello world from", "hello world from effect"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a)))))); +/** + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. + * Emits the intermediate results of the scan operation. + * + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ScanError extends Data.TaggedError("ScanError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4]) + * + * // Effectful scan with async operations + * const asyncScanChannel = Channel.scanEffect( + * numbersChannel, + * "", + * (acc, value) => + * Effect.gen(function*() { + * return acc + value.toString() + * }) + * ) + * await Effect.runPromise(Channel.runCollect(asyncScanChannel)) // => ["", "1", "12", "123", "1234"] + * + * // Scan with error handling + * const errorHandlingScan = Channel.scanEffect( + * numbersChannel, + * 0, + * (sum, n) => { + * if (n < 0) { + * return Effect.fail(new ScanError({ reason: "negative number" })) + * } + * return Effect.succeed(sum + n) + * } + * ) + * await Effect.runPromise(Channel.runCollect(errorHandlingScan)) // => [0, 1, 3, 6, 10] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const scanEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { + let state = initial; + let isFirst = true; + return Effect.suspend(() => { + if (isFirst) { + isFirst = false; + return Effect.succeed(state); + } + return Effect.map(Effect.flatMap(pull, a => f(state, a)), newState => { + state = newState; + return state; + }); + }); +}))))); +/** + * Catches any cause of failure from the channel and allows recovery by + * creating a new channel based on the caught cause. + * + * **Example** (Recovering from failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Data, Effect } from "effect" + * + * class ProcessError extends Data.TaggedError("ProcessError")<{ + * readonly reason: string + * }> {} + * + * class RecoveryError extends Data.TaggedError("RecoveryError")<{ + * readonly message: string + * }> {} + * + * // Create a failing channel + * const failingChannel = Channel.fail( + * new ProcessError({ reason: "network error" }) + * ) + * + * // Catch the cause and provide recovery + * const recoveredChannel = Channel.catchCause(failingChannel, (cause) => { + * if (Cause.hasFails(cause)) { + * return Channel.succeed("Recovered from failure") + * } + * return Channel.succeed("Recovered from interruption") + * }) + * + * Effect.runSync(Channel.runCollect(recoveredChannel)) // => ["Recovered from failure"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => { + let forkedScope = Scope.forkUnsafe(scope); + return Effect.map(toTransform(self)(upstream, forkedScope), pull => { + let currentPull = pull.pipe(Effect.catchCause(cause => { + if (Pull.isDoneCause(cause)) { + return Effect.failCause(cause); + } + const toClose = forkedScope; + forkedScope = Scope.forkUnsafe(scope); + return Scope.close(toClose, Exit.failCause(cause)).pipe(Effect.andThen(toTransform(f(cause))(upstream, forkedScope)), Effect.flatMap(childPull => { + currentPull = childPull; + return childPull; + })); + })); + return Effect.suspend(() => currentPull); + }); +})))); +/** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling + * @since 4.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catchCause(self, cause => fromEffectDrain(Effect.flatMap(f(cause), _ => Effect.failCause(cause))))))); +/** + * Catches causes of failure that match a specific filter, allowing + * conditional error recovery based on the type of failure. + * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, f) => catchCause(self, cause => { + return predicate(cause) ? f(cause) : failCause(cause); +})))); +/** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, filter, f) => catchCause(self, cause => { + const result = filter(cause); + return Result.isFailure(result) ? failCause(result.failure) : f(result.success, cause); +})))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catchCauseFilter(self, Cause.findError, e => f(e))))); + +/** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling + * @since 4.0.0 + */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => transformPull(self, pull => _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .tapError */.sFT(pull, err => _Cause_js__rspack_import_6/* .isDone */.$L(err) ? _Effect_js__rspack_import_3/* ["void"] */.rIH : _Effect_js__rspack_import_3/* .asVoid */.NLW(f(err)))))); +/** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling + * @since 4.0.0 + */ +const catchIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, predicate, f, orElse) => catch_(self, err => { + return predicate(err) ? f(err) : orElse ? orElse(err) : fail(err); +})))); +/** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, filter, f, orElse) => catch_(self, err => { + const result = filter(err); + return Result.isFailure(result) ? orElse ? orElse(result.failure) : fail(result.failure) : f(result.success); +})))); +/** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling + * @since 4.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); + return catchIf(self, pred, f, orElse); +}))); +/** + * Catches a specific reason within a tagged error. + * + * **Example** (Recovering from nested reasons) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const reason = new RateLimitError({ retryAfter: 60 }) + * const channel = Channel.fail(new AiError({ reason })) + * + * const recovered = channel.pipe( + * Channel.catchReason("AiError", "RateLimitError", (reason) => + * Channel.succeed(`retry: ${reason.retryAfter}`) + * ) + * ) + * Effect.runSync(Channel.runCollect(recovered)) // => ["retry: 60"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, errorTag, reasonTag, f, orElse) => catch_(self, error => { + if (isTagged(error, errorTag) && hasProperty(error, "reason")) { + const reason = error.reason; + if (isTagged(reason, reasonTag)) { + return f(reason, error); + } + return orElse ? orElse(reason, error) : fail(error); + } + return fail(error); +})))); +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, errorTag, cases, orElse) => { + let keys; + return catch_(self, error => { + if (isTagged(error, errorTag) && hasProperty(error, "reason") && hasProperty(error.reason, "_tag") && String.isString(error.reason._tag)) { + const reason = error.reason; + keys ??= new Set(Object.keys(cases)); + if (keys.has(reason._tag)) { + return cases[reason._tag](reason, error); + } + return orElse ? orElse(reason, error) : fail(error); + } + return fail(error); + }); +}))); +/** + * Promotes nested reason errors into the channel error, replacing the parent error. + * + * **Example** (Promoting nested reasons) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const reason = new RateLimitError({ retryAfter: 60 }) + * const channel = Channel.fail(new AiError({ reason })) + * + * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) + * Effect.runSync(Effect.exit(Channel.runCollect(unwrapped))) // => Exit.fail(reason) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const unwrapReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, errorTag) => catchFilter(self, error => isTagged(error, errorTag) && hasProperty(error, "reason") ? Result.succeed(error.reason) : Result.fail(error), fail)))); +/** + * Returns a new channel, which is the same as this one, except the failure + * value of the returned channel is created by applying the specified function + * to the failure value of this channel. + * + * @category error handling + * @since 2.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catch_(self, err => fail(f(err)))))); +/** + * Converts all errors in the channel to defects (unrecoverable failures). + * This is useful when you want to treat errors as programming errors. + * + * **Example** (Converting failures to defects) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Data, Effect, Exit } from "effect" + * + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * readonly field: string + * }> {} + * + * // Create a channel that might fail + * const error = new ValidationError({ field: "email" }) + * const failingChannel = Channel.fail(error) + * + * // Convert failures to defects + * const fatalChannel = Channel.orDie(failingChannel) + * + * Effect.runSync(Effect.exit(Channel.runCollect(fatalChannel))) // => Exit.failCause(Cause.die(error)) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => catch_(self, die); +/** + * Ignores all errors in the channel, converting them to an empty channel. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the channel fails. + * + * @category error handling + * @since 4.0.0 + */ +const ignore = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, options) => { + if (!options?.log) { + return catch_(self, () => empty); + } + const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log); + return catch_(tapCause(self, cause => Cause.hasFails(cause) ? logEffect(cause) : Effect.void), () => empty); +}))); +const ignoreCause_ = self => catchCause(self, () => empty); +/** + * Ignores all errors in the channel including defects, converting them to an empty channel. + * + * **When to use** + * + * Use when a channel should become best-effort and all failure causes, including + * defects and interruptions, can be converted to empty output. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the channel fails. + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, options) => { + if (!options?.log) return ignoreCause_(self); + const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log); + return ignoreCause_(tapCause(self, cause => logEffect(cause))); +}))); +/** + * Returns a new channel that retries this channel according to the specified + * schedule whenever it fails. + * + * @category error handling + * @since 4.0.0 + */ +const retry = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => suspend(() => { + let step = undefined; + let meta = Schedule.CurrentMetadata.defaultValue(); + const selfWithMeta = provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)); + const withReset = onFirst(selfWithMeta, () => { + step = undefined; + return Effect.void; + }); + const resolvedSchedule = typeof schedule === "function" ? schedule(identity_) : schedule; + const loop = catch_(withReset, Effect.fnUntraced(function* (error) { + if (!step) { + step = yield* Schedule.toStepWithMetadata(resolvedSchedule); + } + meta = yield* step(error); + return loop; + }, (effect, error) => Pull.catchDone(effect, () => Effect.succeed(fail(error))), unwrap)); + return loop; +})))); +/** + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class SwitchError extends Data.TaggedError("SwitchError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // Switch to new channels based on each value + * const switchedChannel = Channel.switchMap( + * numberChannel, + * (n) => Channel.fromIterable([`value-${n}`]) + * ) + * + * await Effect.runPromise(Channel.runCollect(switchedChannel)) // => ["value-3"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const switchMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, f, options) => self.pipe(map(f), mergeAll({ + ...options, + concurrency: options?.concurrency ?? 1, + switch: true +}))))); +/** + * Merges multiple channels with specified concurrency and buffering options. + * + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class MergeAllError extends Data.TaggedError("MergeAllError")<{ + * readonly reason: string + * }> {} + * + * // Create channels that output other channels + * const nestedChannels = Channel.fromIterable([ + * Channel.fromIterable([1, 2]), + * Channel.fromIterable([3, 4]), + * Channel.fromIterable([5, 6]) + * ]) + * + * // Merge all channels with bounded concurrency + * const mergedChannel = Channel.mergeAll({ + * concurrency: 1, + * bufferSize: 16 + * })(nestedChannels) + * + * await Effect.runPromise(Channel.runCollect(mergedChannel)) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const mergeAll = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (channels, { + bufferSize = 16, + concurrency, + switch: switch_ = false +}) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope, forkedScope) { + const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); + const semaphore = switch_ ? undefined : _Semaphore_js__rspack_import_9/* .makeUnsafe */.LZ(concurrencyN); + const doneLatch = yield* _Latch_js__rspack_import_12/* .make */.L8(true); + const fibers = new Set(); + const queue = yield* _Queue_js__rspack_import_7/* .bounded */.Mm(bufferSize); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_7/* .shutdown */.n_(queue)); + const pull = yield* toTransform(channels)(upstream, scope); + yield* _Effect_js__rspack_import_3/* .gen */.JkU(function* () { + while (true) { + let pullFiber; + if (semaphore) { + if (fibers.size < concurrencyN) { + yield* semaphore.take(1); + } else { + pullFiber = yield* _Effect_js__rspack_import_3/* .forkChild */.zhn(pull); + yield* _Effect_js__rspack_import_3/* .raceFirst */.KT6(semaphore.take(1), _Effect_js__rspack_import_3/* .andThen */.hgn(_Fiber_js__rspack_import_8/* .join */.fj(pullFiber), _Effect_js__rspack_import_3/* .never */.ZmZ)); + } + } + const channel = pullFiber === undefined ? yield* pull : yield* _Fiber_js__rspack_import_8/* .join */.fj(pullFiber); + const childScope = _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope); + const childPull = yield* toTransform(channel)(upstream, childScope); + while (fibers.size >= concurrencyN) { + const fiber = _Iterable_js__rspack_import_13/* .headUnsafe */.BK(fibers); + fibers.delete(fiber); + if (fibers.size === 0) yield* doneLatch.open; + yield* _Fiber_js__rspack_import_8/* .interrupt */.G(fiber); + } + const fiber = yield* childPull.pipe(_Effect_js__rspack_import_3/* .tap */.Mim(() => _Effect_js__rspack_import_3/* .yieldNow */.m9E), _Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_7/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .onError */.S5A(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (cause) { + const halt = _Pull_js__rspack_import_5/* .filterDone */.Dc(cause); + yield* _Effect_js__rspack_import_3/* .exit */.NS5(_Scope_js__rspack_import_4/* .close */.VN(childScope, !_Result_js__rspack_import_14/* .isFailure */.N6(halt) ? _Exit_js__rspack_import_10/* .succeed */.Py(halt.success.value) : _Exit_js__rspack_import_10/* .failCause */.AT(halt.failure))); + if (!fibers.has(fiber)) return; + fibers.delete(fiber); + if (semaphore) yield* semaphore.release(1); + if (fibers.size === 0) yield* doneLatch.open; + if (_Result_js__rspack_import_14/* .isSuccess */.oJ(halt)) return; + return yield* _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause); + })), _Effect_js__rspack_import_3/* .forkChild */.zhn); + doneLatch.closeUnsafe(); + fibers.add(fiber); + } + }).pipe(_Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => { + const halt = _Pull_js__rspack_import_5/* .filterDone */.Dc(cause); + if (_Result_js__rspack_import_14/* .isSuccess */.oJ(halt)) { + return doneLatch.whenOpen(_Queue_js__rspack_import_7/* .failCause */.AT(queue, cause)); + } + return _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause); + }), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + return _Queue_js__rspack_import_7/* .take */.s(queue); +}))); +/** + * Returns a new channel, which is the merge of this channel and the specified + * channel. + * + * **Example** (Merging channels) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create two channels + * const leftChannel = Channel.fromIterable([1, 2, 3]) + * const rightChannel = Channel.fromIterable(["a", "b", "c"]) + * + * // The default "both" strategy waits for both channels to complete + * const mergedChannel = Channel.merge(leftChannel, rightChannel) + * + * const values = await Effect.runPromise(Channel.runCollect(mergedChannel)) + * values.map(String).sort() // => ["1", "2", "3", "a", "b", "c"] + * ``` + * + * @category combining + * @since 4.0.0 + */ +const merge = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, _scope, forkedScope) { + const strategy = options?.haltStrategy ?? "both"; + const queue = yield* _Queue_js__rspack_import_7/* .bounded */.Mm(0); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_7/* .shutdown */.n_(queue)); + let done = 0; + function onExit(side, cause) { + done++; + if (!_Pull_js__rspack_import_5/* .isDoneCause */.Og(cause)) { + return _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause); + } + switch (strategy) { + case "both": + { + return done === 2 ? _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause) : _Effect_js__rspack_import_3/* ["void"] */.rIH; + } + case "left": + case "right": + { + return side === strategy ? _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause) : _Effect_js__rspack_import_3/* ["void"] */.rIH; + } + case "either": + { + return _Queue_js__rspack_import_7/* .failCause */.AT(queue, cause); + } + } + } + const runSide = (side, channel, scope) => toTransform(channel)(upstream, scope).pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(pull => pull.pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_7/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r)), _Effect_js__rspack_import_3/* .onError */.S5A(cause => _Effect_js__rspack_import_3/* .andThen */.hgn(_Scope_js__rspack_import_4/* .close */.VN(scope, _Pull_js__rspack_import_5/* .doneExitFromCause */.aU(cause)), onExit(side, cause))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + yield* runSide("left", left, _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope)); + yield* runSide("right", right, _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope)); + return _Queue_js__rspack_import_7/* .take */.s(queue); +}))); +/** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining + * @since 4.0.0 + */ +const mergeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => merge(self, fromEffectDrain(effect), { + haltStrategy: "left" +})))); +/** + * Splits upstream string chunks into lines, recognizing `\n`, `\r\n`, and + * standalone `\r` as line terminators. The behavior matches + * `String.linesIterator` regardless of how the input is chunked. + * + * **Details** + * + * A line terminator at the very end of the stream does **not** produce a + * trailing empty line (consistent with `String.linesIterator`). Conversely, + * if the stream ends without a terminator the final partial line is still + * emitted. + * + * **Example** (Splitting string chunks into lines) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const result = await Effect.runPromise(Stream.runCollect( + * Stream.splitLines(Stream.make("hel", "lo\r\nwor", "ld\n")) + * )) + * result // => ["hello", "world"] + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const splitLines = () => fromTransform((upstream, _scope) => Effect.sync(() => { + // Accumulates text that has not yet been terminated by a line break. + // Content is carried across chunks until a terminator is found. + let stringBuilder = ""; + // Set when a chunk ends with \r so the next chunk can check whether + // the following character is \n (completing a \r\n pair) or not + // (standalone \r, which is itself a line terminator). + let midCRLF = false; + // Remembers the upstream Done value after the first time the upstream + // signals completion, so subsequent pulls return Done immediately + // without pulling upstream again. + let done = Option.none(); + function splitLinesArray(chunk) { + const chunkBuilder = []; + function pushLine(segment) { + if (stringBuilder.length === 0) { + chunkBuilder.push(segment); + } else { + chunkBuilder.push(stringBuilder + segment); + stringBuilder = ""; + } + } + for (let i = 0; i < chunk.length; i++) { + const str = chunk[i]; + if (str.length !== 0) { + let from = 0; + let indexOfCR = str.indexOf("\r"); + let indexOfLF = str.indexOf("\n"); + if (midCRLF) { + if (indexOfLF === 0) { + pushLine(""); + from = 1; + indexOfLF = str.indexOf("\n", from); + } else { + pushLine(""); + } + midCRLF = false; + } + while (indexOfCR !== -1 || indexOfLF !== -1) { + if (indexOfCR === -1 || indexOfLF !== -1 && indexOfLF < indexOfCR) { + pushLine(str.substring(from, indexOfLF)); + from = indexOfLF + 1; + indexOfLF = str.indexOf("\n", from); + } else { + if (str.length === indexOfCR + 1) { + midCRLF = true; + indexOfCR = -1; + } else { + pushLine(str.substring(from, indexOfCR)); + from = indexOfCR + (indexOfLF === indexOfCR + 1 ? 2 : 1); + indexOfCR = str.indexOf("\r", from); + indexOfLF = str.indexOf("\n", from); + } + } + } + stringBuilder = stringBuilder + str.substring(from, str.length - (midCRLF ? 1 : 0)); + } + } + return Arr.isReadonlyArrayNonEmpty(chunkBuilder) ? chunkBuilder : null; + } + const pullOrFlush = Effect.suspend(() => { + if (done._tag === "Some") { + return Cause.done(done.value); + } + return Pull.matchEffect(upstream, { + onSuccess: loop, + onFailure: Effect.failCause, + onDone: leftover => { + done = Option.some(leftover); + if (stringBuilder.length > 0 || midCRLF) { + const last = stringBuilder; + stringBuilder = ""; + midCRLF = false; + return Effect.succeed([last]); + } + return Cause.done(leftover); + } + }); + }); + function loop(chunk) { + const lines = splitLinesArray(chunk); + return lines !== null ? Effect.succeed(lines) : pullOrFlush; + } + return pullOrFlush; +})); +/** + * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`. + * + * **Details** + * + * Input chunks are decoded with streaming enabled so multi-byte characters may + * span `Uint8Array` boundaries. The optional `encoding` and `options` are + * passed to `TextDecoder`. + * + * @category decoding + * @since 4.0.0 + */ +const decodeText = (encoding, options) => fromTransform((upstream, _scope) => Effect.sync(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + return Effect.map(upstream, Arr.map(line => decoder.decode(line, streamOptions))); +})); +/** + * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`. + * + * **Details** + * + * Each string inside an emitted array is encoded independently. + * + * @category encoding + * @since 4.0.0 + */ +const encodeText = () => fromTransform((upstream, _scope) => Effect.sync(() => { + const encoder = new TextEncoder(); + return Effect.map(upstream, Arr.map(line => encoder.encode(line))); +})); +/** + * Returns a new channel that pipes the output of this channel into the + * specified channel. The returned channel has the input type of this channel, + * and the output type of the specified channel, terminating with the value of + * the specified channel. + * + * **Example** (Piping one channel into another) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class PipeError extends Data.TaggedError("PipeError")<{ + * readonly stage: string + * }> {} + * + * // Create source and transform channels + * const sourceChannel = Channel.fromIterable([1, 2, 3]) + * const transformChannel = Channel.map(sourceChannel, (n: number) => n * 2) + * + * // Pipe the source into the transform + * const pipedChannel = Channel.pipeTo(sourceChannel, transformChannel) + * + * Effect.runSync(Channel.runCollect(pipedChannel)) // => [2, 4, 6] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => toTransform(that)(upstream, scope)))))); +/** + * Returns a new channel that pipes the output of this channel into the + * specified channel and preserves this channel's failures without providing + * them to the other channel for observation. + * + * **Example** (Piping while preserving failures) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class SourceError extends Data.TaggedError("SourceError")<{ + * readonly code: number + * }> {} + * + * // Create a failing source channel + * const error = new SourceError({ code: 404 }) + * const failingSource = Channel.fail(error) + * const safeTransform = Channel.identity() + * + * // Pipe while preserving source failures + * const safePipedChannel = Channel.pipeToOrFail(failingSource, safeTransform) + * + * Effect.runSync(Effect.exit(Channel.runCollect(safePipedChannel))) // => Exit.fail(error) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeToOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => { + const upstreamPull = Effect.catchCause(upstream, cause => Pull.isDoneCause(cause) ? Effect.failCause(cause) : Effect.die(Cause.Done(cause))); + return Effect.map(toTransform(that)(upstreamPull, scope), pull => Effect.catchDefect(pull, defect => Cause.isDone(defect) ? Effect.failCause(defect.value) : Effect.die(defect))); +}))))); +/** + * Constructs a `Channel` from a scoped effect that will result in a + * `Channel` if successful. + * + * **Example** (Unwrapping channel effects) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class UnwrapError extends Data.TaggedError("UnwrapError")<{ + * readonly reason: string + * }> {} + * + * // Create an effect that produces a channel + * const channelEffect = Effect.succeed( + * Channel.fromIterable([1, 2, 3]) + * ) + * + * // Unwrap the effect to get the channel + * const unwrappedChannel = Channel.unwrap(channelEffect) + * + * Effect.runSync(Channel.runCollect(unwrappedChannel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unwrap = channel => fromTransform((upstream, scope) => { + let pull; + return _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (pull) return pull; + return channel.pipe(_Scope_js__rspack_import_4/* .provide */.Gt(scope), _Effect_js__rspack_import_3/* .flatMap */.qIB(channel => toTransform(channel)(upstream, scope)), _Effect_js__rspack_import_3/* .flatMap */.qIB(pull_ => pull = pull_)); + })); +}); +/** + * Runs a channel with a scope provided for the duration of the channel + * execution, removing the channel's `Scope` requirement. + * + * @category resource management + * @since 2.0.0 + */ +const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Effect.map(Scope.provide(toTransform(self)(upstream, scope), forkedScope), Scope.provide(forkedScope))); +/** + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. + * + * **Details** + * + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a base channel + * const baseChannel = Channel.fromIterable([1, 2, 3]) + * + * // Drain the embedded input while the base channel runs + * const embeddedChannel = Channel.embedInput( + * baseChannel, + * (upstream) => + * upstream.pipe( + * Effect.forever, + * Effect.ignore + * ) + * ) + * await Effect.runPromise(Channel.runCollect(embeddedChannel)) // => [1, 2, 3] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const embedInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, input) => fromTransformBracket((upstream, scope, forkedScope) => Effect.andThen(Effect.forkIn(input(upstream), forkedScope), toTransform(self)(Cause.done(), scope)))))); +/** + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs + * + * @category buffering + * @since 2.0.0 + */ +const buffer = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pull = yield* toTransform(self)(upstream, scope); + const queue = yield* Queue.make({ + capacity: options.capacity === "unbounded" ? undefined : options.capacity, + strategy: options.capacity === "unbounded" ? undefined : options.strategy + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({ + disableYield: true + }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope)); + return Queue.take(queue); +}))))); +/** + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays + * + * @category buffering + * @since 4.0.0 + */ +const bufferArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pull = yield* toTransform(self)(upstream, scope); + const queue = yield* Queue.make({ + capacity: options.capacity === "unbounded" ? undefined : options.capacity, + strategy: options.capacity === "unbounded" ? undefined : options.strategy + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* pull.pipe(Effect.flatMap(value => Queue.offerAll(queue, value)), Effect.forever({ + disableYield: true + }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope)); + return Queue.takeAll(queue); +}))))); +/** + * Interrupts a channel when another effect completes. + * + * **When to use** + * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption + * @since 2.0.0 + */ +const interruptWhen = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, effect) => merge(self, fromPull(_Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .flatMap */.qIB(effect, _Cause_js__rspack_import_6/* .done */.Vw))), { + haltStrategy: "either" +})); +/** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption + * @since 4.0.0 + */ +const haltWhen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) { + const pull = yield* toTransform(self)(upstream, scope); + const fiber = yield* Effect.forkIn(effect, forkedScope, { + startImmediately: true + }); + return Effect.suspend(() => { + const exit = fiber.pollUnsafe(); + return exit === undefined ? pull : Exit.match(exit, { + onFailure: Effect.failCause, + onSuccess: Cause.done + }); + }); +}))))); +/** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling + * @since 4.0.0 + */ +const onError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => onExit(self, exit => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void)))); +/** + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class ExitError extends Data.TaggedError("ExitError")<{ + * readonly stage: string + * }> {} + * + * // Create a channel + * const dataChannel = Channel.fromIterable([1, 2, 3]) + * + * // Attach exit handler + * const exits: Array> = [] + * const channelWithExit = Channel.onExit(dataChannel, (exit) => { + * exits.push(exit) + * return Effect.void + * }) + * const observed = [await Effect.runPromise(Channel.runCollect(channelWithExit)), exits] // => [[1, 2, 3], [Exit.void]] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, finalizer) => fromTransformBracket((upstream, scope, forkedScope) => _Scope_js__rspack_import_4/* .addFinalizerExit */.a6(forkedScope, finalizer).pipe(_Effect_js__rspack_import_3/* .andThen */.hgn(toTransform(self)(upstream, scope))))); +/** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks + * @since 4.0.0 + */ +const onStart = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onStart) => unwrap(Effect.as(onStart, self))))); +/** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks + * @since 4.0.0 + */ +const onFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFirst) => transformPull(self, pull => Effect.sync(() => { + let isFirst = true; + const pullFirst = Effect.tap(pull, element => { + isFirst = false; + return onFirst(element); + }); + return Effect.suspend(() => isFirst ? pullFirst : pull); +}))))); +/** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks + * @since 4.0.0 + */ +const onEnd = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onEnd) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, leftover => Effect.flatMap(onEnd, () => Cause.done(leftover)))))))); +/** + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class EnsureError extends Data.TaggedError("EnsureError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel + * const dataChannel = Channel.fromIterable([1, 2, 3]) + * + * // Ensure cleanup always runs + * const events: Array = [] + * const channelWithCleanup = Channel.ensuring( + * dataChannel, + * Effect.sync(() => events.push("cleanup")) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channelWithCleanup)), events] // => [[1, 2, 3], ["cleanup"]] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => onExit(self, _ => finalizer)))); +const runWith = (self, f, onHalt) => _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + const scope = _Scope_js__rspack_import_4/* .makeUnsafe */.LZ(); + const makePull = toTransform(self)(_Cause_js__rspack_import_6/* .done */.Vw(), scope); + return _Pull_js__rspack_import_5/* .catchDone */.m8(_Effect_js__rspack_import_3/* .flatMap */.qIB(makePull, f), onHalt ? onHalt : _Effect_js__rspack_import_3/* .succeed */.PyW).pipe(_Effect_js__rspack_import_3/* .onExit */.cfM(exit => _Scope_js__rspack_import_4/* .close */.VN(scope, exit))); +}); +/** + * Creates a channel from the specified services. + * + * @category accessors + * @since 2.0.0 + */ +const contextWith = f => fromTransform((upstream, scope) => Effect.contextWith(context => toTransform(f(context))(upstream, scope))); +/** + * Provides a `Context` to the channel, removing the corresponding service + * requirements from the returned channel. + * + * @category providing services + * @since 2.0.0 + */ +const provideContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => fromTransform((upstream, scope) => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context)))))); +/** + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category providing services + * @since 2.0.0 + */ +const provideService = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, key, service) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .map */.TjK(_Effect_js__rspack_import_3/* .provideService */.PfK(toTransform(self)(upstream, scope), key, service), _Effect_js__rspack_import_3/* .provideService */.PfK(key, service)))); +/** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category providing services + * @since 4.0.0 + */ +const provideServiceEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.flatMap(service, s => toTransform(provideService(self, key, s))(upstream, scope)))))); +/** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category providing services + * @since 4.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, layer, options) => Context.isContext(layer) ? provideContext(self, layer) : fromTransform((upstream, scope) => Effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context))))))); +/** + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.contextWith(context => { + const toProvide = f(context); + return toTransform(provideContext(self, toProvide))(upstream, scope); +}))))); +/** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category providing services + * @since 2.0.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service))))))); +/** + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = isChannel(arguments[0]); + const name = dataFirst ? arguments[1] : arguments[0]; + const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return withSpanImpl(self, name, options); + } + return self => withSpanImpl(self, name, options); +}; +const withSpanImpl = (self, name, options) => acquireUseRelease(Effect.makeSpan(name, options), span => provideService(self, ParentSpan, span), (span, exit) => Effect.withFiber(fiber => { + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(TracerTimingEnabled); + return endSpan(span, exit, clock, timingEnabled); +})); +/** + * The starting channel for Do notation, emitting an empty object. + * + * @category constructors + * @since 4.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, name, f) => map(self, elem => ({ + ...elem, + [name]: f(elem) +}))))); + +/** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category sequencing + * @since 4.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, name, f, options) => flatMap(self, elem => map(f(elem), b => ({ + ...elem, + [name]: b +})), options)))); +/** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category mapping + * @since 4.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, name) => map(self, elem => ({ + [name]: elem +}))))); +/** + * Runs a channel and counts the number of elements it outputs. + * + * **Example** (Counting channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class CountError extends Data.TaggedError("CountError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with multiple elements + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Count the elements + * const countEffect = Channel.runCount(numbersChannel) + * + * Effect.runSync(countEffect) // => 5 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runCount = self => runFold(self, () => 0, acc => acc + 1); +/** + * Runs a channel and discards all output elements, returning only the final result. + * + * **Example** (Draining channel output at runtime) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class DrainError extends Data.TaggedError("DrainError")<{ + * readonly stage: string + * }> {} + * + * // Create a channel that outputs elements and completes with a result + * const resultChannel = Channel.fromIterable([1, 2, 3]) + * const completedChannel = Channel.concat(resultChannel, Channel.end("completed")) + * + * // Drain all elements and get only the final result + * const drainEffect = Channel.runDrain(completedChannel) + * + * Effect.runSync(drainEffect) // => "completed" + * ``` + * + * @category running + * @since 2.0.0 + */ +const runDrain = self => runWith(self, pull => Effect.forever(pull, { + disableYield: true +})); +/** + * Runs a channel and applies an effect to each output element. + * + * **Example** (Running effects for each output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ForEachError extends Data.TaggedError("ForEachError")<{ + * readonly element: unknown + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * // Run forEach to process each element + * const processed: Array = [] + * const forEachEffect = Channel.runForEach( + * numbersChannel, + * (n) => Effect.sync(() => processed.push(n)) + * ) + * + * await Effect.runPromise(forEachEffect) + * processed // => [1, 2, 3] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runForEach = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => runWith(self, pull => _Effect_js__rspack_import_3/* .forever */.i4r(_Effect_js__rspack_import_3/* .flatMap */.qIB(pull, f), { + disableYield: true +}))); +/** + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * + * @category running + * @since 4.0.0 + */ +const runForEachWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => runWith(self, pull => pull.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({ + disableYield: true +})))))); +/** + * Concatenates a channel's `Uint8Array` chunks into a single `Uint8Array`. + * + * **Example** (Joining channel byte chunks) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromArray([ + * [new Uint8Array([1, 2])], + * [new Uint8Array([3, 4])] + * ] as const) + * + * const bytes = Effect.runSync(Channel.mkUint8Array(channel)) + * Array.from(bytes) // => [1, 2, 3, 4] + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source channel must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category running + * @since 4.0.0 + */ +const mkUint8Array = self => Effect.map(runFold(self, () => ({ + bytes: 0, + arrays: [] +}), (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc.bytes += chunk[i].length; + acc.arrays.push(chunk[i]); + } + return acc; +}), ({ + arrays, + bytes +}) => { + const result = new Uint8Array(bytes); + let offset = 0; + for (let i = 0; i < arrays.length; i++) { + const array = arrays[i]; + result.set(array, offset); + offset += array.length; + } + return result; +}); +/** + * Runs a channel and collects all output elements into an array. + * + * **Example** (Collecting channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class CollectError extends Data.TaggedError("CollectError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with elements + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Collect all elements into an array + * const collectEffect = Channel.runCollect(numbersChannel) + * + * Effect.runSync(collectEffect) // => [1, 2, 3, 4, 5] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runCollect = self => runFold(self, () => [], (acc, o) => { + acc.push(o); + return acc; +}); +/** + * Runs a channel and outputs the done value. + * + * @category running + * @since 4.0.0 + */ +const runDone = self => runWith(self, identity_, Effect.succeed); +/** + * Runs a channel until the first output element is available, returning it in + * an `Option`. + * + * **Details** + * + * Returns `Option.some` with the first output element, or `Option.none` if the + * channel completes without emitting output. + * + * @category running + * @since 4.0.0 + */ +const runHead = self => Effect.suspend(() => { + let head = Option.none(); + return runWith(self, pull => pull.pipe(Effect.asSome, Effect.flatMap(head_ => { + head = head_; + return Cause.done(); + })), () => Effect.succeed(head)); +}); +/** + * Runs a channel to completion and returns the last output element in an + * `Option`. + * + * **Details** + * + * Returns `Option.some` with the last emitted element, or `Option.none` if the + * channel completes without emitting output. + * + * @category running + * @since 4.0.0 + */ +const runLast = self => Effect.suspend(() => { + const absent = Symbol(); // Prevent boxing + let last = absent; + return runWith(self, pull => Effect.forever(Effect.flatMap(pull, item => { + last = item; + return Effect.void; + }), { + disableYield: true + }), () => last === absent ? Effect.succeedNone : Effect.succeedSome(last)); +}); +/** + * Runs a channel and folds over all output elements with an accumulator. + * + * **Example** (Folding channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FoldError extends Data.TaggedError("FoldError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Fold to calculate sum + * const sumEffect = Channel.runFold(numbersChannel, () => 0, (acc, n) => acc + n) + * + * Effect.runSync(sumEffect) // => 15 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runFold = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Effect.suspend(() => { + let state = initial(); + return runWith(self, pull => Effect.whileLoop({ + while: constTrue, + body: () => pull, + step: value => { + state = f(state, value); + } + }), () => Effect.succeed(state)); +})))); +/** + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * + * @category running + * @since 4.0.0 + */ +const runFoldEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Effect.suspend(() => { + let state = initial(); + return runWith(self, pull => Effect.whileLoop({ + while: constTrue, + body: constant(pull.pipe(Effect.flatMap(o => f(state, o)), Effect.map(s => { + state = s; + }))), + step: constVoid + }), () => Effect.succeed(state)); +})))); +/** + * Converts a channel to a scoped `Pull` for low-level consumption. + * + * **Details** + * + * The effect requires a `Scope`. The returned pull should be consumed only + * while that scope remains open. Pulls are serialized so only one pull is + * evaluated at a time. + * + * **Example** (Converting channels to pulls) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class PullError extends Data.TaggedError("PullError")<{ + * readonly step: string + * }> {} + * + * // Create a channel + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * const program = Effect.scoped(Effect.gen(function*() { + * const pull = yield* Channel.toPull(numbersChannel) + * return [yield* pull, yield* pull, yield* pull] + * })) + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPull = /*#__PURE__*/(/* unused pure expression or super */ null && (Effect.fnUntraced(function* (self) { + const semaphore = Semaphore.makeUnsafe(1); + const context = yield* Effect.context(); + const scope = Context.get(context, Scope.Scope); + const pull = yield* toTransform(self)(Cause.done(), scope); + return pull.pipe(Effect.provideContext(context), semaphore.withPermits(1)); +}, +/*#__PURE__*/ +// ensure errors are redirected to the pull effect +Effect.catchCause(cause => Effect.succeed(Effect.failCause(cause)))))); +/** + * Converts a channel to a Pull within an existing scope. + * + * **Example** (Converting channels to scoped pulls) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Scope } from "effect" + * + * class ScopedPullError extends Data.TaggedError("ScopedPullError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * // Convert to Pull with explicit scope + * const scopedPullEffect = Effect.gen(function*() { + * const scope = yield* Effect.scope + * const pull = yield* Channel.toPullScoped(numbersChannel, scope) + * return [yield* pull, yield* pull, yield* pull] + * }) + * await Effect.runPromise(Effect.scoped(scopedPullEffect)) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toPullScoped = (self, scope) => toTransform(self)(_Cause_js__rspack_import_6/* .done */.Vw(), scope); +/** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offer(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { + if (Exit.isSuccess(exit)) { + Queue.endUnsafe(queue); + } else { + Queue.failCauseUnsafe(queue, exit.cause); + } + return Effect.void; +})))))); +/** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoQueueArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offerAll(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { + if (Exit.isSuccess(exit)) { + Queue.endUnsafe(queue); + } else { + Queue.failCauseUnsafe(queue, exit.cause); + } + return Effect.void; +})))))); +/** + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Queue } from "effect" + * + * class QueueError extends Data.TaggedError("QueueError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel with data + * const dataChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Convert to queue for concurrent processing + * const program = Effect.scoped(Effect.gen(function*() { + * const queue = yield* Channel.toQueue(dataChannel, { capacity: 32 }) + * return yield* Queue.takeBetween(queue, 5, 5) + * })) + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const scope = yield* Effect.scope; + const queue = yield* Queue.make({ + capacity: typeof options.capacity === "number" ? options.capacity : undefined, + strategy: typeof options.capacity === "number" ? options.strategy : undefined + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* Effect.forkIn(runIntoQueue(self, queue), scope); + return queue; +})))); +/** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors + * @since 4.0.0 + */ +const toQueueArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const scope = yield* Effect.scope; + const queue = yield* Queue.make({ + capacity: typeof options.capacity === "number" ? options.capacity : undefined, + strategy: typeof options.capacity === "number" ? options.strategy : undefined + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* Effect.forkIn(runIntoQueueArray(self, queue), scope); + return queue; +})))); +/** + * Converts a channel to a PubSub for concurrent consumption. + * + * **Details** + * + * `shutdownOnEnd` indicates whether the PubSub should be shut down when the + * channel ends. By default this is `true`. + * + * @category destructors + * @since 2.0.0 + */ +const toPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* Effect.forkScoped(runIntoPubSub(self, pubsub, { + shutdownOnEnd: options.shutdownOnEnd !== false + })); + return pubsub; +})))); +/** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publish(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)))); +const makePubSub = options => Effect.acquireRelease(options.capacity === "unbounded" ? PubSub.unbounded(options) : options.strategy === "dropping" ? PubSub.dropping(options) : options.strategy === "sliding" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown); +/** + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* Effect.forkScoped(runIntoPubSubArray(self, pubsub, { + shutdownOnEnd: options.shutdownOnEnd !== false + })); + return pubsub; +})))); +/** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoPubSubArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publishAll(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)))); +/** + * Converts a channel to a scoped `PubSub` of `Take` values. + * + * **Details** + * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubTake = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* runForEach(self, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped); + return pubsub; +})))); +//# sourceMappingURL=Channel.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Ie: empty, + OB: fromPull, + Pf: provideService, + Py: succeed, + S6: interruptWhen, + Tj: map, + WK: mapEffect, + Z1: fromTransform, + Zm: never, + cf: onExit, + ed: flattenArray, + lB: toPullScoped, + o1: runForEach, + oA: unwrap, + qI: flatMap, + sF: tapError +}); + + +}, +"./node_modules/effect/dist/Clock.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + +/** + * Context reference for the active time service in the environment. + * + * **When to use** + * + * Use when you need to access or provide the full time service, including sleep + * operations, rather than a single timestamp accessor. + * + * **Example** (Accessing the Clock service) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * const program = Effect.gen(function*() { + * const clock = yield* Clock.Clock + * return clock.currentTimeMillisUnsafe() + * }) + * + * await Effect.runPromise(Effect.provideService(program, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link clockWith} for using the current Clock service inside an effect + * @see {@link currentTimeMillis} for reading the current time in milliseconds + * @see {@link currentTimeNanos} for reading the current time in nanoseconds + * + * @category services + * @since 2.0.0 + */ +const Clock = _internal_effect_js__rspack_import_0/* .ClockRef */.a1U; +/** + * Accesses the current Clock service and uses it to run the provided function. + * + * **When to use** + * + * Use when you need the full Clock service interface to perform multiple time + * operations or call unsafe variants within a single effect. + * + * **Example** (Accessing the current Clock service) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * const program = Clock.clockWith((clock) => Effect.sync(() => clock.currentTimeMillisUnsafe())) + * + * await Effect.runPromise(Effect.provideService(program, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link Clock} for the service reference + * @see {@link currentTimeMillis} for convenience accessor that returns milliseconds + * @see {@link currentTimeNanos} for convenience accessor that returns nanoseconds + * @category accessors + * @since 2.0.0 + */ +const clockWith = _internal_effect_js__rspack_import_0/* .clockWith */.RKA; +/** + * Returns an Effect that succeeds with the current Unix time in milliseconds. + * + * **When to use** + * + * Use to create wall-clock timestamps from the active `Clock` service with + * millisecond precision. + * + * **Gotchas** + * + * The value can move backward or forward when the system wall clock is + * corrected, so it is not suitable for measuring elapsed time. + * + * **Example** (Reading milliseconds) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * await Effect.runPromise(Effect.provideService(Clock.currentTimeMillis, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link currentTimeNanos} for nanosecond precision + * @see {@link monotonicTimeNanos} for measuring elapsed time + * @see {@link clockWith} for accessing the full Clock service + * + * @category accessors + * @since 2.0.0 + */ +const currentTimeMillis = _internal_effect_js__rspack_import_0/* .currentTimeMillis */.Rud; +/** + * Returns an Effect that succeeds with the current Unix time in nanoseconds. + * + * **When to use** + * + * Use to create wall-clock timestamps from the active `Clock` service with + * nanosecond precision. + * + * **Gotchas** + * + * The value can move backward or forward when the system wall clock is + * corrected, so it is not suitable for measuring elapsed time. + * The live clock allows up to one second of drift from `Date.now()` before + * re-anchoring. + * + * **Example** (Reading nanoseconds) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * await Effect.runPromise(Effect.provideService(Clock.currentTimeNanos, Clock.Clock, testClock)) // => 1_000_000_000n + * ``` + * + * @see {@link monotonicTimeNanos} for measuring elapsed time + * + * @category accessors + * @since 2.0.0 + */ +const currentTimeNanos = _internal_effect_js__rspack_import_0/* .currentTimeNanos */.s0X; +/** + * Returns an Effect that succeeds with the current monotonic time in + * nanoseconds. + * + * **When to use** + * + * Use to measure elapsed time by subtracting two readings. + * + * **Gotchas** + * + * The value has an arbitrary origin and is unsuitable for serialization. Use + * it only to subtract readings produced by the same clock. Whether it advances + * while the host is suspended depends on the runtime. + * + * @see {@link currentTimeNanos} for Unix wall-clock timestamps + * + * @category accessors + * @since 4.0.0 + */ +const monotonicTimeNanos = _internal_effect_js__rspack_import_0/* .monotonicTimeNanos */.T13; +//# sourceMappingURL=Clock.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + zD: Clock +}); + + +}, +"./node_modules/effect/dist/Combiner.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Creates a `Combiner` from a binary function. + * + * **When to use** + * + * Use when you have a custom combining operation that is not covered by + * the built-in constructors (`min`, `max`, `first`, `last`, `constant`). + * + * **Details** + * + * The returned combiner's `combine` method delegates to the provided function. + * Any purity, associativity, or mutation behavior comes from that function. + * + * **Example** (Multiplying numbers) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Product = Combiner.make((self, that) => self * that) + * + * Product.combine(3, 5) // => 15 + * ``` + * + * @see {@link Combiner} – the interface this creates + * @category constructors + * @since 4.0.0 + */ +function make(combine) { + return { + combine + }; +} +/** + * Reverses the argument order of a combiner's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative combiner such as string concatenation. + * + * **Details** + * + * Returns a new `Combiner` where `combine(self, that)` calls the original + * combiner as `combine(that, self)`. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const Prepend = Combiner.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function flip(combiner) { + return make((self, that) => combiner.combine(that, self)); +} +/** + * Creates a `Combiner` that returns the smaller of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the minimum value across a collection or + * build a `Reducer` that tracks the running minimum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the minimum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Min = Combiner.min(Number.Order) + * + * Min.combine(3, 1) // => 1 + * Min.combine(1, 3) // => 1 + * ``` + * + * @see {@link max} + * @category constructors + * @since 4.0.0 + */ +function min(order) { + return make((self, that) => order(self, that) === -1 ? self : that); +} +/** + * Creates a `Combiner` that returns the larger of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the maximum value across a collection or + * build a `Reducer` that tracks the running maximum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the maximum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Max = Combiner.max(Number.Order) + * + * Max.combine(3, 1) // => 3 + * Max.combine(1, 3) // => 3 + * ``` + * + * @see {@link min} + * @category constructors + * @since 4.0.0 + */ +function max(order) { + return make((self, that) => order(self, that) === 1 ? self : that); +} +/** + * Creates a `Combiner` that always returns the first (left) argument. + * + * **When to use** + * + * Use when you want "first write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `self` and ignores `that`. + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const First = Combiner.first() + * + * First.combine(1, 2) // => 1 + * ``` + * + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function first() { + return make((self, _) => self); +} +/** + * Creates a `Combiner` that always returns the last (right) argument. + * + * **When to use** + * + * Use when you want "last write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `that` and ignores `self`. + * + * **Example** (Keeping the last value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Last = Combiner.last() + * + * Last.combine(1, 2) // => 2 + * ``` + * + * @see {@link first} + * @category constructors + * @since 4.0.0 + */ +function last() { + return make((_, that) => that); +} +/** + * Creates a `Combiner` that ignores both arguments and always returns the + * given constant value. + * + * **When to use** + * + * Use when you need a combiner that always returns a fixed value, including + * when a generic API requires a combiner but the result is predetermined. + * + * **Details** + * + * `combine(self, that)` returns the constant `a` and ignores both arguments. + * + * **Example** (Always returning zero) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Zero = Combiner.constant(0) + * + * Zero.combine(42, 99) // => 0 + * ``` + * + * @see {@link first} + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function constant(a) { + return make(() => a); +} +/** + * Wraps a `Combiner` so that a separator value is inserted between every + * pair of combined elements. + * + * **When to use** + * + * Use when you need to inject a fixed separator between accumulated values, + * such as when building delimited strings, paths, or CSV-like output by + * repeated combination. + * + * **Details** + * + * `intercalate(middle)(combiner).combine(self, that)` is equivalent to + * `combiner.combine(self, combiner.combine(middle, that))`. This function is + * curried: first provide the separator, then the base combiner. + * + * **Example** (Joining strings with a separator) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const commaSep = Combiner.intercalate(",")(String.ReducerConcat) + * + * commaSep.combine("a", "b") // => "a,b" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function intercalate(middle) { + return combiner => make((self, that) => combiner.combine(self, combiner.combine(middle, that))); +} +//# sourceMappingURL=Combiner.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make) +}); + + +}, +"./node_modules/effect/dist/Context.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Effectable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Effectable.js"); +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _Option_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); + + + + + + + +/** + * Runtime type identifier attached to `Context` service keys and used by + * `isKey` to recognize them. + * + * @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 + * + * @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__*/_Effectable_js__rspack_import_0/* .Prototype */.b({ + label: "Service", + evaluate(fiber) { + return (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => f(get(fiber.context, this))); + }, + useSync(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId = "~effect/Context"; +const MaxDepth = 8; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = undefined; + self.baseHits = 0; + 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 makeUnsafe(map); +}; +// A private symbol so user code cannot forge a value that reads as absent +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); + // Misses must not advance the counter: reference-default lookups miss the + // base on every fiber cache refresh, which would flatten every short-lived + // request context and reintroduce the O(services) per-request cost + if (value === undefined && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = undefined; + 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. + * + * **Gotchas** + * + * 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 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = mapUnsafe => makeImpl(undefined, mapUnsafe, undefined, 0); +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ..._internal_core_js__rspack_import_1/* .PipeInspectableProto */.fU, + [TypeId]: { + _Services: _ => _ + }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](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) || !_Equal_js__rspack_import_2/* .equals */.aI(value, other.get(key))) return false; + } + return true; + }, + [_Hash_js__rspack_import_3/* .symbol */.HR]() { + return _Hash_js__rspack_import_3/* .number */.ai(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 + * + * @category guards + * @since 2.0.0 + */ +const isContext = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether the provided argument is a `Key`. + * + * **Example** (Checking for keys) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * Context.isKey(Context.Service("Service")) // => true + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isKey = u => hasProperty(u, ServiceTypeId); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => emptyContext; +const emptyContext = /*#__PURE__*/makeUnsafe(/*#__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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = (key, service) => makeUnsafe(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` + * + * @category combining + * @since 2.0.0 + */ +const add = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** + * Adds a service by key to a given `Context` using a string key. + * + * @category combining + * @since 4.0.0 + */ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? undefined : impl.cacheRoot; + if (impl.depth >= MaxDepth) { + // Rebase the overlay chain into a flat map, keeping the cacheRoot so a + // rebase on an ordinary key does not invalidate fiber caches + const map = new Map(impl.mapUnsafe); + map.set(key, service); + return makeImpl(cacheRoot, map, undefined, 0); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1); +}; +/** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts import.meta.vitest + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * Context.getOption(withPort, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(withoutPort, Port) // => Option.none() + * ``` + * + * @see {@link add} for always storing a service value + * + * @category combining + * @since 4.0.0 + */ +const addOrOmit = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => service._tag === "None" ? omit(key)(self) : add(self, key, service.value)))); +/** + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * + * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") + * const Database = Context.Service<{ query: (sql: string) => string }>( + * "Database" + * ) + * + * const context = Context.make(Logger, { log: (_msg: string) => {} }) + * + * const logger = Context.getOrElse(context, Logger, () => ({ log: () => {} })) + * const database = Context.getOrElse( + * context, + * Database, + * () => ({ query: () => "fallback" }) + * ) + * + * logger === Context.get(context, Logger) // => true + * database.query("SELECT 1") // => "fallback" + * ``` + * + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, orElse) => { + const value = lookup(self, key.key); + if (value !== notFound) return value; + return isReference(key) ? getDefaultValue(key) : orElse(); +}))); +/** + * 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 + * + * @category getters + * @since 4.0.0 + */ +const getOrUndefined = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? undefined : 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 + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @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 = 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 + * + * @category getters + * @since 2.0.0 + */ +const getOption = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, service) => { + const value = lookup(self, service.key); + if (value !== notFound) return _Option_js__rspack_import_6.some(value); + return isReference(service) ? _Option_js__rspack_import_6.some(getDefaultValue(service)) : _Option_js__rspack_import_6.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 + * + * @category combining + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @category combining + * @since 3.12.0 + */ +const mergeAll = (...ctxs) => { + const map = new Map(); + for (let i = 0; i < ctxs.length; i++) { + ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + } + return makeUnsafe(map); +}; +/** + * Returns a new `Context` that contains only the specified services. + * + * **When to use** + * + * Use when you want to keep an allowlist of services in a `Context`. + * + * **Example** (Picking services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.pick(Port)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link omit} for removing selected services + * + * @category filtering + * @since 2.0.0 + */ +const pick = (...services) => self => { + const keep = new Set(services.map(key => key.key)); + return withFlat(self, map => map.forEach((_, key) => { + if (!keep.has(key)) map.delete(key); + })); +}; +/** + * Returns a new `Context` with the specified service keys removed. + * + * **When to use** + * + * Use when you want to remove a denylist of services from a `Context`. + * + * **Example** (Omitting services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.omit(Timeout)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link pick} for keeping selected services + * + * @category filtering + * @since 2.0.0 + */ +const omit = (...keys) => self => withFlat(self, map => { + for (let i = 0; i < keys.length; i++) { + map.delete(keys[i].key); + } +}); +/** + * 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 + * + * @category services + * @since 3.11.0 + */ +const Reference = Service; +//# sourceMappingURL=Context.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Ie: empty, + Jt: get, + L8: make, + LZ: makeUnsafe, + Or: Reference, + Pf: hasSameCache, + Ub: getOrUndefinedUnsafe, + Um: mergeAll, + WQ: add, + Y6: getOrUndefined, + aE: isContext, + fp: getUnsafe, + h1: merge, + kl: Service, + om: getOption +}); + + +}, +"./node_modules/effect/dist/Deferred.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); + + + + + + +const TypeId = "~effect/Deferred"; +/** + * Checks whether a value is a `Deferred`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Deferred` values. + * + * @category guards + * @since 4.0.0 + */ +const isDeferred = u => hasProperty(u, TypeId); +const DeferredProto = { + [TypeId]: { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const makeUnsafe = () => { + const self = Object.create(DeferredProto); + self.resumes = undefined; + self.effect = undefined; + return self; +}; +/** + * Creates a new `Deferred`. + * + * **When to use** + * + * Use to allocate an empty `Deferred` inside an `Effect` workflow. + * + * **Example** (Creating a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = () => _internal_effect_js__rspack_import_2/* .sync */.OH5(() => makeUnsafe()); +const _await = self => _internal_effect_js__rspack_import_2/* .callback */.E2r(resume => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return _internal_effect_js__rspack_import_2/* .sync */.OH5(() => { + // Completion resumes all waiters and clears `resumes`, so a cleanup + // running after completion has nothing to unregister. + const resumes = self.resumes; + if (resumes === undefined) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); + +/** + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. + * + * **When to use** + * + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.complete(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.suspend(() => self.effect ? internalEffect.succeed(false) : into(effect, self))))); +/** + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.completeWith(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion + * @since 2.0.0 + */ +const completeWith = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, effect) => _internal_effect_js__rspack_import_2/* .sync */.OH5(() => doneUnsafe(self, effect))); +/** + * Completes the `Deferred` with the specified `Exit` value, which will be + * propagated to all fibers waiting on the value of the `Deferred`. + * + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.done(deferred, Exit.succeed(42)) + * return yield* Effect.exit(Deferred.await(deferred)) + * }) + * + * await Effect.runPromise(program) // => Exit.succeed(42) + * ``` + * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion + * @since 2.0.0 + */ +const done = completeWith; +/** + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.fail(deferred, "Operation failed") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Operation failed")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, error) => done(self, _internal_core_js__rspack_import_3/* .exitFail */.Rk(error))); +/** + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failSync(deferred, () => "Lazy error") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Lazy error")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => fail(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCause(deferred, Cause.fail("Operation failed")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Operation failed"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => done(self, core.exitFailCause(cause))))); +/** + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCauseSync(deferred, () => Cause.fail("Lazy error")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Lazy error"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCauseSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => failCause(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Something went wrong") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.die(deferred, defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const die = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, defect) => done(self, core.exitDie(defect))))); +/** + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Lazy error") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.dieSync(deferred, () => defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const dieSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => die(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with interruption by the current fiber. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by the current fiber. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with the current fiber id + * only if this call completes it. The returned effect succeeds with `true` + * when this call completed the `Deferred`, or `false` if it was already + * completed. + * + * **Example** (Interrupting a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interrupt(deferred) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] as const + * }) + * + * const [success, exit] = await Effect.runPromise(program) + * success // => true + * Exit.hasInterrupts(exit) // => true + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interrupt = self => core.withFiber(fiber => interruptWith(self, fiber.id)); +/** + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interruptWith(deferred, 42) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.interrupt(42)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interruptWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, fiberId) => failCause(self, internalEffect.causeInterrupt(fiberId))))); +/** + * Returns `true` if this `Deferred` has already been completed with a value or + * an error, `false` otherwise. + * + * **When to use** + * + * Use to check completion status inside an `Effect` workflow. + * + * **Example** (Checking Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.isDone(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.isDone(deferred) + * return [beforeCompletion, afterCompletion] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isDone = self => internalEffect.sync(() => isDoneUnsafe(self)); +/** + * Returns whether this `Deferred` has already been completed synchronously. + * + * **When to use** + * + * Use to check `Deferred` completion synchronously in code that cannot return + * an `Effect`, such as low-level integration code. + * + * @see {@link isDone} for checking completion inside `Effect` + * @see {@link poll} for reading the completed effect when available + * + * @category predicates + * @since 4.0.0 + */ +const isDoneUnsafe = self => self.effect !== undefined; +/** + * Returns the current completion effect as an `Option`. This returns + * `Option.some(effect)` when the `Deferred` is completed, `Option.none()` + * otherwise. + * + * **When to use** + * + * Use to inspect whether a `Deferred` is already completed and retrieve its + * stored completion effect when available. + * + * **Example** (Polling Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Option } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.poll(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.poll(deferred) + * const afterValue = yield* Effect.transposeOption(afterCompletion) + * return [beforeCompletion, afterValue] + * }) + * + * await Effect.runPromise(program) // => [Option.none(), Option.some(42)] + * ``` + * + * @category getters + * @since 2.0.0 + */ +function poll(self) { + return internalEffect.sync(() => Option.fromUndefinedOr(self.effect)); +} +/** + * Attempts to complete the `Deferred` with the specified value. + * + * **When to use** + * + * Use to complete a `Deferred` with a successful value. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, value) => done(self, _internal_core_js__rspack_import_3/* .exitSucceed */.xt(value))); +/** + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.sync(deferred, () => 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const sync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => succeed(self, evaluate()))))); +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + // Clear `resumes` before resuming: a waiter resumed with an interrupt + // cause dies synchronously inside `resume`, and its await cleanup would + // otherwise splice this array mid-iteration and skip the next waiter. + const resumes = self.resumes; + self.resumes = undefined; + for (let i = 0; i < resumes.length; i++) { + resumes[i](effect); + } + } + return true; +}; +/** + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. + * + * **Details** + * + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const successEffect = Effect.succeed(42) + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const isCompleted = yield* Deferred.into(successEffect, deferred) + * const value = yield* Deferred.await(deferred) + * return [isCompleted, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const into = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, deferred) => internalEffect.uninterruptibleMask(restore => internalEffect.flatMap(internalEffect.exit(restore(self)), exit => done(deferred, exit)))))); +//# sourceMappingURL=Deferred.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L8: make, + LZ: makeUnsafe, + Py: succeed, + Tx: _await, + Vw: done, + fJ: fail +}); + + +}, +"./node_modules/effect/dist/Duration.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Represents immutable spans of time. + * + * A `Duration` can be finite, positive infinity, or negative infinity. It is + * the standard representation for delays, timeouts, intervals, and + * time-to-live values across Effect APIs. This module includes constructors + * from common input shapes, unit conversions, comparisons, arithmetic, + * formatting, and reusable reducer or combiner helpers. + * + * @since 2.0.0 + */ + + + + + + + + + + +const TypeId = "~effect/time/Duration"; +const bigint0 = /*#__PURE__*/BigInt(0); +const bigint1 = /*#__PURE__*/BigInt(1); +const bigint2 = /*#__PURE__*/BigInt(2); +const bigint10 = /*#__PURE__*/BigInt(10); +const bigint24 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(24))); +const bigint60 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(60))); +const bigint1e3 = /*#__PURE__*/BigInt(1_000); +const bigint1e6 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000))); +const bigint1e9 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000_000))); +const roundTiesAwayFromZero = input => BigInt(input < 0 ? Math.ceil(input - 0.5) : Math.floor(input + 0.5)); +const roundMillisToNanos = millis => roundTiesAwayFromZero(millis * 1_000_000); +const parseNanos = (input, scale) => { + const decimalIndex = input.indexOf("."); + if (decimalIndex === -1) return BigInt(input) * scale; + const isNegative = input[0] === "-"; + const fractional = input.slice(decimalIndex + 1); + const fractionalScale = bigint10 ** BigInt(fractional.length); + const scaled = (BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) * scale; + const rounded = scaled / fractionalScale + (scaled % fractionalScale * bigint2 >= fractionalScale ? bigint1 : bigint0); + return isNegative ? -rounded : rounded; +}; +const nanosToHrTime = nanos => { + const sign = nanos < bigint0 ? -bigint1 : bigint1; + const absolute = nanos < bigint0 ? -nanos : nanos; + return [Number(sign * (absolute / bigint1e9)), Number(sign * (absolute % bigint1e9))]; +}; +const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; +/** + * Decodes a `Duration.Input` into a `Duration`. + * + * **When to use** + * + * Use when the input has already been validated or comes from a trusted source + * and throwing is acceptable for invalid duration syntax. + * + * **Gotchas** + * + * If the input is not a valid `Duration.Input`, it throws an error. + * + * **Example** (Decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.fromInputUnsafe(1000) // => Duration.millis(1000) + * Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5) + * Duration.fromInputUnsafe("Infinity") // => Duration.infinity + * Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInputUnsafe = input => { + switch (typeof input) { + case "number": + return millis(input); + case "bigint": + return nanos(input); + case "string": + { + if (input === "Infinity") { + return infinity; + } + if (input === "-Infinity") { + return negativeInfinity; + } + const match = DURATION_REGEXP.exec(input); + if (!match) break; + const [_, valueStr, unit] = match; + if (unit === "nano" || unit === "nanos") { + return nanos(parseNanos(valueStr, bigint1)); + } + if (unit === "micro" || unit === "micros") { + return nanos(parseNanos(valueStr, bigint1e3)); + } + const value = Number(valueStr); + switch (unit) { + case "milli": + case "millis": + return millis(value); + case "second": + case "seconds": + return seconds(value); + case "minute": + case "minutes": + return minutes(value); + case "hour": + case "hours": + return hours(value); + case "day": + case "days": + return days(value); + case "week": + case "weeks": + return weeks(value); + } + break; + } + case "object": + { + if (input === null) break; + if (TypeId in input) return input; + if (Array.isArray(input)) { + if (input.length !== 2 || !input.every(_Predicate_js__rspack_import_0/* .isNumber */.Et)) { + return invalid(input); + } + if (Number.isNaN(input[0]) || Number.isNaN(input[1])) { + return zero; + } + if (input[0] === -Infinity || input[1] === -Infinity) { + return negativeInfinity; + } + if (input[0] === Infinity || input[1] === Infinity) { + return infinity; + } + return make(roundTiesAwayFromZero(input[0] * 1_000_000_000 + input[1])); + } + const obj = input; + let millis = 0; + // we can use truthy checks here, because 0 can be ignored + if (obj.weeks) millis += obj.weeks * 604_800_000; + if (obj.days) millis += obj.days * 86_400_000; + if (obj.hours) millis += obj.hours * 3_600_000; + if (obj.minutes) millis += obj.minutes * 60_000; + if (obj.seconds) millis += obj.seconds * 1_000; + if (obj.milliseconds) millis += obj.milliseconds; + if (!obj.microseconds && !obj.nanoseconds) return make(millis); + return make(roundTiesAwayFromZero(millis * 1_000_000 + (obj.microseconds ?? 0) * 1_000 + (obj.nanoseconds ?? 0))); + } + } + return invalid(input); +}; +const invalid = input => { + throw new Error(`Invalid Input: ${input}`); +}; +/** + * Decodes a `Input` value into a `Duration` safely, returning + * `Option.none()` if decoding fails. + * + * **Example** (Safely decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.fromInput(1000) // => Option.some(Duration.seconds(1)) + * Duration.fromInput("invalid" as any) // => Option.none() + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInput = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(fromInputUnsafe))); +const zeroDurationValue = { + _tag: "Millis", + millis: 0 +}; +const infinityDurationValue = { + _tag: "Infinity" +}; +const negativeInfinityDurationValue = { + _tag: "NegativeInfinity" +}; +const DurationProto = { + [TypeId]: TypeId, + [_Hash_js__rspack_import_1/* .symbol */.HR]() { + // Hash equal finite durations using the same canonical nanoseconds + // representation used by `equals`. + switch (this.value._tag) { + case "Millis": + { + const nanos = this.value.millis * 1_000_000; + return Number.isFinite(nanos) ? _Hash_js__rspack_import_1/* .hash */.tW(roundTiesAwayFromZero(nanos)) : _Hash_js__rspack_import_1/* .number */.ai(this.value.millis); + } + case "Nanos": + return _Hash_js__rspack_import_1/* .hash */.tW(this.value.nanos); + default: + return _Hash_js__rspack_import_1/* .structure */.QK(this.value); + } + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](that) { + return isDuration(that) && equals(this, that); + }, + toString() { + switch (this.value._tag) { + case "Infinity": + return "Infinity"; + case "NegativeInfinity": + return "-Infinity"; + case "Nanos": + return `${this.value.nanos} nanos`; + case "Millis": + return `${this.value.millis} millis`; + } + }, + toJSON() { + switch (this.value._tag) { + case "Millis": + return { + _id: "Duration", + _tag: "Millis", + millis: this.value.millis + }; + case "Nanos": + return { + _id: "Duration", + _tag: "Nanos", + nanos: String(this.value.nanos) + }; + case "Infinity": + return { + _id: "Duration", + _tag: "Infinity" + }; + case "NegativeInfinity": + return { + _id: "Duration", + _tag: "NegativeInfinity" + }; + } + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + }, + pipe() { + return (0,_Pipeable_js__rspack_import_4/* .pipeArguments */.tT)(this, arguments); + } +}; +const make = input => { + const duration = Object.create(DurationProto); + if (typeof input === "number") { + if (isNaN(input) || input === 0 || Object.is(input, -0)) { + duration.value = zeroDurationValue; + } else if (!Number.isFinite(input)) { + duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue; + } else if (!Number.isInteger(input)) { + duration.value = { + _tag: "Nanos", + nanos: roundMillisToNanos(input) + }; + } else { + duration.value = { + _tag: "Millis", + millis: input + }; + } + } else if (input === bigint0) { + duration.value = zeroDurationValue; + } else { + duration.value = { + _tag: "Nanos", + nanos: input + }; + } + return duration; +}; +/** + * Checks whether a value is a Duration. + * + * **Example** (Checking for durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isDuration(Duration.seconds(1)) // => true + * Duration.isDuration(1000) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isDuration = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether a Duration is finite (not infinite). + * + * **Example** (Checking finite durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isFinite(Duration.seconds(5)) // => true + * Duration.isFinite(Duration.infinity) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFinite = self => self.value._tag !== "Infinity" && self.value._tag !== "NegativeInfinity"; +/** + * Checks whether a Duration is zero. + * + * **Example** (Checking for zero durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isZero(Duration.zero) // => true + * Duration.isZero(Duration.seconds(1)) // => false + * ``` + * + * @category predicates + * @since 3.5.0 + */ +const isZero = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis === 0; + case "Nanos": + return self.value.nanos === bigint0; + case "Infinity": + case "NegativeInfinity": + return false; + } +}; +/** + * Returns `true` if the duration is negative (strictly less than zero). + * + * **Example** (Checking for negative durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isNegative(Duration.seconds(-5)) // => true + * Duration.isNegative(Duration.zero) // => false + * Duration.isNegative(Duration.negativeInfinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isNegative = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis < 0; + case "Nanos": + return self.value.nanos < bigint0; + case "NegativeInfinity": + return true; + case "Infinity": + return false; + } +}; +/** + * Returns `true` if the duration is positive (strictly greater than zero). + * + * **Example** (Checking for positive durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isPositive(Duration.seconds(5)) // => true + * Duration.isPositive(Duration.zero) // => false + * Duration.isPositive(Duration.infinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isPositive = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis > 0; + case "Nanos": + return self.value.nanos > bigint0; + case "Infinity": + return true; + case "NegativeInfinity": + return false; + } +}; +/** + * Returns the absolute value of the duration. + * + * **Example** (Taking absolute duration values) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.abs(Duration.seconds(-5)) // => Duration.seconds(5) + * Duration.abs(Duration.negativeInfinity) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const abs = self => { + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis < 0 ? make(-self.value.millis) : self; + case "Nanos": + return self.value.nanos < bigint0 ? make(-self.value.nanos) : self; + } +}; +/** + * Returns the negated duration. + * + * **Example** (Negating durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.negate(Duration.seconds(5)) // => Duration.seconds(-5) + * Duration.negate(Duration.infinity) // => Duration.negativeInfinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const negate = self => { + switch (self.value._tag) { + case "Infinity": + return negativeInfinity; + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis === 0 ? self : make(-self.value.millis); + case "Nanos": + return self.value.nanos === bigint0 ? self : make(-self.value.nanos); + } +}; +/** + * A Duration representing zero time. + * + * **Example** (Referencing the zero duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.zero) // => 0 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const zero = /*#__PURE__*/make(0); +/** + * A Duration representing infinite time. + * + * **Example** (Referencing infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.infinity) // => Infinity + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const infinity = /*#__PURE__*/make(Infinity); +/** + * A Duration representing negative infinite time. + * + * **Example** (Referencing negative infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.negativeInfinity) // => -Infinity + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const negativeInfinity = /*#__PURE__*/make(-Infinity); +/** + * Creates a Duration from nanoseconds. + * + * **Example** (Creating durations from nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const nanos = nanos => make(nanos); +/** + * Creates a Duration from microseconds. + * + * **Example** (Creating durations from microseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.micros(500_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const micros = micros => make(micros * bigint1e3); +/** + * Creates a Duration from milliseconds. + * + * **Example** (Creating durations from milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.millis(1000)) // => 1000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const millis = millis => make(millis); +/** + * Creates a Duration from seconds. + * + * **Example** (Creating durations from seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(30)) // => 30_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const seconds = seconds => make(seconds * 1000); +/** + * Creates a Duration from minutes. + * + * **Example** (Creating durations from minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.minutes(5)) // => 300_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const minutes = minutes => make(minutes * 60_000); +/** + * Creates a Duration from hours. + * + * **Example** (Creating durations from hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.hours(2)) // => 7_200_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const hours = hours => make(hours * 3_600_000); +/** + * Creates a Duration from days. + * + * **Example** (Creating durations from days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.days(1)) // => 86_400_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const days = days => make(days * 86_400_000); +/** + * Creates a Duration from weeks. + * + * **Example** (Creating durations from weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.weeks(1)) // => 604_800_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const weeks = weeks => make(weeks * 604_800_000); +/** + * Converts a Duration to milliseconds. + * + * **Example** (Converting durations to milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(5)) // => 5000 + * Duration.toMillis(Duration.minutes(2)) // => 120_000 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toMillis = self => match(fromInputUnsafe(self), { + onMillis: _Function_js__rspack_import_5/* .identity */.D_, + onNanos: nanos => Number(nanos) / 1_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to seconds. + * + * **Example** (Converting durations to seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toSeconds(Duration.millis(5000)) // => 5 + * Duration.toSeconds(Duration.minutes(2)) // => 120 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toSeconds = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 1_000, + onNanos: nanos => Number(nanos) / 1_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to minutes. + * + * **Example** (Converting durations to minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMinutes(Duration.seconds(120)) // => 2 + * Duration.toMinutes(Duration.hours(1)) // => 60 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toMinutes = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 60_000, + onNanos: nanos => Number(nanos) / 60_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to hours. + * + * **Example** (Converting durations to hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHours(Duration.minutes(120)) // => 2 + * Duration.toHours(Duration.days(1)) // => 24 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toHours = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 3_600_000, + onNanos: nanos => Number(nanos) / 3_600_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to days. + * + * **Example** (Converting durations to days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toDays(Duration.hours(48)) // => 2 + * Duration.toDays(Duration.weeks(1)) // => 7 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toDays = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 86_400_000, + onNanos: nanos => Number(nanos) / 86_400_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to weeks. + * + * **Example** (Converting durations to weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toWeeks(Duration.days(14)) // => 2 + * Duration.toWeeks(Duration.days(7)) // => 1 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toWeeks = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 604_800_000, + onNanos: nanos => Number(nanos) / 604_800_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Gets the duration in nanoseconds as a bigint. + * + * **When to use** + * + * Use when the duration is known to be finite and you need the nanosecond value + * as a `bigint`. + * + * **Details** + * + * Millisecond-backed fractional durations are rounded to the nearest + * nanosecond, with ties away from zero. + * + * **Gotchas** + * + * If the duration is infinite, it throws an error. + * + * **Example** (Reading nanoseconds unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n + * + * // Duration.toNanosUnsafe(Duration.infinity) + * // throws Error: "Cannot convert infinite duration to nanos" + * ``` + * + * @category getters + * @since 4.0.0 + */ +const toNanosUnsafe = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + throw new Error("Cannot convert infinite duration to nanos"); + case "Nanos": + return self.value.nanos; + case "Millis": + return roundMillisToNanos(self.value.millis); + } +}; +/** + * Gets the duration in nanoseconds safely as an `Option`. + * + * **Details** + * + * If the duration is infinite, returns `Option.none()`. + * + * **Example** (Safely reading nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.toNanos(Duration.seconds(1)) // => Option.some(1_000_000_000n) + * Duration.toNanos(Duration.infinity) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toNanos = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(toNanosUnsafe))); +/** + * Converts a Duration to high-resolution time format [seconds, nanoseconds]. + * + * **Example** (Converting durations to high-resolution time) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHrTime(Duration.millis(1500)) // => [1, 500_000_000] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toHrTime = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + return [Infinity, 0]; + case "NegativeInfinity": + return [-Infinity, 0]; + case "Nanos": + return nanosToHrTime(self.value.nanos); + case "Millis": + return nanosToHrTime(roundMillisToNanos(self.value.millis)); + } +}; +/** + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.match(Duration.seconds(5), { + * onMillis: (millis) => `${millis} milliseconds`, + * onNanos: (nanos) => `${nanos} nanoseconds`, + * onInfinity: () => "infinite" + * }) // => "5000 milliseconds" + * ``` + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, options) => { + switch (self.value._tag) { + case "Millis": + return options.onMillis(self.value.millis); + case "Nanos": + return options.onNanos(self.value.nanos); + case "Infinity": + return options.onInfinity(); + case "NegativeInfinity": + return (options.onNegativeInfinity ?? options.onInfinity)(); + } +}); +/** + * Pattern matches on two `Duration`s, providing handlers that receive both values. + * + * **Example** (Pattern matching on duration pairs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.matchPair(Duration.seconds(3), Duration.seconds(2), { + * onMillis: (a, b) => a + b, + * onNanos: (a, b) => Number(a + b), + * onInfinity: () => Infinity + * }) // => 5000 + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchPair = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, that, options) => { + if (self.value._tag === "Infinity" || self.value._tag === "NegativeInfinity" || that.value._tag === "Infinity" || that.value._tag === "NegativeInfinity") return options.onInfinity(self, that); + if (self.value._tag === "Millis") { + return that.value._tag === "Millis" ? options.onMillis(self.value.millis, that.value.millis) : options.onNanos(toNanosUnsafe(self), that.value.nanos); + } else { + return options.onNanos(self.value.nanos, toNanosUnsafe(that)); + } +}); +/** + * Provides an `Order` instance for comparing `Duration` values. + * + * **Details** + * + * `NegativeInfinity` < any finite value < `Infinity`. + * + * **Example** (Sorting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * const durations = [ + * Duration.seconds(3), + * Duration.seconds(1), + * Duration.seconds(2) + * ] + * durations.sort((a, b) => Duration.Order(a, b)).map(Duration.toSeconds) // => [1, 2, 3] + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Order = /*#__PURE__*/(/* unused pure expression or super */ null && (order.make((self, that) => matchPair(self, that, { + onMillis: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onNanos: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onInfinity: (self, that) => { + if (self.value._tag === that.value._tag) return 0; + if (self.value._tag === "Infinity") return 1; + if (self.value._tag === "NegativeInfinity") return -1; + // self is finite + if (that.value._tag === "Infinity") return -1; + // that is NegativeInfinity + return 1; + } +})))); +/** + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.between(Duration.seconds(3), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => true + * ``` + * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * + * @category predicates + * @since 2.0.0 + */ +const between = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isBetween(Order))); +/** + * Provides an `Equivalence` instance for comparing `Duration` values. + * + * **Example** (Comparing durations for equivalence) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Equivalence = (self, that) => matchPair(self, that, { + onMillis: (self, that) => self === that, + onNanos: (self, that) => self === that, + onInfinity: (self, that) => self.value._tag === that.value._tag +}); +/** + * Returns the smaller of two Durations. + * + * **Example** (Selecting the shorter duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.min(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(3) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (order.min(Order))); +/** + * Returns the larger of two Durations. + * + * **Example** (Selecting the longer duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.max(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (order.max(Order))); +/** + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.clamp(Duration.seconds(10), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const clamp = /*#__PURE__*/(/* unused pure expression or super */ null && (order.clamp(Order))); +/** + * Divides a `Duration` by a finite, non-zero number safely. + * + * **Details** + * + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.divide(Duration.seconds(10), 2) // => Option.some(Duration.seconds(5)) + * Duration.divide(Duration.seconds(10), 0) // => Option.none() + * ``` + * + * @category math + * @since 2.4.19 + */ +const divide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return Option.none(); + if (by === 0 || Object.is(by, -0)) return Option.none(); + return match(self, { + onMillis: millis => Option.some(make(millis / by)), + onNanos: nanos => { + try { + return Option.some(make(nanos / BigInt(by))); + } catch { + return Option.none(); + } + }, + onInfinity: () => Option.some(by > 0 ? infinity : negativeInfinity), + onNegativeInfinity: () => Option.some(by > 0 ? negativeInfinity : infinity) + }); +}))); +/** + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.divideUnsafe(Duration.seconds(10), 2) // => Duration.seconds(5) + * Duration.divideUnsafe(Duration.seconds(10), 0) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const divideUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return zero; + return match(self, { + onMillis: millis => make(millis / by), + onNanos: nanos => { + if (Object.is(by, 0) || Object.is(by, -0)) { + if (nanos === bigint0) return zero; + // match IEEE 754: same sign → +infinity, different sign → -infinity + const positiveNanos = nanos > bigint0; + const positiveZero = Object.is(by, 0); + return positiveNanos === positiveZero ? infinity : negativeInfinity; + } + try { + return make(nanos / BigInt(by)); + } catch { + return zero; + } + }, + onInfinity: () => by > 0 ? infinity : by < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => by > 0 ? negativeInfinity : by < 0 ? infinity : zero + }); +}))); +/** + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.times(Duration.seconds(5), 2) // => Duration.seconds(10) + * ``` + * + * @category math + * @since 2.0.0 + */ +const times = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, times) => match(self, { + onMillis: millis => make(millis * times), + onNanos: nanos => make(nanos * BigInt(times)), + onInfinity: () => times > 0 ? infinity : times < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => times > 0 ? negativeInfinity : times < 0 ? infinity : zero +})))); +/** + * Subtracts one Duration from another. The result can be negative. + * + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.subtract(Duration.seconds(10), Duration.seconds(3)) // => Duration.seconds(7) + * ``` + * + * @category math + * @since 2.0.0 + */ +const subtract = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self - that), + onNanos: (self, that) => make(self - that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity") return t === "Infinity" ? zero : infinity; + if (s === "NegativeInfinity") return t === "NegativeInfinity" ? zero : negativeInfinity; + return t === "Infinity" ? negativeInfinity : infinity; + } +})))); +/** + * Adds two Durations together. + * + * **Details** + * + * Infinity addition follows these rules: + * + * - infinity + infinity = infinity + * - infinity + negativeInfinity = zero + * - infinity + finite = infinity + * - negativeInfinity + negativeInfinity = negativeInfinity + * - negativeInfinity + finite = negativeInfinity + * + * **Example** (Adding durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.sum(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(8) + * ``` + * + * @category math + * @since 2.0.0 + */ +const sum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self + that), + onNanos: (self, that) => make(self + that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity" && t === "NegativeInfinity") return zero; + if (s === "NegativeInfinity" && t === "Infinity") return zero; + if (s === "Infinity" || t === "Infinity") return infinity; + if (s === "NegativeInfinity" || t === "NegativeInfinity") return negativeInfinity; + // unreachable, but satisfy TS + return zero; + } +})))); +/** + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThan(Duration.seconds(3), Duration.seconds(5)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThan(Order))); +/** + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThanOrEqualTo(Order))); +/** + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThan(Duration.seconds(5), Duration.seconds(3)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThan(Order))); +/** + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThanOrEqualTo(Order))); +/** + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const equals = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, that) => Equivalence(self, that)); +/** + * Decomposes a `Duration` into normalized signed components. + * + * **Details** + * + * Finite durations are returned as `{ days, hours, minutes, seconds, millis, + * nanos }`. Infinite durations return every component as `Infinity` or + * `-Infinity`. + * + * **Example** (Decomposing durations into parts) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * // Create a complex duration by adding multiple parts + * const duration = Duration.sum( + * Duration.sum( + * Duration.sum(Duration.days(1), Duration.hours(2)), + * Duration.sum(Duration.minutes(30), Duration.seconds(45)) + * ), + * Duration.millis(123) + * ) + * Duration.parts(duration) // => ({ days: 1, hours: 2, minutes: 30, seconds: 45, millis: 123, nanos: 0 }) + * + * const complex = Duration.sum(Duration.hours(25), Duration.minutes(90)) + * Duration.parts(complex) // => ({ days: 1, hours: 2, minutes: 30, seconds: 0, millis: 0, nanos: 0 }) + * ``` + * + * @category converting + * @since 3.8.0 + */ +const parts = self => { + if (self.value._tag === "Infinity") { + return { + days: Infinity, + hours: Infinity, + minutes: Infinity, + seconds: Infinity, + millis: Infinity, + nanos: Infinity + }; + } + if (self.value._tag === "NegativeInfinity") { + return { + days: -Infinity, + hours: -Infinity, + minutes: -Infinity, + seconds: -Infinity, + millis: -Infinity, + nanos: -Infinity + }; + } + const n = toNanosUnsafe(self); + const neg = n < bigint0; + const a = neg ? -n : n; + const ms = a / bigint1e6; + const sec = ms / bigint1e3; + const min = sec / bigint60; + const hr = min / bigint60; + const d = hr / bigint24; + const sign = neg ? -1 : 1; + return { + days: sign * Number(d), + hours: sign * Number(hr % bigint24), + minutes: sign * Number(min % bigint60), + seconds: sign * Number(sec % bigint60), + millis: sign * Number(ms % bigint1e3), + nanos: sign * Number(a % bigint1e6) + }; +}; +/** + * Converts a `Duration` to a human readable string. + * + * **Example** (Formatting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.format(Duration.millis(1000)) // => "1s" + * Duration.format(Duration.millis(1001)) // => "1s 1ms" + * ``` + * + * @category converting + * @since 2.0.0 + */ +const format = self => { + if (self.value._tag === "Infinity") { + return "Infinity"; + } + if (self.value._tag === "NegativeInfinity") { + return "-Infinity"; + } + if (isZero(self)) { + return "0"; + } + if (isNegative(self)) { + return "-" + format(abs(self)); + } + const fragments = parts(self); + const pieces = []; + if (fragments.days !== 0) { + pieces.push(`${fragments.days}d`); + } + if (fragments.hours !== 0) { + pieces.push(`${fragments.hours}h`); + } + if (fragments.minutes !== 0) { + pieces.push(`${fragments.minutes}m`); + } + if (fragments.seconds !== 0) { + pieces.push(`${fragments.seconds}s`); + } + if (fragments.millis !== 0) { + pieces.push(`${fragments.millis}ms`); + } + if (fragments.nanos !== 0) { + pieces.push(`${fragments.nanos}ns`); + } + return pieces.join(" "); +}; +/** + * Reducer for summing `Duration`s. + * + * **When to use** + * + * Use to sum many `Duration` values through APIs that consume a `Reducer`. + * + * **Details** + * + * `ReducerSum` uses `sum` and starts from `zero`, so `combineAll([])` returns + * `zero`. + * + * @see {@link sum} for adding two duration values directly + * @see {@link CombinerMax} for keeping the longest duration instead of summing + * @see {@link CombinerMin} for keeping the shortest duration instead of summing + * + * @category math + * @since 4.0.0 + */ +const ReducerSum = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make(sum, zero))); +/** + * Combiner that returns the maximum `Duration`. + * + * **When to use** + * + * Use to keep the longest `Duration` when an API consumes a `Combiner`. + * + * @see {@link CombinerMin} for keeping the shortest `Duration` + * @see {@link max} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMax = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.max(Order))); +/** + * Combiner that returns the minimum `Duration`. + * + * **When to use** + * + * Use to keep the shortest `Duration` through APIs that consume a `Combiner`. + * + * @see {@link CombinerMax} for keeping the longest `Duration` + * @see {@link min} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMin = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.min(Order))); +//# sourceMappingURL=Duration.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Tn: infinity, + bN: fromInputUnsafe, + cF: nanos, + kE: toMillis, + ne: millis, + v_: zero +}); + + +}, +"./node_modules/effect/dist/Effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _internal_executionPlan_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/executionPlan.js"); +/* import */ var _internal_layer_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/layer.js"); +/* import */ var _internal_request_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/request.js"); +/* import */ var _internal_schedule_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/schedule.js"); + + + + + + + + + + + + + + +/** + * Runtime identifier used to recognize `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .EffectTypeId */.$n; +/** + * Checks whether a value is an `Effect`. + * + * **Example** (Checking whether a value is an Effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * Effect.isEffect(Effect.succeed(1)) // => true + * Effect.isEffect("hello") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEffect = _internal_core_js__rspack_import_0/* .isEffect */.yw; +/** + * 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. + * @category combining + * @since 2.0.0 + */ +const all = _internal_effect_js__rspack_import_1/* .all */.Q7R; +/** + * Applies an effectful function to each element and partitions failures and + * successes. + * + * **Details** + * + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. + * + * This function runs every effect and never fails. Use `concurrency` to control + * parallelism. + * + * **Example** (Separating successes and failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.partition([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromise(program) // => [['0 is even', '2 is even'], [1, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = _internal_effect_js__rspack_import_1/* .partition */.jBG; +/** + * Reduces elements from left to right with an effectful accumulator function. + * + * **When to use** + * + * Use when each accumulation step is effectful and must run sequentially in + * iteration order. + * + * **Details** + * + * The accumulator function receives the current accumulator, the current + * element, and its zero-based index. The `zero` function is evaluated each + * time the effect runs. An empty iterable succeeds with its result. If a step + * fails, remaining elements are not processed. + * + * **Example** (Summing values sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.reduce( + * [1, 2, 3], + * () => 0, + * (total, value, index) => + * Effect.sync(() => { output.push(`Adding ${value} at index ${index}`) }).pipe( + * Effect.as(total + value) + * ) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Adding 1 at index 0", "Adding 2 at index 1", "Adding 3 at index 2", 6] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = _internal_effect_js__rspack_import_1/* .reduce */.TSs; +/** + * Applies an effectful function to each element and accumulates all failures. + * + * **Details** + * + * This function always evaluates every element. If at least one effect fails, + * all failures are returned as a non-empty array and successes are discarded. + * If all effects succeed, it returns all collected successes. + * + * Use `discard: true` to ignore successful values while still validating all + * elements. + * + * **Example** (Validating every element) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const program = Effect.validate([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromiseExit(program) // => Exit.fail(["0 is even", "2 is even"]) + * ``` + * + * @category validation + * @since 2.0.0 + */ +const validate = _internal_effect_js__rspack_import_1/* .validate */.tfT; +/** + * Returns the first element that satisfies an effectful predicate. + * + * **Details** + * + * The predicate receives the element and its index. Evaluation short-circuits + * as soon as an element matches. + * + * **Example** (Finding the first successful match) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.findFirst([1, 2, 3, 4], (n) => Effect.succeed(n > 2)) + * + * await Effect.runPromise(program) // => Option.some(3) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _internal_effect_js__rspack_import_1/* .findFirst */.i8i; +/** + * Returns the first value that passes an effectful `FilterEffect`. + * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * + * The filter receives the element and index. Evaluation short-circuits on the + * first `Result.succeed` and returns the transformed value in `Option.some`. + * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category searching + * @since 4.0.0 + */ +const findFirstFilter = _internal_effect_js__rspack_import_1/* .findFirstFilter */.kAe; +/** + * Executes an effectful operation for each element in an `Iterable`. + * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * + * **Details** + * + * The `forEach` function applies a provided operation to each element in the + * iterable, producing a new effect that returns an array of results. + * + * If any effect fails, the iteration stops immediately (short-circuiting), and + * the error is propagated. + * + * Concurrency: + * + * The `concurrency` option controls how many operations are performed + * concurrently. By default, the operations are performed sequentially. + * + * Discarding Results: + * + * If the `discard` option is set to `true`, the intermediate results are not + * collected, and the final result of the operation is `void`. + * + * **Example** (Mapping over an iterable with effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)) + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", [2, 4, 6, 8, 10]] + * ``` + * + * **Example** (Running effects without collecting results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Apply effects but discard the results + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)), + * { discard: true } + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", undefined] + * ``` + * + * @see {@link all} for combining multiple effects into one. + * @category sequencing + * @since 2.0.0 + */ +const forEach = _internal_effect_js__rspack_import_1/* .forEach */.jJl; +/** + * Returns the first element of the iterable produced by an effect, or fails + * with `NoSuchElementError` if the iterable is empty. + * + * **When to use** + * + * Use when an effect produces a collection that must contain at least one + * element and absence should be represented in the typed error channel. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const first = await Effect.runPromise(Effect.head(Effect.succeed([1, 2, 3]))) + * first // => 1 + * + * const empty = Effect.head(Effect.succeed([] as Array)).pipe(Effect.catchNoSuchElement) + * await Effect.runPromise(empty) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = _internal_effect_js__rspack_import_1/* .head */.d5f; +/** + * Executes a body effect repeatedly while a condition holds true. + * + * **Example** (Repeating an effectful loop) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let counter = 0 + * + * const program = Effect.whileLoop({ + * while: () => counter < 5, + * body: () => Effect.sync(() => ++counter), + * step: (n) => void output.push(`Current count: ${n}`) + * }) + * + * await Effect.runPromise(program) + * output // => ["Current count: 1", "Current count: 2", "Current count: 3", "Current count: 4", "Current count: 5"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const whileLoop = _internal_effect_js__rspack_import_1/* .whileLoop */.iMI; +// ----------------------------------------------------------------------------- +// Creating Effects +// ----------------------------------------------------------------------------- +/** + * Creates an `Effect` that represents an asynchronous computation guaranteed to + * succeed. + * + * **When to use** + * + * Use to convert a `Promise` into an `Effect` when the async operation is + * guaranteed to succeed and will not reject. + * + * **Details** + * + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. + * + * **Gotchas** + * + * The `Promise` must not reject. If it rejects, the rejection is treated as a + * defect, not as a typed failure. Use `tryPromise` when rejection is expected. + * + * Interruption aborts the provided `AbortSignal`, but the underlying + * asynchronous operation only stops if it observes that signal. + * + * **Example** (Wrapping a non-rejecting Promise) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const succeedAsync = (message: string) => + * Effect.promise(() => Promise.resolve(message)) + * + * // ┌─── Effect + * // ▼ + * const program = succeedAsync("Async operation completed successfully!") + * await Effect.runPromise(program) // => "Async operation completed successfully!" + * ``` + * + * @see {@link tryPromise} for a version that can handle failures. + * @category constructors + * @since 2.0.0 + */ +const promise = _internal_effect_js__rspack_import_1/* .promise */.ivC; +/** + * Creates an `Effect` from an asynchronous computation that may throw or + * reject, mapping failures into the error channel. + * + * **When to use** + * + * Use when you need to perform asynchronous operations that might fail, such + * as fetching data from an API, and want thrown exceptions or rejected promises + * captured as Effect errors. + * + * **Details** + * + * The promise thunk is evaluated when the effect runs. If it returns a promise + * that resolves, the resolved value becomes the success value. If the thunk + * throws before returning a promise, or if the returned promise rejects, the + * thrown or rejected value is mapped into the error channel. + * + * Passing the thunk directly maps failures to {@link Cause.UnknownError}. + * Passing `{ try, catch }` uses `catch` to map failures to an error of type + * `E`. + * + * The thunk receives an `AbortSignal` that is aborted if the effect is + * interrupted. The underlying asynchronous operation only stops if it observes + * that signal. + * + * **Gotchas** + * + * If `catch` throws while mapping the error, that thrown value is treated as a + * defect. Return the error value you want in the error channel instead of + * throwing it. + * + * **Example** (Wrapping a fetch request that may fail) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const getTodo = (id: number) => + * Effect.tryPromise(() => Promise.resolve({ id, completed: false })) + * + * // ┌─── Effect<{ id: number; completed: boolean }, UnknownError, never> + * // ▼ + * const program = getTodo(1) + * await Effect.runPromise(program) // => { id: 1, completed: false } + * ``` + * + * **Example** (Mapping Promise rejections to a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TodoFetchError extends Data.TaggedError("TodoFetchError")<{ readonly cause: unknown }> {} + * + * const getTodo = (id: number) => + * Effect.tryPromise({ + * try: () => Promise.reject(`Todo ${id} is unavailable`), + * // remap the error + * catch: (cause) => new TodoFetchError({ cause }) + * }) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.flip(getTodo(1)) + * const error = await Effect.runPromise(program) + * error._tag // => "TodoFetchError" + * ``` + * + * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. + * @category constructors + * @since 2.0.0 + */ +const tryPromise = _internal_effect_js__rspack_import_1/* .tryPromise */.$mh; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_effect_js__rspack_import_1/* .succeed */.PyW; +/** + * Returns an effect which succeeds with `None`. + * + * **Example** (Succeeding with Option.none) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedNone + * + * Effect.runSync(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedNone = _internal_effect_js__rspack_import_1/* .succeedNone */.lwU; +/** + * Returns an effect which succeeds with the value wrapped in a `Some`. + * + * **Example** (Succeeding with Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedSome(42) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedSome = _internal_effect_js__rspack_import_1/* .succeedSome */.nGE; +/** + * Creates an `Effect` lazily, delaying construction until it is needed. + * + * **When to use** + * + * Use when you need to defer the evaluation of an effect until it is required. + * + * **Details** + * + * `suspend` takes a thunk that represents an effect and delays creating it + * until the suspended effect is evaluated. This is useful for optimizing + * expensive computations, managing circular dependencies such as recursive + * functions, and helping TypeScript unify return types when branches construct + * different effects. Any side effects or scoped captures inside the thunk are + * re-executed on each invocation. + * + * **Example** (Lazily evaluating side effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * let i = 0 + * + * const bad = Effect.succeed(i++) + * + * const good = Effect.suspend(() => Effect.succeed(i++)) + * + * Effect.runSync(bad) // => 0 + * Effect.runSync(bad) // => 0 + * + * Effect.runSync(good) // => 1 + * Effect.runSync(good) // => 2 + * ``` + * + * **Example** (Suspending recursive Fibonacci evaluation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const blowsUp = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b) + * + * // console.log(Effect.runSync(blowsUp(32))) + * // crash: JavaScript heap out of memory + * + * const allGood = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith( + * Effect.suspend(() => allGood(n - 1)), + * Effect.suspend(() => allGood(n - 2)), + * (a, b) => a + b + * ) + * + * Effect.runSync(allGood(16)) // => 1597 + * ``` + * + * **Example** (Helping TypeScript infer recursive effect types) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Without suspend, TypeScript may struggle with type inference. + * // Inferred type: + * // (a: number, b: number) => + * // Effect | Effect + * const withoutSuspend = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * + * // Using suspend to unify return types. + * // Inferred type: + * // (a: number, b: number) => Effect + * const withSuspend = (a: number, b: number) => + * Effect.suspend(() => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * ) + * + * Effect.runSync(withSuspend(6, 2)) // => 3 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = _internal_effect_js__rspack_import_1/* .suspend */.DYE; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const sync = _internal_effect_js__rspack_import_1/* .sync */.OH5; +const void_ = _internal_effect_js__rspack_import_1/* ["void"] */.rIH; + +const undefined_ = _internal_effect_js__rspack_import_1/* .undefined */.Vxk; + +/** + * Creates an `Effect` from a callback-based asynchronous API. + * + * **When to use** + * + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. + * + * **Details** + * + * The registration function receives a `resume` callback and, when requested, + * an `AbortSignal`. Call `resume` at most once with the effect that should + * complete the fiber; later calls are ignored. Return an optional cleanup + * effect from the registration function to run if the fiber is interrupted. + * + * **Example** (Integrating callback APIs) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fromCallback = (message: string) => + * Effect.callback((resume) => { + * queueMicrotask(() => { + * void output.push(message) + * resume(Effect.void) + * }) + * }) + * + * await Effect.runPromise(fromCallback("callback completed")) + * output // => ["callback completed"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = _internal_effect_js__rspack_import_1/* .callback */.E2r; +/** + * Returns an effect that will never produce anything. The moral equivalent of + * `while(true) {}`, only without the wasted CPU cycles. + * + * **Example** (Creating a never-ending effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.timeoutOption(Effect.never, 0) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = _internal_effect_js__rspack_import_1/* .never */.ZmZ; +/** + * Effect that succeeds with an empty record `{}`, used as the starting point + * for do notation chains. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * const program = pipe( + * Effect.Do, + * Effect.bind("x", () => Effect.succeed(2)), + * Effect.bind("y", ({ x }) => Effect.succeed(x + 1)), + * Effect.let("sum", ({ x, y }) => x + y) + * ) + * + * Effect.runSync(program) // => { x: 2, y: 3, sum: 5 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Do = _internal_effect_js__rspack_import_1.Do; +/** + * Gives a name to the success value of an `Effect`, creating a single-key + * record used in do notation pipelines. + * + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = _internal_effect_js__rspack_import_1/* .bindTo */.JrD; +const let_ = _internal_effect_js__rspack_import_1/* ["let"] */.uVU; + +/** + * Adds an `Effect` value to the do notation record under a given name. + * + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category sequencing + * @since 2.0.0 + */ +const bind = _internal_effect_js__rspack_import_1/* .bind */.oIE; +/** + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const gen = _internal_effect_js__rspack_import_1/* .gen */.JkU; +/** + * Creates an `Effect` that represents a recoverable error. + * + * **When to use** + * + * Use to explicitly signal a recoverable error in an `Effect`. + * + * **Details** + * + * The error keeps propagating unless it is handled. You can handle tagged + * errors with functions like {@link catchTag} or {@link catchTags}. + * + * **Example** (Creating a failed effect) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {} + * + * // ┌─── Effect + * // ▼ + * const failure = Effect.fail( + * new OperationFailedError() + * ) + * Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError" + * ``` + * + * @see {@link succeed} to create an effect that represents a successful value. + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_effect_js__rspack_import_1/* .fail */.fJG; +/** + * Creates an `Effect` that represents a recoverable error using a lazy evaluation. + * + * **When to use** + * + * Use to defer computing a recoverable error value until the effect is run. + * + * **Details** + * + * The error-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating failures) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ProgramError extends Data.TaggedError("ProgramError")<{ readonly operation: string }> {} + * + * const program = Effect.failSync(() => new ProgramError({ operation: "sync" })) + * + * Effect.runSync(Effect.flip(program)).operation // => "sync" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = _internal_effect_js__rspack_import_1/* .failSync */.gOk; +/** + * Creates an `Effect` that represents a failure with a specific `Cause`. + * + * **When to use** + * + * Use when you already have a full `Cause` and need to preserve defects, + * interruptions, annotations, or combined failures in the effect's failure + * channel. + * + * **Details** + * + * This function allows you to create effects that fail with complex error + * structures, including multiple errors, defects, interruptions, and more. + * + * **Example** (Failing with a full Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCause( + * Cause.fail("Network error") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Network error" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_effect_js__rspack_import_1/* .failCause */.ATB; +/** + * Creates an `Effect` that represents a failure with a `Cause` computed lazily. + * + * **When to use** + * + * Use to defer computing a full `Cause` until the effect is run. + * + * **Details** + * + * The cause-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCauseSync(() => + * Cause.fail("Error computed at runtime") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Error computed at runtime" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = _internal_effect_js__rspack_import_1/* .failCauseSync */.pVV; +/** + * Creates an effect that terminates a fiber with a specified error. + * + * **When to use** + * + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. + * + * **Details** + * + * The `die` function is used to signal a defect, which represents a critical + * and unexpected error in the code. When invoked, it produces an effect that + * does not handle the error and instead terminates the fiber. + * + * The error channel of the resulting effect is of type `never`, indicating that + * it cannot recover from this failure. + * + * **Example** (Failing on division by zero) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const defect = new Error("Cannot divide by zero") + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.die(defect) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = divide(1, 0) + * + * Effect.runSyncExit(program) // => Exit.die(defect) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_effect_js__rspack_import_1/* .die */.F_Q; +const try_ = _internal_effect_js__rspack_import_1/* ["try"] */.SvU; + +/** + * Yields control back to the Effect runtime, allowing other fibers to execute. + * + * **Example** (Yielding to other fibers) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("Before yield") + * yield* Effect.yieldNow + * void output.push("After yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["Before yield", "After yield"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const yieldNow = _internal_effect_js__rspack_import_1/* .yieldNow */.m9E; +/** + * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute. + * + * **Example** (Yielding with priority) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("High priority task") + * yield* Effect.yieldNowWith(10) // Higher priority + * void output.push("Continued after yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["High priority task", "Continued after yield"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const yieldNowWith = _internal_effect_js__rspack_import_1/* .yieldNowWith */.KN3; +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const withFiber = _internal_core_js__rspack_import_0/* .withFiber */.R6; +// ----------------------------------------------------------------------------- +// Conversions +// ----------------------------------------------------------------------------- +/** + * Converts a `Result` to an `Effect`. + * + * **Example** (Converting a Result into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * const output: Array = [] + * + * const success = Result.succeed(42) + * const failure = Result.fail("Something went wrong") + * + * const effect1 = Effect.fromResult(success) + * const effect2 = Effect.fromResult(failure) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))) + * output // => [42, "Something went wrong"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromResult = _internal_effect_js__rspack_import_1/* .fromResult */.yUA; +/** + * Converts an `Option` into an `Effect`. + * + * **When to use** + * + * Use when absence should become a typed `NoSuchElementError` in the effect error + * channel. + * + * **Details** + * + * `Option.some` becomes a successful effect with the contained value, while + * `Option.none` becomes a failed effect. By default the failure is a + * `NoSuchElementError`, but you can provide an `onNone` callback to customize + * the error value. + * + * **Example** (Converting an Option into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Option.some(42) + * const none = Option.none() + * + * const effect1 = Effect.fromOption(some) + * const effect2 = Effect.fromOption(none) + * const effect3 = Effect.fromOption(none, () => new Error("missing")) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))._tag) + * void output.push(Effect.runSync(Effect.flip(effect3)).message) + * output // => [42, "NoSuchElementError", "missing"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromOption = _internal_effect_js__rspack_import_1/* .fromOption */.sVm; +/** + * Converts an `Option` of an `Effect` into an `Effect` of an `Option`. + * + * **When to use** + * + * Use when an effect should run only when an optional value is present, while + * preserving absence as a successful `None`. + * + * **Details** + * + * - `None` becomes an effect that succeeds with `None` + * - `Some(effect)` runs the inner effect and wraps its success value in `Some` + * - Inner failures are preserved in the resulting effect + * + * **Example** (Transposing an Option of an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const some = Option.some(Effect.succeed(42)) + * + * // ┌─── Effect, never, never> + * // ▼ + * const program = Effect.transposeOption(some) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category converting + * @since 3.13.0 + */ +const transposeOption = _internal_effect_js__rspack_import_1/* .transposeOption */.pkL; +/** + * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` + * when the value is `null` or `undefined`. + * + * **Example** (Failing on nullish values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.fn(function*(input: string | null) { + * const value = yield* Effect.fromNullishOr(input) + * yield* Effect.sync(() => { output.push(value) }) + * }, + * Effect.catch(() => Effect.sync(() => { output.push("missing") })) + * ) + * + * await Effect.runPromise(program(null)) + * await Effect.runPromise(program("hello")) + * output // => ["missing", "hello"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = _internal_effect_js__rspack_import_1/* .fromNullishOr */.bJ; +// ----------------------------------------------------------------------------- +// Mapping +// ----------------------------------------------------------------------------- +/** + * Chains effects to produce new `Effect` instances, useful for combining + * operations that depend on previous results. + * + * **When to use** + * + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. + * + * **Details** + * + * `flatMap` lets you sequence effects so that the result of one effect can be + * used in the next step. It is similar to `flatMap` used with arrays but works + * specifically with `Effect` instances, allowing you to avoid deeply nested + * effect structures. + * + * Since effects are immutable, `flatMap` always returns a new effect instead of + * changing the original one. + * + * **Example** (Choosing flatMap syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * + * void output.push(Effect.runSync(Effect.all([ + * flatMappedWithPipe, + * flatMappedWithDataFirst, + * flatMappedWithMethod + * ]))) + * output // => [[2, 2, 2]] + * ``` + * + * **Example** (Sequencing dependent effects) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Chaining the fetch and discount application using `flatMap` + * const finalAmount = pipe( + * fetchTransactionAmount, + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(finalAmount) // => 95 + * ``` + * + * @see {@link tap} for a version that ignores the result of the effect. + * @category sequencing + * @since 2.0.0 + */ +const flatMap = _internal_effect_js__rspack_import_1/* .flatMap */.qIB; +/** + * Flattens an `Effect` that produces another `Effect` into a single effect. + * + * **Example** (Flattening nested effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const nested = Effect.succeed(Effect.succeed("hello")) + * + * const program = Effect.gen(function*() { + * const value = yield* Effect.flatten(nested) + * yield* Effect.sync(() => { output.push(value) }) + * }) + * + * Effect.runSync(program) + * output // => ["hello"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = _internal_effect_js__rspack_import_1/* .flatten */.Bqz; +/** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. + * + * **When to use** + * + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. + * + * **Details** + * + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. + * + * **Example** (Choosing andThen syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") + * + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * + * void output.push(Effect.runSync(Effect.all([ + * transformedWithPipe, + * transformedWithDataFirst, + * transformedWithMethod + * ]))) + * output // => [['done', 'done', 'done']] + * ``` + * + * **Example** (Sequencing a discount calculation after fetching a total) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Using Effect.map and Effect.flatMap + * const result1 = pipe( + * fetchTransactionAmount, + * Effect.map((amount) => amount * 2), + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result1) // => 190 + * + * // Using Effect.andThen + * const result2 = pipe( + * fetchTransactionAmount, + * Effect.andThen((amount) => Effect.succeed(amount * 2)), + * Effect.andThen((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result2) // => 190 + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = _internal_effect_js__rspack_import_1/* .andThen */.hgn; +/** + * 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] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tap = _internal_effect_js__rspack_import_1/* .tap */.Mim; +/** + * Converts both success and failure of an `Effect` into a `Result` type. + * + * **When to use** + * + * Use when you want an `Effect`'s typed failures to be handled as `Result` + * data while preserving the original error value. + * + * **Details** + * + * This function converts an effect that may fail into an effect that always + * succeeds, wrapping the outcome in a `Result` type. The result will be + * `Result.Failure` if the effect fails, containing the recoverable error, or + * `Result.Success` if it succeeds, containing the result. + * + * Using this function, you can handle recoverable errors explicitly without + * causing the effect to fail. This is particularly useful in scenarios where + * you want to chain effects and manage both success and failure in the same + * logical flow. + * + * The resulting effect cannot fail directly because all recoverable failures + * are represented inside the `Result` type. + * + * **Gotchas** + * + * `result` only captures typed, recoverable failures. Defects and + * interruptions are not captured inside the `Result` and still fail the + * effect. + * + * **Example** (Capturing success or failure as Result) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.result(success) + * const program2 = Effect.result(failure) + * + * Effect.runSync(program1) // => Result.succeed(42) + * + * Effect.runSync(program2) // => Result.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 4.0.0 + */ +const result = _internal_effect_js__rspack_import_1/* .result */.Ket; +/** + * Converts success to `Option.some` and failure to `Option.none`. + * + * **When to use** + * + * Use when you only care whether an effect succeeds and want recoverable + * failures represented as `Option.none`. + * + * **Details** + * + * Success values become `Option.some`, recoverable failures become + * `Option.none`, and defects still fail the effect. + * + * **Gotchas** + * + * `option` only captures typed, recoverable failures as `Option.none`. + * Defects and interruptions are not captured inside the `Option` and still + * fail the effect. + * + * `option` also discards typed failure values. Use `result` if the failure + * value matters. + * + * **Example** (Capturing success or failure as Option) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.all([ + * Effect.option(Effect.succeed(1)), + * Effect.option(Effect.fail("missing")) + * ]) + * + * Effect.runSync(program) // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link result} for a version that uses `Result` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 2.0.0 + */ +const option = _internal_effect_js__rspack_import_1/* .option */.uKv; +/** + * Transforms an effect to encapsulate both failure and success using the `Exit` + * data type. + * + * **When to use** + * + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. + * + * **Details** + * + * `exit` wraps an effect's success or failure inside an `Exit` type, allowing + * you to handle both cases explicitly. + * + * The resulting effect cannot fail because the failure is encapsulated within + * the `Exit.Failure` type. The error type is set to `never`, indicating that + * the effect is structured to never fail directly. + * + * **Example** (Capturing completion as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.exit(success) + * const program2 = Effect.exit(failure) + * + * Effect.runSync(program1) // => Exit.succeed(42) + * + * Effect.runSync(program2) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link result} for a version that uses `Result` instead. + * + * @category error handling + * @since 2.0.0 + */ +const exit = _internal_effect_js__rspack_import_1/* .exit */.NS5; +/** + * 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. + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .map */.TjK; +/** + * Replaces the value inside an effect with a constant value. + * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * + * `as` allows you to ignore the original value inside an effect and + * replace it with a new constant value. + * + * **Example** (Replacing a success value) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * // Replaces the value 5 with the constant "new value" + * const program = pipe(Effect.succeed(5), Effect.as("new value")) + * + * Effect.runSync(program) // => "new value" + * ``` + * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping + * @since 2.0.0 + */ +const as = _internal_effect_js__rspack_import_1.as; +/** + * Maps the success value of an `Effect` to `Some`, preserving failures. + * + * **Example** (Wrapping success in Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.asSome(Effect.succeed(42)) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asSome = _internal_effect_js__rspack_import_1/* .asSome */.Xx$; +/** + * Maps the success value of an `Effect` to `void`, preserving failures. + * + * **Example** (Discarding success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.asVoid(Effect.succeed(42)) + * + * Effect.runSync(program) // => undefined + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .asVoid */.NLW; +/** + * Swaps an effect's success and failure channels. + * + * **When to use** + * + * Use to swap an `Effect`'s success and failure channels. + * + * **Details** + * + * For an `Effect`, the returned effect has type `Effect`. + * + * **Example** (Swapping success and failure channels) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const program = Effect.fail("Oh uh!").pipe(Effect.as(2)) + * + * // ┌─── Effect + * // ▼ + * const flipped = Effect.flip(program) + * Effect.runSync(flipped) // => "Oh uh!" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flip = _internal_effect_js__rspack_import_1/* .flip */.UUz; +// ----------------------------------------------------------------------------- +// Zipping +// ----------------------------------------------------------------------------- +/** + * Combines two effects into a single effect, producing a tuple with the results of both effects. + * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * + * The `zip` function executes the first effect (left) and then the second effect (right). + * Once both effects succeed, their results are combined into a tuple. + * + * Concurrency: + * + * By default, `zip` processes the effects sequentially. To execute the effects concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two effects sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Combine the two effects together + * // + * // ┌─── Effect<[number, string], never, never> + * // ▼ + * const program = Effect.zip(task1, task2) + * + * Effect.runSync(program) // => [1, 'hello'] + * ``` + * + * **Example** (Combining two effects concurrently) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Run both effects concurrently using the concurrent option + * const program = Effect.zip(task1, task2, { concurrent: true }) + * + * await Effect.runPromise(program) // => [1, 'hello'] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. + * + * @category zipping + * @since 2.0.0 + */ +const zip = _internal_effect_js__rspack_import_1/* .zip */.yU6; +/** + * Combines two effects sequentially and applies a function to their results to + * produce a single value. + * + * **When to use** + * + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. + * + * **Details** + * + * Concurrency: + * + * By default, the effects are run sequentially. To execute them concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two success values with a function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * const task3 = Effect.zipWith( + * task1, + * task2, + * // Combines results into a single value + * (number, string) => number + string.length + * ) + * + * Effect.runSync(task3) // => 6 + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = _internal_effect_js__rspack_import_1/* .zipWith */.OYO; +// ----------------------------------------------------------------------------- +// Error handling +// ----------------------------------------------------------------------------- +const catch_ = _internal_effect_js__rspack_import_1/* .catch_ */.h_t; + +/** + * Catches and handles specific errors by their `_tag` field, which is used as a + * discriminator. + * + * **When to use** + * + * Use when you need to recover from one specific tagged error in an effect + * error channel. + * + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class NetworkError { + * readonly _tag = "NetworkError" + * constructor(readonly message: string) {} + * } + * + * class ValidationError { + * readonly _tag = "ValidationError" + * constructor(readonly message: string) {} + * } + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError("offline")) + * + * const program = Effect.catchTag( + * task, + * "NetworkError", + * (error) => Effect.succeed(`Recovered from network error: ${error.message}`) + * ) + * + * Effect.runSync(program) // => "Recovered from network error: offline" + * ``` + * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling + * @since 2.0.0 + */ +const catchTag = _internal_effect_js__rspack_import_1/* .catchTag */.KuX; +/** + * Handles multiple errors in a single block of code using their `_tag` field. + * + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** + * + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. + * + * The error type must have a readonly `_tag` field to use `catchTags`. This + * field is used to identify and match errors. + * + * **Example** (Handling multiple tagged errors) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * // Define tagged error types + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * message: string + * }> {} + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * // An effect that might fail with multiple error types + * const program: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 503 })) + * + * // Handle multiple error types at once + * const handled = Effect.catchTags(program, { + * ValidationError: (error) => + * Effect.succeed(`Validation failed: ${error.message}`), + * NetworkError: (error) => Effect.succeed(`Network error: ${error.statusCode}`) + * }) + * + * Effect.runSync(handled) // => "Network error: 503" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTags = _internal_effect_js__rspack_import_1/* .catchTags */.loE; +/** + * Catches a specific reason within a tagged error. + * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * + * Use this to handle nested error causes without removing the parent error + * from the error channel. The handler receives the unwrapped reason. + * + * **Example** (Handling an error reason) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Handle rate limits specifically + * const handled = program.pipe( + * Effect.catchReason("AiError", "RateLimitError", (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`) + * ) + * ) + * + * Effect.runSync(handled) // => "Retry after 30s" + * ``` + * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = _internal_effect_js__rspack_import_1/* .catchReason */.AXC; +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * **Example** (Handling multiple error reasons) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new QuotaExceededError({ limit: 100 }) }) + * ) + * + * const handled = program.pipe( + * Effect.catchReasons("AiError", { + * RateLimitError: (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`), + * QuotaExceededError: (reason) => + * Effect.succeed(`Quota exceeded: ${reason.limit}`) + * }) + * ) + * + * Effect.runSync(handled) // => "Quota exceeded: 100" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = _internal_effect_js__rspack_import_1/* .catchReasons */.zt4; +/** + * Promotes nested reason errors into the Effect error channel, replacing + * the parent error. + * + * **Example** (Extracting the reason from a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Before: Effect + * // After: Effect + * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) + * Effect.runSync(Effect.flip(unwrapped))._tag // => "RateLimitError" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const unwrapReason = _internal_effect_js__rspack_import_1/* .unwrapReason */.scW; +/** + * Handles both recoverable and unrecoverable errors by providing a recovery + * effect. + * + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. + * + * **Details** + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically shouldn't be recovered from, as + * they often indicate serious issues. However, in some cases, such as + * dynamically loaded plugins, controlled recovery might be needed. + * + * **Example** (Recovering from full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * // An effect that might fail in different ways + * const program = Effect.die("Something went wrong") + * + * // Recover from any cause (including defects) + * const recovered = Effect.catchCause(program, (cause) => { + * if (Cause.hasDies(cause)) { + * return Effect.sync(() => { output.push("Caught defect") }).pipe( + * Effect.as("Recovered from defect") + * ) + * } + * return Effect.succeed("Unknown error") + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = _internal_effect_js__rspack_import_1/* .catchCause */.Tyx; +/** + * Recovers from defects using a provided recovery function. + * + * **When to use** + * + * Use when you need to report or translate defects at integration boundaries. + * + * **Details** + * + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. + * + * **Example** (Recovering from defects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // An effect that might throw an unexpected error (defect) + * const program = Effect.sync(() => { + * throw new Error("Unexpected error") + * }) + * + * // Recover from defects only + * const recovered = Effect.catchDefect(program, (defect) => { + * return Effect.sync(() => { output.push(`Caught defect: ${(defect as Error).message}`) }).pipe( + * Effect.as("Recovered from defect") + * ) + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect: Unexpected error", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchDefect = _internal_effect_js__rspack_import_1/* .catchDefect */.Fig; +/** + * Recovers from specific errors using a `Predicate` or `Refinement`. + * + * **When to use** + * + * Use when you need to recover from errors that match a condition. + * + * **Details** + * + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. + * + * **Example** (Recovering when a predicate matches) + * + * ```ts import.meta.vitest + * import { Data, Effect, Filter } from "effect" + * + * class NotFound extends Data.TaggedError("NotFound")<{ id: string }> {} + * + * const program = Effect.fail(new NotFound({ id: "user-1" })) + * + * // With a refinement + * const recovered = program.pipe( + * Effect.catchIf( + * (error): error is NotFound => error._tag === "NotFound", + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * // With a Filter + * const recovered2 = program.pipe( + * Effect.catchFilter( + * Filter.tagged("NotFound"), + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * Effect.runSync(Effect.all([recovered, recovered2])) // => ['missing:user-1', 'missing:user-1'] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchIf = _internal_effect_js__rspack_import_1/* .catchIf */.XWm; +/** + * Recovers from specific errors using a `Filter`. + * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = _internal_effect_js__rspack_import_1/* .catchFilter */.osR; +/** + * Catches `NoSuchElementError` failures and converts them to `Option.none`. + * + * **When to use** + * + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. + * + * **Details** + * + * Success values become `Option.some`, `NoSuchElementError` becomes + * `Option.none`, and all other errors are preserved. + * + * **Example** (Recovering from missing Option values) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Effect.fromNullishOr(1).pipe(Effect.catchNoSuchElement) + * const none = Effect.fromNullishOr(null).pipe(Effect.catchNoSuchElement) + * + * void output.push(Effect.runSync(some)) + * void output.push(Effect.runSync(none)) + * output // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError` + * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError` + * @see {@link option} for converting any failure into `Option.none` + * + * @category error handling + * @since 4.0.0 + */ +const catchNoSuchElement = _internal_effect_js__rspack_import_1/* .catchNoSuchElement */.U9Y; +/** + * Recovers from specific failures based on a predicate. + * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * + * This function allows you to conditionally catch and recover from failures + * that match a specific predicate. This is useful when you want to handle + * only certain types of errors while letting others propagate. + * + * **Example** (Recovering from selected causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * const httpRequest = Effect.fail("Network Error") + * + * // Only catch network-related failures + * const program = Effect.catchCauseIf( + * httpRequest, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Caught network error: ${Cause.squash(cause)}`) }) + * return "Fallback response" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Caught network error: Network Error", "Fallback response"] + * ``` + * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = _internal_effect_js__rspack_import_1/* .catchCauseIf */.sJf; +/** + * Recovers from specific failures based on a `Filter`. + * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk; +/** + * Transforms the failure value of an effect without changing its success value. + * + * **When to use** + * + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const mapped = Effect.mapError( + * simulatedTask, + * (message) => new TaskError({ message }) + * ) + * Effect.runSync(Effect.flip(mapped)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .mapError */.xm_; +/** + * Applies transformations to both the success and error channels of an effect. + * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * + * **Details** + * + * This function takes two map functions as arguments: one for the error channel + * and one for the success channel. You can use it when you want to modify both + * the error and the success values without altering the overall success or + * failure status of the effect. + * + * **Example** (Transforming success and failure channels) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const modified = Effect.mapBoth(simulatedTask, { + * onFailure: (message) => new TaskError({ message }), + * onSuccess: (n) => n > 0 + * }) + * Effect.runSync(Effect.flip(modified)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapError} for a version that operates on the error channel. + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .mapBoth */.UcN; +/** + * Converts typed failures from the error channel into defects, removing the + * error type from the returned effect. + * + * **When to use** + * + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. + * + * **Example** (Converting typed failures into defects) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * + * class DivideByZeroError extends Data.TaggedError("DivideByZeroError")<{}> {} + * + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new DivideByZeroError()) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.orDie(divide(1, 0)) + * + * Effect.runSyncExit(program) // => Exit.die(new DivideByZeroError()) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = _internal_effect_js__rspack_import_1/* .orDie */.QgK; +/** + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. + * + * **Example** (Running effects on failure) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a task that fails with an error + * const task: Effect.Effect = Effect.fail("NetworkError") + * + * // Use tapError to log the error message when the task fails + * const tapping = Effect.tapError( + * task, + * (error) => Effect.sync(() => { output.push(`expected error: ${error}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping)) + * output // => ["expected error: NetworkError", Exit.fail("NetworkError")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = _internal_effect_js__rspack_import_1/* .tapError */.sFT; +/** + * Runs an effectful handler when a failure's `_tag` matches. + * + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * field: string + * }> {} + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 504 })) + * + * const program = Effect.tapErrorTag(task, "NetworkError", (error) => + * Effect.sync(() => { output.push(`expected error: ${error.statusCode}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["expected error: 504", Exit.fail(new NetworkError({ statusCode: 504 }))] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapErrorTag = _internal_effect_js__rspack_import_1/* .tapErrorTag */.k$L; +/** + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** + * + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. + * + * **Details** + * + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. + * + * **Example** (Observing full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.tapCause( + * task, + * (cause) => Effect.sync(() => { output.push(`Logging cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging cause: Something went wrong", Exit.fail("Something went wrong")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = _internal_effect_js__rspack_import_1/* .tapCause */.dGm; +/** + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** + * + * This function allows you to tap into the cause of an effect's failure only when + * the cause matches a specific predicate. This is useful for conditional logging, + * monitoring, or other side effects based on the type of failure. + * + * **Example** (Observing selected failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Network timeout") + * + * // Only log causes that contain failures (not interrupts or defects) + * const program = Effect.tapCauseIf( + * task, + * Cause.hasFails, + * (cause) => Effect.sync(() => { output.push(`Logging failure cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging failure cause: Network timeout", Exit.fail("Network timeout")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseIf = _internal_effect_js__rspack_import_1/* .tapCauseIf */.cA6; +/** + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. + * + * **Details** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseFilter = _internal_effect_js__rspack_import_1/* .tapCauseFilter */.bKC; +/** + * Runs an effectful operation when the source effect dies with a defect. + * + * **Details** + * + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. + * + * **Example** (Observing defects) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a severe failure in the system + * const task2: Effect.Effect = Effect.die( + * "Something went wrong" + * ) + * + * // Log the defect using tapDefect + * const tapping2 = Effect.tapDefect( + * task2, + * (defect) => Effect.sync(() => { output.push(`defect: ${defect}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping2)) + * output // => ["defect: Something went wrong", Exit.die("Something went wrong")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapDefect = _internal_effect_js__rspack_import_1/* .tapDefect */.nAi; +/** + * Retries an effect until it succeeds, discarding failures. + * + * **Details** + * + * Yields between attempts so other fibers can run. + * + * **Example** (Retrying until success) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let attempts = 0 + * + * const flaky = Effect.gen(function*() { + * attempts++ + * yield* Effect.sync(() => { output.push(`Attempt ${attempts}`) }) + * if (attempts < 3) { + * return yield* Effect.fail("Not ready") + * } + * return "Ready" + * }) + * + * const program = Effect.eventually(flaky) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Attempt 1", "Attempt 2", "Attempt 3", "Ready"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const eventually = _internal_effect_js__rspack_import_1/* .eventually */.u4Y; +/** + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. + * + * **Details** + * + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. + * + * **Gotchas** + * + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. + * + * Defects and interruptions are not retried. + * + * **Example** (Retrying with a schedule) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * + * class AttemptError extends Data.TaggedError("AttemptError")<{ readonly attempt: number }> {} + * + * let attempt = 0 + * const task = Effect.callback((resume) => { + * attempt++ + * if (attempt <= 2) { + * resume(Effect.fail(new AttemptError({ attempt }))) + * } else { + * resume(Effect.succeed("Success!")) + * } + * }) + * + * const policy = Schedule.recurs(5) + * const program = Effect.retry(task, policy) + * + * await Effect.runPromise(program) // => "Success!" + * ``` + * + * @see {@link retryOrElse} for a version that allows you to run a fallback. + * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. + * @category error handling + * @since 2.0.0 + */ +const retry = _internal_schedule_js__rspack_import_2/* .retry */.L5; +/** + * Retries a failing effect and runs a fallback effect if retries are exhausted. + * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * + * **Details** + * + * The `Effect.retryOrElse` function attempts to retry a failing effect multiple + * times according to a defined {@link Schedule} policy. + * + * If the retries are exhausted and the effect still fails, it runs a fallback + * effect instead. + * + * **Example** (Falling back after retries are exhausted) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * const output: Array = [] + * + * class NetworkTimeoutError extends Data.TaggedError("NetworkTimeoutError")<{}> {} + * + * let attempt = 0 + * const networkRequest = Effect.gen(function*() { + * attempt++ + * yield* Effect.sync(() => { output.push(`Network attempt ${attempt}`) }) + * if (attempt < 3) { + * return yield* Effect.fail(new NetworkTimeoutError()) + * } + * return "Network data" + * }) + * + * // Retry up to 2 times, then fall back to cached data + * const program = Effect.retryOrElse( + * networkRequest, + * Schedule.recurs(2), + * (error, retryCount) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`All ${retryCount} retries failed, using cache`) }) + * return "Cached data" + * }) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Network attempt 1", "Network attempt 2", "Network attempt 3", "Network data"] + * ``` + * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling + * @since 2.0.0 + */ +const retryOrElse = _internal_schedule_js__rspack_import_2/* .retryOrElse */.$L; +/** + * Exposes an effect's full failure cause in the error channel as `Cause`. + * + * **Details** + * + * Use `sandbox` when downstream error handling needs to distinguish typed + * failures, defects, and interruptions. Use `unsandbox` to restore the original + * typed error channel after cause-level handling. + * + * **Example** (Exposing failures as causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * // Sandbox exposes the full cause as the error type + * const program = Effect.gen(function*() { + * const result = yield* Effect.flip(Effect.sandbox(task)) + * return `Caught cause: ${Cause.squash(result)}` + * }) + * + * Effect.runSync(program) // => "Caught cause: Something went wrong" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const sandbox = _internal_effect_js__rspack_import_1/* .sandbox */._Sg; +/** + * Discards both the success and failure values of an effect. + * + * **When to use** + * + * Use when an effect should run for its side effects while both success and + * failure values are discarded. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Discarding success and failure values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const task = Effect.fail("Uh oh!").pipe(Effect.as(5)) + * + * // ┌─── Effect + * // ▼ + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * **Example** (Logging failures while ignoring results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("Uh oh!") + * + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const ignore = _internal_effect_js__rspack_import_1/* .ignore */.XeO; +/** + * Ignores the effect's failure cause, including defects and interruptions. + * + * **When to use** + * + * Use when a best-effort effect should never fail, even from defects or + * interruption, and optional cause logging is enough. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Ignoring failures and logging causes) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("boom") + * + * const program = task.pipe(Effect.ignoreCause) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = _internal_effect_js__rspack_import_1/* .ignoreCause */.GrF; +/** + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources + * until it succeeds or the plan is exhausted. + * + * **Details** + * + * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), + * and retry timing is derived per step (the first attempt uses the remaining + * attempts schedule; later retries apply the step schedule at least once). + * + * Attempts can be observed from outside the effect by passing + * `options.onEvent`, which receives an `ExecutionPlan.Event` before each + * attempt and after it settles. The handler is awaited inline before and after + * every attempt, so events are strictly ordered; keep it cheap. It cannot + * fail, which keeps observation from changing the plan's outcome, and its + * requirements are added to the resulting effect. Terminal events run like + * finalizers, so they are emitted even when the attempt is interrupted. + * + * **Example** (Retrying with an execution plan) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }), attempts: 2 }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const program = Effect.withExecutionPlan(fetchUrl, plan) + * Effect.runSync(program) // => "good" + * ``` + * + * **Example** (Observing execution-plan attempts) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }) }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const events: Array = [] + * const program = Effect.withExecutionPlan(fetchUrl, plan, { + * onEvent: (event) => Effect.sync(() => events.push(`${event._tag}:${event.stepIndex}`)) + * }) + * + * await Effect.runPromise(program) // => "good" + * + * events // => ["AttemptStart:0", "AttemptFailure:0", "AttemptStart:1", "AttemptSuccess:1"] + * ``` + * + * @category error handling + * @since 3.16.0 + */ +const withExecutionPlan = _internal_executionPlan_js__rspack_import_3/* .withExecutionPlan */.OR; +/** + * Runs an effect and reports any errors to the configured `ErrorReporter`s. + * + * **Details** + * + * If the `defectsOnly` option is set to `true`, only defects (unrecoverable + * errors) will be reported, while regular failures will be ignored. + * + * @category error handling + * @since 4.0.0 + */ +const withErrorReporting = _internal_effect_js__rspack_import_1/* .withErrorReporting */.$$g; +// ----------------------------------------------------------------------------- +// Fallback +// ----------------------------------------------------------------------------- +/** + * Recovers from a typed failure by producing a fallback success value. + * + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. + * + * Defects and interruptions are not recovered by this operator. + * + * **Example** (Replacing failures with a value) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const validate = (age: number): Effect.Effect => { + * if (age < 0) { + * return Effect.fail("NegativeAgeError") + * } else if (age < 18) { + * return Effect.fail("IllegalAgeError") + * } else { + * return Effect.succeed(age) + * } + * } + * + * const program = Effect.orElseSucceed(validate(-1), () => 18) + * + * Effect.runSyncExit(program) // => Exit.succeed(18) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSucceed = _internal_effect_js__rspack_import_1/* .orElseSucceed */.DM4; +/** + * Runs a sequence of effects and returns the result of the first successful + * one. + * + * **When to use** + * + * Use when you have prioritized fallback `Effect`s, such as attempting + * multiple APIs, reading configuration from several sources, or trying + * alternative resource locations in order. + * + * **Details** + * + * This function executes the provided effects in sequence, stopping at the + * first success. If an effect succeeds, its result is returned immediately and + * no further effects in the sequence are executed. + * + * If all effects fail, the returned effect fails with the error from the last + * effect. If the collection is empty, the returned effect defects with an + * `Error` whose message is `"Received an empty collection of effects"`. + * + * **Example** (Trying alternatives until one succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const primary = Effect.fail("primary unavailable") + * const secondary = Effect.succeed("secondary result") + * const tertiary = Effect.sync(() => { + * throw new Error("not evaluated") + * }) + * + * const program = Effect.firstSuccessOf([ + * primary, + * secondary, + * tertiary + * ]) + * + * Effect.runSync(program) // => "secondary result" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const firstSuccessOf = _internal_effect_js__rspack_import_1/* .firstSuccessOf */.Dd; +// ----------------------------------------------------------------------------- +// Delays & timeouts +// ----------------------------------------------------------------------------- +/** + * Adds a time limit to an effect, triggering a timeout if the effect exceeds + * the duration. + * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * + * The `timeout` function allows you to specify a time limit for an + * effect's execution. If the effect does not complete within the given time, a + * `TimeoutError` is raised. This can be useful for controlling how long your + * program waits for a task to finish, ensuring that it doesn't hang + * indefinitely if the task takes too long. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const timedEffect = Effect.never.pipe(Effect.timeout(0)) + * const error = await Effect.runPromise(Effect.flip(timedEffect)) + * error._tag // => "TimeoutError" + * ``` + * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timeout = _internal_effect_js__rspack_import_1/* .timeout */.wRz; +/** + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. + * + * **When to use** + * + * Use when a timeout of an `Effect` should be handled as `Option.none`. + * + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const timedOutEffect = Effect.never.pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(timedOutEffect) // => Option.none() + * ``` + * + * @see {@link timeout} for a version that raises a `TimeoutError`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 3.1.0 + */ +const timeoutOption = _internal_effect_js__rspack_import_1/* .timeoutOption */.D52; +/** + * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. + * + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.timeoutOrElse(Effect.never, { + * duration: 0, + * orElse: () => Effect.sync(() => { output.push("Query timed out, using cached data") }).pipe( + * Effect.as("Cached result") + * ) + * }) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Query timed out, using cached data", "Cached result"] + * ``` + * + * @see {@link timeout} for failing with a `TimeoutError`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 + */ +const timeoutOrElse = _internal_effect_js__rspack_import_1/* .timeoutOrElse */.mgX; +/** + * Returns an effect that is delayed from this effect by the specified + * `Duration`. + * + * **Example** (Delaying an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.delay(Effect.sync(() => { output.push("Delayed message") }), 0) + * + * await Effect.runPromise(program) + * output // => ["Delayed message"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const delay = _internal_effect_js__rspack_import_1/* .delay */.cbG; +/** + * Returns an effect that suspends the current fiber for the specified duration + * without blocking a JavaScript thread. + * + * **Example** (Pausing without blocking) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Start") }) + * yield* Effect.sleep(0) + * yield* Effect.sync(() => { output.push("End") }) + * }) + * + * await Effect.runPromise(program) + * output // => ["Start", "End"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const sleep = _internal_effect_js__rspack_import_1/* .sleep */.yy4; +/** + * Returns the runtime duration of an effect together with its result. + * + * **Details** + * + * The original success, failure, or interruption is preserved; only the success + * value is paired with the duration. + * + * **Example** (Measuring execution time) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const [, value] = yield* Effect.timed(Effect.succeed("ok")) + * return value + * }) + * + * Effect.runSync(program) // => "ok" + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timed = _internal_effect_js__rspack_import_1/* .timed */.ayu; +// ----------------------------------------------------------------------------- +// Racing +// ----------------------------------------------------------------------------- +/** + * Runs multiple effects concurrently and returns the first successful result. + * + * **When to use** + * + * Use when early failures should be ignored until a success occurs + * or all effects fail. + * + * **Details** + * + * Early failures do not finish the race; `raceAll` keeps waiting until one + * effect succeeds or every effect has failed. When one effect succeeds, the + * remaining effects are interrupted. If every effect fails, the returned effect + * fails with a cause containing the collected failure reasons. + * + * **Example** (Racing many effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAll([ + * Effect.succeed("Fast"), + * Effect.never + * ]) + * await Effect.runPromise(raced) // => "Fast" + * ``` + * + * @see {@link race} for a version that handles only two effects. + * @category racing + * @since 2.0.0 + */ +const raceAll = _internal_effect_js__rspack_import_1/* .raceAll */.Vdx; +/** + * Runs multiple effects concurrently and completes with the first effect to + * finish, whether it succeeds or fails. + * + * **Details** + * + * After the first effect completes, all remaining effects are interrupted. Use + * `raceAll` when early failures should be ignored until a success occurs or + * all effects fail. + * + * **Example** (Taking the first settled result) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAllFirst([ + * Effect.fail("First failed"), + * Effect.never + * ]) + * await Effect.runPromise(Effect.flip(raced)) // => "First failed" + * ``` + * + * @category racing + * @since 4.0.0 + */ +const raceAllFirst = _internal_effect_js__rspack_import_1/* .raceAllFirst */.FfP; +/** + * Races two effects and returns the first successful result. + * + * **Details** + * + * If one effect succeeds, the other is interrupted and `onWinner` can observe the + * winning fiber. If both fail, the race fails. + * + * **Example** (Racing two effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.succeed("slow-success") + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.race(fastFail, slowSuccess) + * yield* Effect.sync(() => { output.push(`winner: ${result}`) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["winner: slow-success"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const race = _internal_effect_js__rspack_import_1/* .race */.O4F; +/** + * Races two effects and returns the result of the first one to complete, whether + * it succeeds or fails. + * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * + * The losing effect is interrupted, and `onWinner` can observe the winning fiber. + * + * **Example** (Observing the winning fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.never + * + * const program = Effect.gen(function*() { + * const message = yield* Effect.match(Effect.raceFirst(fastFail, slowSuccess), { + * onFailure: (error) => `failed: ${error}`, + * onSuccess: (value) => `succeeded: ${value}` + * }) + * yield* Effect.sync(() => { output.push(message) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["failed: fast-fail"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const raceFirst = _internal_effect_js__rspack_import_1/* .raceFirst */.KT6; +// ----------------------------------------------------------------------------- +// Filtering +// ----------------------------------------------------------------------------- +/** + * Filters elements of an iterable using a predicate, refinement, or effectful + * predicate. + * + * **Example** (Filtering success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Sync predicate + * const evens = Effect.filter([1, 2, 3, 4], (n) => n % 2 === 0) + * + * // Effectful predicate + * const checked = Effect.filter([1, 2, 3], (n) => Effect.succeed(n > 1)) + * + * void output.push(Effect.runSync(evens)) + * void output.push(Effect.runSync(checked)) + * output // => [[2, 4], [2, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = _internal_effect_js__rspack_import_1/* .filter */.pbD; +/** + * Filters and maps elements of an iterable with a `Filter`. + * + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = _internal_effect_js__rspack_import_1/* .filterMap */.x1Q; +/** + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering + * @since 4.0.0 + */ +const filterMapEffect = _internal_effect_js__rspack_import_1/* .filterMapEffect */.E8K; +/** + * Filters an effect, providing an alternative effect if the predicate fails. + * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, it executes the `orElse` effect instead. The + * `orElse` effect can produce an alternative value or perform additional + * computations. + * + * **Example** (Filtering with a fallback effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, provide alternative for odd numbers + * const filtered = Effect.filterOrElse( + * program, + * (n) => n % 2 === 0, + * (n) => Effect.succeed(`Number ${n} is odd`) + * ) + * + * Effect.runSync(filtered) // => "Number 5 is odd" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrElse = _internal_effect_js__rspack_import_1/* .filterOrElse */.Pm0; +/** + * Filters an effect with a `Filter`, providing an alternative effect on failure. + * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrElse = _internal_effect_js__rspack_import_1/* .filterMapOrElse */.VtY; +/** + * Filters an effect, failing with a custom error if the predicate fails. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, the effect fails with either a custom + * error (if `orFailWith` is provided) or a `NoSuchElementError`. + * + * **Example** (Filtering with a custom failure) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, fail for odd numbers + * const filtered = Effect.filterOrFail( + * program, + * (n) => n % 2 === 0, + * (n) => `Expected even number, got ${n}` + * ) + * + * Effect.runSync(Effect.flip(filtered)) // => "Expected even number, got 5" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrFail = _internal_effect_js__rspack_import_1/* .filterOrFail */.W$I; +/** + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrFail = _internal_effect_js__rspack_import_1/* .filterMapOrFail */.ahH; +// ----------------------------------------------------------------------------- +// Conditional Operators +// ----------------------------------------------------------------------------- +/** + * Runs an effect conditionally based on the result of an effectful boolean + * condition. + * + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. + * + * **Details** + * + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. + * + * **Example** (Conditionally running an effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const shouldLog = true + * + * const program = Effect.when( + * Effect.sync(() => { output.push("Condition is true!") }), + * Effect.succeed(shouldLog) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Condition is true!", Option.some(undefined)] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const when = _internal_effect_js__rspack_import_1/* .when */.z7s; +// ----------------------------------------------------------------------------- +// Pattern matching +// ----------------------------------------------------------------------------- +/** + * Handles both success and failure cases of an effect without performing side + * effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * + * **Details** + * + * `match` lets you define custom handlers for both success and failure + * scenarios. You provide separate functions to handle each case, allowing you + * to process the result if the effect succeeds, or handle the error if the + * effect fails. + * + * **Example** (Matching success and failure values) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * + * const program1 = Effect.match(success, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the successful effect + * Effect.runSync(program1) // => "success: 42" + * + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program2 = Effect.match(failure, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the failed effect + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .match */.YWq; +/** + * Handles both success and failure cases of an effect without performing side + * effects, with eager evaluation for resolved effects. + * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * + * **Details** + * + * `matchEager` works like `match` but provides better performance for resolved + * effects (Success or Failure). When the effect is already resolved, it applies + * the handlers immediately without fiber scheduling. For unresolved effects, + * it falls back to the regular `match` behavior. + * + * **Example** (Pattern matching eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.matchEager(Effect.succeed(42), { + * onFailure: (error) => `Failed: ${error}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * void output.push(result) + * }) + * + * Effect.runSync(program) + * output // => ["Success: 42"] + * ``` + * + * @see {@link match} for the non-eager version. + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 4.0.0 + */ +const matchEager = _internal_effect_js__rspack_import_1/* .matchEager */.G$Q; +/** + * Handles failures by matching the cause of failure. + * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * + * **Details** + * + * The `matchCause` function allows you to handle failures with access to the + * full cause of the failure within a fiber. + * + * **Example** (Matching on success or failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.matchCause(task, { + * onFailure: (cause) => `Failed: ${Cause.squash(cause)}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * + * Effect.runSync(program) // => "Failed: Something went wrong" + * ``` + * + * @see {@link matchCauseEffect} if you need to perform side effects in the + * handlers. + * @see {@link match} if you don't need to handle the cause of the failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchCause = _internal_effect_js__rspack_import_1/* .matchCause */.D$$; +/** + * Handles failures by matching the cause of failure with eager evaluation. + * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * + * **Details** + * + * `matchCauseEager` works like `matchCause` but provides better performance for resolved + * effects by immediately applying the matching function instead of deferring it + * through the effect pipeline. + * + * **Example** (Eagerly matching already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const handleResult = Effect.matchCauseEager(Effect.succeed(42), { + * onSuccess: (value) => `Success: ${value}`, + * onFailure: (cause) => `Failed: ${cause}` + * }) + * Effect.runSync(handleResult) // => "Success: 42" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEager = _internal_effect_js__rspack_import_1/* .matchCauseEager */.NZb; +/** + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** + * + * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like + * {@link matchCauseEffect}. + * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEffectEager = _internal_effect_js__rspack_import_1/* .matchCauseEffectEager */.wR5; +/** + * Handles failures with access to the cause and allows performing side effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * + * **Details** + * + * The `matchCauseEffect` function works similarly to {@link matchCause}, but it + * also allows you to perform additional side effects based on the failure + * cause. This function provides access to the complete cause of the failure, + * making it possible to differentiate between various failure types, and allows + * you to respond accordingly while performing side effects (like logging or + * other operations). + * + * **Example** (Effectfully matching on causes) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Result } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const task = Effect.fail(new TaskError({ message: "Task failed" })) + * + * const program = Effect.matchCauseEffect(task, { + * onFailure: (cause) => + * Effect.gen(function*() { + * if (Cause.hasFails(cause)) { + * const error = Cause.findError(cause) + * if (Result.isSuccess(error)) { + * yield* Effect.sync(() => { output.push(`Handling error: ${error.success.message}`) }) + * } + * return "recovered from error" + * } else { + * yield* Effect.sync(() => { output.push("Handling interruption or defect") }) + * return "recovered from interruption/defect" + * } + * }), + * onSuccess: (value) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Success: ${value}`) }) + * return `processed ${value}` + * }) + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Handling error: Task failed", "recovered from error"] + * ``` + * + * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. + * @see {@link matchEffect} if you don't need to handle the cause of the failure. + * + * @category pattern matching + * @since 2.0.0 + */ +const matchCauseEffect = _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu; +/** + * Handles both success and failure by running effectful handlers. + * + * **When to use** + * + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. + * + * **Details** + * + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. + * + * **Example** (Matching success and failure with effectful handlers) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program1 = Effect.matchEffect(success, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program1) // => "success: 42" + * + * const program2 = Effect.matchEffect(failure, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchEffect = _internal_effect_js__rspack_import_1/* .matchEffect */.tvg; +// ----------------------------------------------------------------------------- +// Condition checking +// ----------------------------------------------------------------------------- +/** + * Determines whether an effect fails. + * + * **Details** + * + * Defects are not converted; if the effect dies, the resulting effect dies too. + * + * **Example** (Checking whether an effect fails) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const failed = yield* Effect.isFailure(Effect.fail("Uh oh!")) + * yield* Effect.sync(() => { output.push(failed) }) + * }) + * + * Effect.runSync(program) + * output // => [true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .isFailure */.N6O; +/** + * Returns whether an effect completes successfully. + * + * **Details** + * + * Returns `false` for failures in the error channel, but defects still fail the + * effect. + * + * **Example** (Checking whether an effect succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ok = yield* Effect.isSuccess(Effect.succeed("done")) + * const failed = yield* Effect.isSuccess(Effect.fail("Uh oh")) + * yield* Effect.sync(() => { output.push(`ok: ${ok}`) }) + * yield* Effect.sync(() => { output.push(`failed: ${failed}`) }) + * }) + * + * Effect.runSync(program) + * output // => ["ok: true", "failed: false"] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .isSuccess */.oJd; +// ----------------------------------------------------------------------------- +// Environment +// ----------------------------------------------------------------------------- +/** + * 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 + * + * @category accessors + * @since 2.0.0 + */ +const context = _internal_effect_js__rspack_import_1/* .context */._OA; +/** + * Transforms the current context using the provided function. + * + * **When to use** + * + * Use to derive an effect from the complete `Context`. + * + * **Details** + * + * This function allows you to access the complete context and perform + * computations based on all available services. This is useful when you need + * to conditionally execute logic based on what services are available. + * + * **Example** (Deriving values from the context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Cache = Context.Service<{ + * get: (key: string) => string | null + * }>("Cache") + * + * const program = Effect.contextWith((services: Context.Context>) => { + * const cacheOption = Context.getOption(services, Cache) + * const hasCache = Option.isSome(cacheOption) + * + * if (hasCache) { + * return Effect.gen(function*() { + * const cache = yield* Effect.service(Cache) + * yield* Effect.sync(() => { output.push("Using cached data") }) + * return cache.get("user:123") || "default" + * }) + * } else { + * return Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("No cache available, using fallback") }) + * return "fallback data" + * }) + * } + * }) + * + * const withCache = Effect.provideService(program, Cache, { + * get: () => "cached_value" + * }) + * void output.push(Effect.runSync(withCache)) + * output // => ["Using cached data", "cached_value"] + * ``` + * + * @see {@link context} for reading the complete context as a value + * @see {@link service} for reading one service from the context + * + * @category accessors + * @since 2.0.0 + */ +const contextWith = _internal_effect_js__rspack_import_1/* .contextWith */.sxi; +/** + * Provides dependencies to an effect using layers or a context. Use `options.local` + * to build the layer every time; by default, layers are shared between provide + * calls. + * + * **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" + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provide = _internal_layer_js__rspack_import_4/* .provide */.G; +/** + * Provides a context to an effect, fulfilling its service requirements. + * + * **Details** + * + * This function provides multiple services at once by supplying a context + * that contains all the required services. It removes the provided services + * from the effect's requirements, making them available to the effect. + * + * **Example** (Providing a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define service keys + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Database = Context.Service<{ + * query: (sql: string) => string + * }>("Database") + * + * // Create a context with multiple services + * const context = Context.make(Logger, { log: (message) => { output.push(message) } }) + * .pipe(Context.add(Database, { query: () => "result" })) + * + * // An effect that requires both services + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * const db = yield* Effect.service(Database) + * logger.log("Querying database") + * return db.query("SELECT * FROM users") + * }) + * + * const provided = Effect.provideContext(program, context) + * void output.push(Effect.runSync(provided)) + * output // => ["Querying database", "result"] + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const provideContext = _internal_effect_js__rspack_import_1/* .provideContext */.PpN; +/** + * Runs an effect with the provided context as its complete environment. + * + * **When to use** + * + * Use when you already have a `Context` containing every service required by + * the effect and want the wrapped effect to run with exactly that context. + * + * **Gotchas** + * + * `setContext` replaces the current context for the wrapped effect. Services + * from an outer context are not inherited unless they are also present in the + * context passed to `setContext`. + * + * **Example** (Running with a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const program = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * return `${config.greeting}, World!` + * }) + * + * const context = Context.make(Config, { greeting: "Hello" }) + * + * const runnable = Effect.setContext(program, context) + * + * Effect.runSync(runnable) // => "Hello, World!" + * ``` + * + * @see {@link provideContext} for partially satisfying an effect's context requirements. + * @see {@link updateContext} for deriving the required context from the current one. + * + * @category providing services + * @since 4.0.0 + */ +const setContext = _internal_effect_js__rspack_import_1/* .setContext */.oao; +/** + * Accesses a service from the context. + * + * **Example** (Accessing a required service) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Database { + * readonly query: (sql: string) => Effect.Effect + * } + * + * const Database = Context.Service("Database") + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * const runnable = Effect.provideService(program, Database, { + * query: (sql) => Effect.succeed(`Result for: ${sql}`) + * }) + * Effect.runSync(runnable) // => "Result for: SELECT * FROM users" + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const service = _internal_effect_js__rspack_import_1/* .service */.euC; +/** + * Optionally accesses a service from the environment. + * + * **When to use** + * + * Use to read an optional dependency from the current context without making + * that dependency part of the effect's required environment. + * + * **Details** + * + * This function attempts to access a service from the environment. If the + * service is available, it returns `Some(service)`. If the service is not + * available, it returns `None`. Unlike `service`, this function does not + * require the service to be present in the environment. + * + * **Example** (Accessing an optional service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * // Define a service key + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * // Use serviceOption to optionally access the logger + * const program = Effect.gen(function*() { + * const maybeLogger = yield* Effect.serviceOption(Logger) + * + * if (Option.isSome(maybeLogger)) { + * maybeLogger.value.log("Service is available") + * } else { + * void output.push("Service not available") + * } + * }) + * + * Effect.runSync(program) + * output // => ["Service not available"] + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const serviceOption = _internal_effect_js__rspack_import_1/* .serviceOption */.Nav; +/** + * Provides part of the required context while leaving the rest unchanged. + * + * **Details** + * + * This function allows you to transform the context required by an effect, + * providing part of the context and leaving the rest to be fulfilled later. + * + * **Example** (Updating the context before running) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * // Define services + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Config = Context.Service<{ + * name: string + * }>("Config") + * + * const program = Effect.service(Config).pipe( + * Effect.map((config) => `Hello ${config.name}!`) + * ) + * + * // Transform services by providing Config while keeping Logger requirement + * const configured = program.pipe( + * Effect.updateContext((context: Context.Context>) => + * Context.add(context, Config, { name: "World" }) + * ) + * ) + * + * // The effect now requires only Logger service + * const result = Effect.provideService(configured, Logger, { + * log: () => {} + * }) + * Effect.runSync(result) // => "Hello World!" + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = _internal_effect_js__rspack_import_1/* .updateContext */.r_d; +/** + * 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] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const updateService = _internal_effect_js__rspack_import_1/* .updateService */.bUZ; +/** + * 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 + * + * @category providing services + * @since 4.0.0 + */ +const updateServiceScoped = _internal_effect_js__rspack_import_1/* .updateServiceScoped */.L_I; +/** + * Provides one concrete service implementation to an effect. + * + * **When to use** + * + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a service for configuration + * const Config = Context.Service<{ + * apiUrl: string + * timeout: number + * }>("Config") + * + * const fetchData = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * yield* Effect.sync(() => { output.push(`Fetching from: ${config.apiUrl}`) }) + * yield* Effect.sync(() => { output.push(`Timeout: ${config.timeout}ms`) }) + * return "data" + * }) + * + * // Provide the service implementation + * const program = Effect.provideService(fetchData, Config, { + * apiUrl: "https://api.example.com", + * timeout: 5000 + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Fetching from: https://api.example.com", "Timeout: 5000ms", "data"] + * ``` + * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category providing services + * @since 2.0.0 + */ +const provideService = _internal_effect_js__rspack_import_1/* .provideService */.PfK; +/** + * Provides one service to an effect using an effectful acquisition. + * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a database connection service + * interface DatabaseConnection { + * readonly query: (sql: string) => Effect.Effect + * } + * const Database = Context.Service("Database") + * + * // Effect that creates a database connection + * const createConnection = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Establishing database connection...") }) + * yield* Effect.sync(() => { output.push("Database connected!") }) + * return { + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * // Provide the service through an effect + * const withDatabase = Effect.provideServiceEffect( + * program, + * Database, + * createConnection + * ) + * + * void output.push(await Effect.runPromise(withDatabase)) + * output // => ["Establishing database connection...", "Database connected!", "Result for: SELECT * FROM users"] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideServiceEffect = _internal_effect_js__rspack_import_1/* .provideServiceEffect */.c7E; +// ----------------------------------------------------------------------------- +// Resource management & finalization +// ----------------------------------------------------------------------------- +/** + * Returns the current scope for resource management. + * + * **Example** (Accessing the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const currentScope = yield* Effect.scope + * yield* Effect.sync(() => { output.push("Got scope for resource management") }) + * + * // Use the scope to manually manage resources if needed + * const resource = yield* Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * + * return resource + * }) + * + * void output.push(Effect.runSync(Effect.scoped(program))) + * output // => ["Got scope for resource management", "Acquiring resource", "Releasing resource", "resource"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scope = _internal_effect_js__rspack_import_1/* .scope */.z8E; +/** + * 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"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scoped = _internal_effect_js__rspack_import_1/* .scoped */.P1j; +/** + * Creates a scoped effect by providing access to the scope. + * + * **When to use** + * + * Use when resource acquisition needs direct access to the scope being created, + * for example to register finalizers manually. + * + * **Example** (Working with an explicit scope) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * const output: Array = [] + * + * const program = Effect.scopedWith((scope) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Inside scoped context") }) + * + * // Manually add a finalizer to the scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => { output.push("Manual finalizer") })) + * + * // Create a scoped resource + * const resource = yield* Effect.scoped( + * Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * ) + * + * return resource + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Inside scoped context", "Acquiring resource", "Releasing resource", "Manual finalizer", "resource"] + * ``` + * + * @category resource management + * @since 3.11.0 + */ +const scopedWith = _internal_effect_js__rspack_import_1/* .scopedWith */.Pxi; +/** + * 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 + * + * @category resource management + * @since 2.0.0 + */ +const acquireRelease = _internal_effect_js__rspack_import_1/* .acquireRelease */.Q56; +/** + * Acquires a scoped resource that implements JavaScript disposal protocols. + * + * **When to use** + * + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. + * + * **Details** + * + * The resource is automatically disposed when the surrounding + * {@link Scope} is closed, using {@link Symbol.dispose} for + * synchronous disposables or {@link Symbol.asyncDispose} for asynchronous + * disposables. + * + * This is similar to {@link acquireRelease}, but uses the standard + * JavaScript disposal protocol instead of requiring an explicit release + * function. It works with JavaScript `Disposable` and `AsyncDisposable` + * resources. + * + * **Example** (Acquiring a disposable resource) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * class Resource implements Disposable { + * [Symbol.dispose]() { + * void output.push("disposed") + * } + * } + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.acquireDisposable(Effect.succeed(new Resource())) + * void output.push("acquired") + * }) + * ) + * + * Effect.runSync(program) + * output // => ["acquired", "disposed"] + * ``` + * + * @see {@link acquireRelease} for resources that need an explicit finalizer + * + * @category resource management + * @since 4.0.0 + */ +const acquireDisposable = _internal_effect_js__rspack_import_1/* .acquireDisposable */.N24; +/** + * Runs resource acquisition, usage, and release as one bracketed effect. + * + * **When to use** + * + * Use to bracket acquire, use, and release logic in one effect. + * + * **Details** + * + * `acquireUseRelease` does the following: + * + * 1. Ensures that the `Effect` value that acquires the resource will not be + * interrupted. Note that acquisition may still fail due to internal + * reasons (such as an uncaught exception). + * 2. Ensures that the `release` `Effect` value will not be interrupted, + * and will be executed as long as the acquisition `Effect` value + * successfully acquires the resource. + * + * During the time period between the acquisition and release of the resource, + * the `use` `Effect` value will be executed. + * + * If the `release` `Effect` value fails, then the entire `Effect` value will + * fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior + * is not desired, errors produced by the `release` `Effect` value can be caught + * and ignored. + * + * **Example** (Acquiring resources with cleanup) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * readonly connection: string + * readonly query: (sql: string) => Effect.Effect + * } + * + * const program = Effect.acquireUseRelease( + * // Acquire - connect to database + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Connecting to database...") }) + * return { + * connection: "db://localhost:5432", + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }), + * // Use - perform database operations + * (db) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Connected to ${db.connection}`) }) + * const result = yield* db.query("SELECT * FROM users") + * yield* Effect.sync(() => { output.push(`Query result: ${result}`) }) + * return result + * }), + * // Release - close database connection + * (db, exit) => + * Effect.gen(function*() { + * if (Exit.isSuccess(exit)) { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (success)`) }) + * } else { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (failure)`) }) + * } + * }) + * ) + * + * await Effect.runPromise(program) + * output // => ["Connecting to database...", "Connected to db://localhost:5432", "Query result: Result for: SELECT * FROM users", "Closing connection to db://localhost:5432 (success)"] + * ``` + * + * @see {@link acquireRelease} for scoped resources whose use happens later + * + * @category resource management + * @since 2.0.0 + */ +const acquireUseRelease = _internal_effect_js__rspack_import_1/* .acquireUseRelease */.jGc; +/** + * Adds a finalizer to the current scope. + * + * **When to use** + * + * Use to register low-level cleanup in the current scope. + * + * **Details** + * + * The finalizer runs when the surrounding scope is closed and receives the + * `Exit` value used to close the scope. + * + * **Example** (Registering scope finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * // Add a finalizer that runs when the scope closes + * yield* Effect.addFinalizer((exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? "Cleanup: Operation completed successfully" + * : "Cleanup: Operation failed, cleaning up resources" + * ) }) + * ) + * + * yield* Effect.sync(() => { output.push("Performing main operation...") }) + * + * // This could succeed or fail + * return "operation result" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Performing main operation...", "Cleanup: Operation completed successfully", "operation result"] + * ``` + * + * @see {@link acquireRelease} for resource acquisition with a release finalizer + * @see {@link ensuring} for attaching a finalizer to one effect + * + * @category resource management + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_1/* .addFinalizer */.U9h; +/** + * Returns an effect that, if this effect _starts_ execution, then the + * specified `finalizer` is guaranteed to be executed, whether this effect + * succeeds, fails, or is interrupted. + * + * **Details** + * + * For use cases that need access to the effect's result, see `onExit`. + * + * Finalizers offer very powerful guarantees, but they are low-level, and + * should generally not be used for releasing resources. For higher-level + * logic built on `ensuring`, see the `acquireRelease` family of methods. + * + * **Example** (Always running cleanup) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task started") }) + * yield* Effect.sync(() => { output.push("Task completed") }) + * return 42 + * }) + * + * // Ensure cleanup always runs, regardless of success or failure + * const program = Effect.ensuring( + * task, + * Effect.sync(() => { output.push("Cleanup: This always runs!") }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task started", "Task completed", "Cleanup: This always runs!", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = _internal_effect_js__rspack_import_1/* .ensuring */.yeE; +/** + * Runs the specified effect if this effect fails, providing the error to the + * effect if it exists. The provided effect will not be interrupted. + * + * **Example** (Running cleanup on failure) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const error = new TaskError({ message: "Something went wrong" }) + * const task = Effect.fail(error) + * + * const program = Effect.onError( + * task, + * (cause) => Effect.sync(() => { output.push(`Cleanup on error: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cleanup on error: TaskError: Something went wrong", Exit.fail(error)] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onError = _internal_effect_js__rspack_import_1/* .onError */.S5A; +/** + * Runs the finalizer only when this effect fails and the `Cause` matches the + * provided predicate. + * + * **Example** (Running cleanup for selected failures) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("boom") + * + * const program = Effect.onErrorIf( + * task, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Cause: ${Cause.squash(cause)}`) }) + * }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cause: boom", Exit.fail("boom")] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onErrorIf = _internal_effect_js__rspack_import_1/* .onErrorIf */.BeE; +/** + * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management + * @since 4.0.0 + */ +const onErrorFilter = _internal_effect_js__rspack_import_1/* .onErrorFilter */.iKM; +/** + * Runs an optional finalizer with the effect's `Exit` value when the effect + * completes. + * + * **When to use** + * + * Use when you are building a low-level `Effect` operator that must inspect the + * source effect's `Exit`, may skip finalization by returning `undefined`, or + * must choose whether finalization is forced into an uninterruptible region. + * + * **Details** + * + * This low-level operator preserves the source effect's result unless the + * finalizer fails. If both the source effect and the finalizer fail, the two + * causes are merged. Prefer `onExit` for normal cleanup logic. + * + * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect + * + * @category resource management + * @since 4.0.0 + */ +const onExitPrimitive = _internal_effect_js__rspack_import_1/* .onExitPrimitive */.r7h; +/** + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * If both the effect and the cleanup function fail, the two causes are merged. + * + * **Example** (Observing every exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.succeed(42) + * + * const program = Effect.onExit(task, (exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? `Task succeeded with: ${exit.value}` + * : `Task failed: ${Exit.isFailure(exit) ? exit.cause : "interrupted"}` + * ) })) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onExit = _internal_effect_js__rspack_import_1/* .onExit */.cfM; +/** + * Runs the cleanup effect only when the `Exit` satisfies the provided + * predicate. + * + * **Example** (Observing selected exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.onExitIf( + * Effect.succeed(42), + * Exit.isSuccess, + * (exit) => + * Exit.isSuccess(exit) + * ? Effect.sync(() => { output.push(`Succeeded with: ${exit.value}`) }) + * : Effect.void + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExitIf = _internal_effect_js__rspack_import_1/* .onExitIf */.fGe; +/** + * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management + * @since 4.0.0 + */ +const onExitFilter = _internal_effect_js__rspack_import_1/* .onExitFilter */.uRq; +// ----------------------------------------------------------------------------- +// Caching +// ----------------------------------------------------------------------------- +/** + * Returns an effect that lazily computes a result and caches it for subsequent + * evaluations. + * + * **When to use** + * + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. + * + * **Details** + * + * This function wraps an effect and ensures that its result is computed only + * once. Once the result is computed, it is cached, meaning that subsequent + * evaluations of the same effect will return the cached result without + * re-executing the logic. + * + * **Example** (Memoizing an effect until invalidated) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * void output.push("non-cached version:") + * yield* expensiveTask.pipe(Effect.andThen(record)) + * yield* expensiveTask.pipe(Effect.andThen(record)) + * void output.push("cached version:") + * const cached = yield* Effect.cached(expensiveTask) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * await Effect.runPromise(program) + * output // => ["non-cached version:", "expensive task...", "result 1", "expensive task...", "result 2", "cached version:", "expensive task...", "result 3", "result 3"] + * ``` + * + * @see {@link cachedWithTTL} for a similar function that includes a + * time-to-live duration for the cached value. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cached = _internal_effect_js__rspack_import_1/* .cached */.PO3; +/** + * Returns an effect that caches its result for a specified `Duration`, + * known as "timeToLive" (TTL). + * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * + * **Details** + * + * This function is used to cache the result of an effect for a specified amount + * of time. This means that the first time the effect is evaluated, its result + * is computed and stored. + * + * If the effect is evaluated again within the specified `timeToLive`, the + * cached result will be used, avoiding recomputation. + * + * After the specified duration has passed, the cache expires, and the effect + * will be recomputed upon the next evaluation. + * + * **Example** (Memoizing an effect with TTL) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const cached = yield* Effect.cachedWithTTL(expensiveTask, "1 hour") + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "result 1"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cachedWithTTL = _internal_effect_js__rspack_import_1/* .cachedWithTTL */.Rgn; +/** + * Creates a cached effect result for a specified duration and allows manual + * invalidation before expiration. + * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * + * **Details** + * + * This function behaves similarly to {@link cachedWithTTL} by caching the + * result of an effect for a specified period of time. However, it introduces an + * additional feature: it provides an effect that allows you to manually + * invalidate the cached result before it naturally expires. + * + * This gives you more control over the cache, allowing you to refresh the + * result when needed, even if the original cache has not yet expired. + * + * Once the cache is invalidated, the next time the effect is evaluated, the + * result will be recomputed, and the cache will be refreshed. + * + * **Example** (Memoizing with TTL and invalidation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL( + * expensiveTask, + * "1 hour" + * ) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* invalidate + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "expensive task...", "result 2"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching + * @since 2.0.0 + */ +const cachedInvalidateWithTTL = _internal_effect_js__rspack_import_1/* .cachedInvalidateWithTTL */.CJw; +// ----------------------------------------------------------------------------- +// Interruption +// ----------------------------------------------------------------------------- +/** + * Returns an effect that is immediately interrupted. + * + * **Example** (Creating an interrupted effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * return yield* Effect.interrupt + * yield* Effect.succeed("This won't execute and is unreachable") + * }) + * + * Effect.runSyncExit(program)._tag // => "Failure" + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .interrupt */.GaK; +/** + * Returns a new effect that allows the effect to be interruptible. + * + * **Example** (Allowing interruption) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.interruptible(Effect.never).pipe( + * Effect.timeoutOption(0) + * ) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptible = _internal_effect_js__rspack_import_1/* .interruptible */.Inz; +/** + * Runs the specified finalizer effect if this effect is interrupted. + * + * **Example** (Running cleanup on interruption) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * const task = Effect.forever(Effect.succeed("working...")) + * + * const program = Effect.onInterrupt( + * task, + * () => Effect.sync(() => { output.push("Task was interrupted, cleaning up...") }) + * ) + * + * const fiber = Effect.runFork(program) + * await Effect.runPromise(Fiber.interrupt(fiber)) + * output // => ["Task was interrupted, cleaning up..."] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const onInterrupt = _internal_effect_js__rspack_import_1/* .onInterrupt */.nAr; +/** + * Returns a new effect that disables interruption for the given effect. + * + * **Example** (Preventing interruption) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const criticalTask = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Starting critical section...") }) + * yield* Effect.sync(() => { output.push("Critical section completed") }) + * }) + * + * const program = Effect.uninterruptible(criticalTask) + * + * Effect.runSync(program) + * output // => ["Starting critical section...", "Critical section completed"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptible = _internal_effect_js__rspack_import_1/* .uninterruptible */.rfi; +/** + * Disables interruption and provides a restore function to restore the + * interruptible state within the effect. + * + * **Example** (Restoring interruption in protected regions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.uninterruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * // Restore interruptibility for this part + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to uninterruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Uninterruptible phase...", "Interruptible phase...", "Back to uninterruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptibleMask = _internal_effect_js__rspack_import_1/* .uninterruptibleMask */.FcF; +/** + * Runs an effect in an interruptible region while providing `restore` for + * locally restoring the previous interruptibility. + * + * **Example** (Controlling interruptibility locally) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.interruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * // Make this part uninterruptible + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to interruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Interruptible phase...", "Uninterruptible phase...", "Back to interruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptibleMask = _internal_effect_js__rspack_import_1/* .interruptibleMask */.eMl; +/** + * Creates an AbortSignal that is managed by the provided scope. + * + * **When to use** + * + * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation + * through a signal. + * + * **Details** + * + * Each acquisition creates a fresh `AbortController`. Closing the owning scope + * runs a finalizer that aborts the controller and the effect succeeds with the + * controller's signal. + * + * **Gotchas** + * + * The signal is aborted when its owning scope closes, so avoid keeping it for + * work that outlives that scope. + * + * @see {@link scoped} for binding resource lifetime to a scope + * + * @category interruption + * @since 4.0.0 + */ +const abortSignal = _internal_effect_js__rspack_import_1/* .abortSignal */.dsN; +/** + * Repeats this effect forever (until the first error). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.forever(Effect.never).pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const forever = _internal_effect_js__rspack_import_1/* .forever */.i4r; +/** + * Repeats an effect based on a specified schedule or until the first failure. + * + * **When to use** + * + * Use to rerun an effect after successful executions. + * + * **Details** + * + * This function executes an effect repeatedly according to the given schedule. + * Each repetition occurs after the initial execution of the effect, meaning + * that the schedule determines the number of additional repetitions. For + * example, using `Schedule.once` will result in the effect being executed twice + * (once initially and once as part of the repetition). + * + * If the effect succeeds, it is repeated according to the schedule. If it + * fails, the repetition stops immediately, and the failure is returned. + * + * The schedule can also specify delays between repetitions, making it useful + * for tasks like retrying operations with backoff, periodic execution, or + * performing a series of dependent actions. + * + * You can combine schedules for more advanced repetition logic, such as adding + * delays, limiting recursions, or dynamically adjusting based on the outcome of + * each execution. + * + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * + * ```ts import.meta.vitest + * // Success Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const action = Effect.sync(() => { output.push("success") }) + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push(Effect.runSync(program)) + * output // => ["success", "success", "success", 2] + * ``` + * + * **Example** (Stopping repetition on failure) + * + * ```ts import.meta.vitest + * // Failure Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * let count = 0 + * + * // Define a callback effect that simulates an action with possible failures + * const action = Effect.callback((resume) => { + * if (count > 1) { + * void output.push("failure") + * resume(Effect.fail("Uh oh!")) + * } else { + * count++ + * void output.push("success") + * resume(Effect.succeed("yay!")) + * } + * }) + * + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push((await Effect.runPromiseExit(program))._tag) + * output // => ["success", "success", "failure", "Failure"] + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails + * + * @category repetition + * @since 2.0.0 + */ +const repeat = _internal_schedule_js__rspack_import_2/* .repeat */.ux; +/** + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. + * + * **Details** + * + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. + * + * **Example** (Recovering after repetition stops) + * + * ```ts import.meta.vitest + * import { Effect, Option, Schedule } from "effect" + * const output: Array = [] + * + * let attempt = 0 + * const task = Effect.gen(function*() { + * attempt++ + * if (attempt <= 2) { + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} failed`) }) + * return yield* Effect.fail(`Error ${attempt}`) + * } + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} succeeded`) }) + * return "success" + * }) + * + * const program = Effect.repeatOrElse( + * task, + * Schedule.recurs(3), + * (error, attempts) => + * Effect.sync(() => { output.push( + * `Final failure: ${error}, after ${ + * Option.getOrElse(attempts, () => 0) + * } attempts` + * ) }).pipe(Effect.map(() => 0)) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Attempt 1 failed", "Final failure: Error 1, after 0 attempts", 0] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const repeatOrElse = _internal_schedule_js__rspack_import_2/* .repeatOrElse */.i3; +/** + * Returns an array of `n` identical effects. + * + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category repetition + * @since 2.0.0 + */ +const replicate = _internal_effect_js__rspack_import_1/* .replicate */.aAq; +/** + * Performs this effect `n` times and collects results with `Effect.all` semantics. + * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * + * Use `concurrency` to control parallelism and `discard: true` to ignore results. + * + * **Example** (Replicating an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const results = yield* Effect.replicateEffect(3)(Effect.succeed(1)) + * yield* Effect.sync(() => { output.push(results) }) + * }) + * + * Effect.runSync(program) + * output // => [[1, 1, 1]] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const replicateEffect = _internal_effect_js__rspack_import_1/* .replicateEffect */.Xrv; +/** + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. + * + * **Details** + * + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. + * + * **Example** (Scheduling repeated execution) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task executing...") }) + * return 1 + * }) + * + * const program = Effect.schedule(task, Schedule.recurs(2)) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task executing...", "Task executing...", 2] + * ``` + * + * @see {@link scheduleFrom} for a variant that allows the schedule's decision + * to depend on the result of this effect. + * + * @category repetition + * @since 2.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => scheduleFrom(self, undefined, schedule)))); +/** + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. + * + * **Details** + * + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. + * + * **Example** (Scheduling from an initial value) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = (input: number) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Processing: ${input}`) }) + * return input + 1 + * }) + * + * // Start with 0, repeat 3 times + * const program = Effect.scheduleFrom( + * task(0), + * 0, + * Schedule.recurs(2) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Processing: 0", "Processing: 0", 2] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const scheduleFrom = _internal_schedule_js__rspack_import_2/* .scheduleFrom */.mG; +// ----------------------------------------------------------------------------- +// Tracing +// ----------------------------------------------------------------------------- +/** + * Returns the current tracer from the context. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const currentTracer = yield* Effect.tracer + * return typeof currentTracer.span + * }) + * + * Effect.runSync(program) // => "function" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const tracer = _internal_effect_js__rspack_import_1/* .tracer */.kJM; +/** + * Provides a tracer to an effect. + * + * **Example** (Providing a tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.tracer + * return yield* Effect.withTracer(Effect.succeed("completed"), tracer) + * }) + * + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracer = _internal_effect_js__rspack_import_1/* .withTracer */._o1; +/** + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not be registered with the tracer + * Effect.withTracerEnabled(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerEnabled = _internal_effect_js__rspack_import_1/* .withTracerEnabled */.nDN; +/** + * Enables or disables tracer timing for the given Effect. + * + * **Example** (Enabling or disabling tracing timing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not have timing information + * Effect.withTracerTiming(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerTiming = _internal_effect_js__rspack_import_1/* .withTracerTiming */.MaT; +/** + * Adds an annotation to each span in this effect. + * + * **Example** (Annotating all spans) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed("result") + * + * // Add single annotation + * const annotated1 = Effect.annotateSpans(program, "user", "john") + * + * // Add multiple annotations + * const annotated2 = Effect.annotateSpans(program, { + * operation: "data-processing", + * version: "1.0.0", + * environment: "production" + * }) + * + * Effect.runSync(Effect.all([annotated1, annotated2])) // => ['result', 'result'] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateSpans = _internal_effect_js__rspack_import_1/* .annotateSpans */.Muk; +/** + * Adds an annotation to the current span if available. + * + * **Example** (Annotating the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * yield* Effect.annotateCurrentSpan("userId", "123") + * yield* Effect.annotateCurrentSpan({ + * operation: "user-lookup" + * }) + * return "success" + * }) + * + * const traced = Effect.withSpan(program, "user-operation") + * Effect.runSync(traced) // => "success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateCurrentSpan = _internal_effect_js__rspack_import_1/* .annotateCurrentSpan */.ww9; +/** + * Returns the currently active local tracing span. + * + * **Details** + * + * The effect fails with `NoSuchElementError` when there is no active local + * `Span`. + * + * **Example** (Reading the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.currentSpan + * return span.name + * }) + * + * const traced = Effect.withSpan(program, "my-span") + * Effect.runSync(traced) // => "my-span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentSpan = _internal_effect_js__rspack_import_1/* .currentSpan */._32; +/** + * Returns the current parent span from the effect context. + * + * **Details** + * + * The effect succeeds with either a local span or external span when one is + * present, and fails with `NoSuchElementError` when no parent span is + * available. + * + * **Example** (Reading the parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const childOperation = Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * return parentSpan._tag + * }) + * + * const program = Effect.withSpan(childOperation, "child-span") + * + * const traced = Effect.withSpan(program, "parent-span") + * Effect.runSync(traced) // => "Span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentParentSpan = _internal_effect_js__rspack_import_1/* .currentParentSpan */.Wj8; +/** + * Returns the tracing span annotations currently carried in the effect context. + * + * **Details** + * + * These annotations are applied to spans created inside the context, such as + * spans created by `withSpan`, `useSpan`, or `makeSpan`. + * + * **Example** (Providing span annotations) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const annotations = yield* Effect.spanAnnotations + * return annotations + * }).pipe(Effect.annotateSpans({ userId: "123", operation: "data-processing" })) + * + * Effect.runSync(program) // => { userId: '123', operation: 'data-processing' } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanAnnotations = _internal_effect_js__rspack_import_1/* .spanAnnotations */.Fu6; +/** + * Returns the tracing span links currently carried in the effect context. + * + * **Details** + * + * These links are attached to spans created inside the context. Span links + * connect related spans without making one span the parent of another. + * + * **Example** (Providing span links) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * // Get the current span links + * const links = yield* Effect.spanLinks + * return links + * }) + * + * Effect.runSync(program).length // => 0 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanLinks = _internal_effect_js__rspack_import_1/* .spanLinks */.WbR; +/** + * Adds a link with the provided span to all spans in this effect. + * + * **Details** + * + * This is useful for connecting spans that are related but not in a direct + * parent-child relationship. For example, you might want to link spans from + * parallel operations or connect spans across different traces. + * + * **Example** (Linking one span to another span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.withSpan(Effect.gen(function*() { + * const parentSpan = yield* Effect.currentSpan + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans(parentSpan, { relationship: "follows" }) + * ) + * }), "parent-operation") + * + * Effect.runSync(program).length // => 1 + * ``` + * + * **Example** (Linking multiple spans at once) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span1 = yield* Effect.makeSpan("span-1") + * const span2 = yield* Effect.makeSpan("span-2") + * + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans([span1, span2], { + * type: "dependency", + * source: "multiple-operations" + * }) + * ) + * }) + * + * Effect.runSync(program).length // => 2 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const linkSpans = _internal_effect_js__rspack_import_1/* .linkSpans */.A_r; +/** + * Creates a new tracing span and returns it without managing its lifetime. + * + * **Details** + * + * The span is not added to the current span stack and is not ended + * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span + * should be installed as context or closed automatically. + * + * **Example** (Creating a span manually) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("my-operation") + * return span.name + * }) + * + * Effect.runSync(program) // => "my-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpan = _internal_effect_js__rspack_import_1/* .makeSpan */.Z98; +/** + * Create a new span for tracing, and automatically close it when the Scope + * finalizes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Creating a scoped standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const span = yield* Effect.makeSpanScoped("scoped-operation") + * return span.name + * // Span automatically closes when scope ends + * }) + * ) + * + * Effect.runSync(program) // => "scoped-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpanScoped = _internal_effect_js__rspack_import_1/* .makeSpanScoped */.Rd$; +/** + * Create a new span for tracing, and automatically close it when the effect + * completes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Running an effect with a standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.useSpan( + * "user-operation", + * (span) => Effect.succeed(`${span.name}: success`) + * ) + * Effect.runSync(program) // => "user-operation: success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const useSpan = _internal_effect_js__rspack_import_1/* .useSpan */.gvr; +/** + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.succeed("result") + * + * const traced = Effect.withSpan(task, "my-task", { + * attributes: { version: "1.0" } + * }) + * Effect.runSync(traced) // => "result" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = _internal_effect_js__rspack_import_1/* .withSpan */.fRP; +/** + * Wraps the effect with a scoped child span for tracing. + * + * **Details** + * + * The span is ended when the Scope is finalized. + * + * **Example** (Creating a scoped child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const task = Effect.succeed("working") + * yield* Effect.withSpanScoped(task, "scoped-task") + * return "completed" + * }) + * ) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpanScoped = _internal_effect_js__rspack_import_1/* .withSpanScoped */.zr8; +/** + * Adds the provided span to the current span stack. + * + * **Example** (Setting a parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("parent-span") + * const childTask = Effect.succeed("child operation") + * yield* Effect.withParentSpan(childTask, span) + * return "completed" + * }) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = _internal_effect_js__rspack_import_1/* .withParentSpan */.hq; +// ----------------------------------------------------------------------------- +// Batching +// ----------------------------------------------------------------------------- +/** + * Executes a request using the provided resolver. + * + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Request, RequestResolver } from "effect" + * const output: Array = [] + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: number + * } + * const GetUser = Request.tagged("GetUser") + * + * const resolver = RequestResolver.make( + * Effect.fnUntraced(function*(entries) { + * for (const entry of entries) { + * yield* Request.complete(entry, Exit.succeed(`user-${entry.request.id}`)) + * } + * }) + * ) + * + * const program = Effect.gen(function*() { + * const name = yield* Effect.request(GetUser({ id: 1 }), resolver) + * yield* Effect.sync(() => { output.push(name) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["user-1"] + * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category running + * @since 2.0.0 + */ +const request = _internal_request_js__rspack_import_5/* .request */.E; +/** + * Registers a request with a resolver and delivers the exit value via `onExit`. + * + * **When to use** + * + * Use when you already have a `Context` and need to enqueue a request outside + * an `Effect` while receiving completion through `onExit`. + * + * **Details** + * + * It returns a canceler that removes the pending request entry. + * + * @see {@link request} for the `Effect`-returning API used for normal request execution + * + * @category unsafe + * @since 4.0.0 + */ +const requestUnsafe = _internal_request_js__rspack_import_5/* .requestUnsafe */.m; +// ----------------------------------------------------------------------------- +// Supervision & Fiber's +// ----------------------------------------------------------------------------- +/** + * 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 other higher-level methods, such as `raceWith`, + * `zipPar`, and so forth. + * + * 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" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkChild = _internal_effect_js__rspack_import_1/* .forkChild */.zhn; +/** + * Forks the effect in the specified scope. The fiber will be interrupted + * when the scope is closed. + * + * **Example** (Forking into a supplied scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const scope = yield* Effect.scope + * const fiber = yield* Effect.forkIn(task, scope) + * // Fiber will be interrupted when scope closes + * return "done" + * }) + * ) + * + * await Effect.runPromise(program) // => "done" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkIn = _internal_effect_js__rspack_import_1/* .forkIn */.ar0; +/** + * Forks the fiber in a `Scope`, interrupting it when the scope is closed. + * + * **Example** (Forking into the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const backgroundTask = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* backgroundTask.pipe(Effect.forkScoped) + * + * // Fiber will be interrupted when scope closes + * return "scope completed" + * }) + * ) + * + * await Effect.runPromise(program) // => "scope completed" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkScoped = _internal_effect_js__rspack_import_1/* .forkScoped */.x6Z; +/** + * Forks the effect into a new fiber attached to the global scope. Because the + * new fiber is attached to the global scope, when the fiber executing the + * returned effect terminates, the forked fiber will continue running. + * + * **Example** (Forking a detached fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const daemonTask = Effect.succeed("daemon result") + * + * const program = Effect.gen(function*() { + * const fiber = yield* daemonTask.pipe(Effect.forkDetach) + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "daemon result" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkDetach = _internal_effect_js__rspack_import_1/* .forkDetach */.yxg; +/** + * Waits for all child fibers forked by this effect to complete before this + * effect completes. + * + * **When to use** + * + * Use to let an effect start child work concurrently while still delaying its + * own completion until that child work is done. + * + * **Gotchas** + * + * Child fibers that already exist before the wrapped effect starts are not + * awaited. + * + * @see {@link forkChild} for forking child fibers that are awaited by this operator + * @see {@link forkDetach} for forking fibers outside the child scope + * @see {@link forkIn} for forking into an explicit scope + * @see {@link forkScoped} for forking fibers tied to the current scope + * + * @category sequencing + * @since 2.0.0 + */ +const awaitAllChildren = _internal_effect_js__rspack_import_1/* .awaitAllChildren */.PCg; +/** + * Accesses the fiber currently executing the effect. + * + * **Example** (Accessing the current fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.fiber + * yield* Effect.sync(() => { output.push(typeof fiber.id) }) + * }) + * + * Effect.runSync(program) + * output // => ["number"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const fiber = _internal_effect_js__rspack_import_1/* .fiber */.pEE; +/** + * Accesses the current fiber id executing the effect. + * + * **Example** (Accessing the current fiber id) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.fiberId.pipe(Effect.map((id) => typeof id)) + * Effect.runSync(program) // => "number" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const fiberId = _internal_effect_js__rspack_import_1/* .fiberId */.ABT; +/** + * Runs an effect in the background, returning a fiber that can + * be observed or interrupted. + * + * **When to use** + * + * Use when you need to start an effect in the background and receive a fiber. + * + * **Example** (Running an effect in the background) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * // ┌─── Effect + * // ▼ + * const program = Effect.sync(() => { output.push("running...") }).pipe(Effect.as("done")) + * + * // ┌─── RuntimeFiber + * // ▼ + * const fiber = Effect.runFork(program) + * + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["running...", "done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runFork = _internal_effect_js__rspack_import_1/* .runFork */.MY7; +/** + * Runs an effect in the background with the provided services. + * + * **When to use** + * + * Use when an effect still requires services, you already have a `Context`, and + * you want a background fiber. + * + * **Example** (Running with services in the background) + * + * ```ts import.meta.vitest + * import { Context, Effect, Fiber } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => void + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => void output.push(message) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * logger.log("Hello from service!") + * return "done" + * }) + * + * const fiber = Effect.runForkWith(services)(program) + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["Hello from service!", "done"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runForkWith = _internal_effect_js__rspack_import_1/* .runForkWith */.eJC; +/** + * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor. + * + * **When to use** + * + * Use when embedding an effect into callback-style code with explicit services + * and a synchronous interruptor. + * + * **Details** + * + * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id. + * + * **Example** (Running with services and a callback) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => Effect.Effect + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => Effect.sync(() => { output.push(message) }) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * yield* logger.log("Started") + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallbackWith(services)(program, { + * onExit: (exit) => { + * void output.push(exit._tag) + * resolve() + * } + * }) + * }) + * output // => ["Started", "Success"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runCallbackWith = _internal_effect_js__rspack_import_1/* .runCallbackWith */.lSz; +/** + * Runs an effect asynchronously, registering `onExit` as a fiber observer and + * returning an interruptor. + * + * **Details** + * + * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor + * id. + * + * **Example** (Running with a callback) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("working") }) + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallback(program, { + * onExit: (exit) => { + * Effect.runSync( + * Exit.match(exit, { + * onFailure: () => Effect.sync(() => { output.push("failed") }), + * onSuccess: (value) => Effect.sync(() => { output.push(`success: ${value}`) }) + * }) + * ) + * resolve() + * } + * }) + * }) + * + * output // => ["working", "success: done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runCallback = _internal_effect_js__rspack_import_1/* .runCallback */.bPG; +/** + * 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. + * @category running + * @since 2.0.0 + */ +const runPromise = _internal_effect_js__rspack_import_1/* .runPromise */.pR5; +/** + * Executes an effect as a Promise with the provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that rejects on + * effect failure. + * + * **Example** (Running with services as a promise) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Config { + * apiUrl: string + * } + * + * const Config = Context.Service("Config") + * + * const context = Context.make(Config, { + * apiUrl: "https://api.example.com" + * }) + * + * const program = Effect.gen(function*() { + * const config = yield* Config + * return `Connecting to ${config.apiUrl}` + * }) + * + * await Effect.runPromiseWith(context)(program) // => "Connecting to https://api.example.com" + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseWith = _internal_effect_js__rspack_import_1/* .runPromiseWith */.v2Q; +/** + * Runs an effect and returns a `Promise` that resolves to an `Exit`, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use when you need to determine if an effect succeeded + * or failed, including any defects, and you want to work with a `Promise`. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * **Example** (Observing promise results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * // Execute a successful effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * // Execute a failing effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * @see {@link runPromise} for a version that rejects on failure. + * + * @category running + * @since 2.0.0 + */ +const runPromiseExit = _internal_effect_js__rspack_import_1/* .runPromiseExit */.NpQ; +/** + * Runs an effect and returns a Promise of Exit with provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that preserves + * success and failure as an `Exit`. + * + * **Example** (Running with services as an Exit promise) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * query: (sql: string) => string + * } + * + * const Database = Context.Service("Database") + * + * const services = Context.make(Database, { + * query: (sql) => `Result for: ${sql}` + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Database + * return db.query("SELECT * FROM users") + * }) + * + * const exit = await Effect.runPromiseExitWith(services)(program) + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } + * output // => ["Success: Result for: SELECT * FROM users"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseExitWith = _internal_effect_js__rspack_import_1/* .runPromiseExitWith */.jqV; +/** + * 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, is interrupted, or performs asynchronous work, + * `runSync` throws a `FiberFailure` instead of returning a value. 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. + * @category running + * @since 2.0.0 + */ +const runSync = _internal_effect_js__rspack_import_1/* .runSync */.HZF; +/** + * Executes an effect synchronously with provided services. + * + * **When to use** + * + * Use when you already have a `Context`, the effect is known to complete + * synchronously, and failures should throw. + * + * **Example** (Running synchronously with services) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface MathService { + * add: (a: number, b: number) => number + * } + * + * const MathService = Context.Service("MathService") + * + * const context = Context.make(MathService, { + * add: (a, b) => a + b + * }) + * + * const program = Effect.gen(function*() { + * const math = yield* MathService + * return math.add(2, 3) + * }) + * + * const result = Effect.runSyncWith(context)(program) + * result // => 5 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncWith = _internal_effect_js__rspack_import_1/* .runSyncWith */.lE; +/** + * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use to find out whether an effect succeeded or failed, + * including any defects, without dealing with asynchronous operations. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * If the effect contains asynchronous operations, `runSyncExit` will + * return an `Failure` with a `Die` cause, indicating that the effect cannot be + * resolved synchronously. + * + * **Example** (Observing synchronous results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * **Example** (Capturing async work as a Die cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))) + * const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some( + * (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect) + * ) + * + * isAsyncDie // => true + * ``` + * + * @see {@link runSync} for a version that throws on failure. + * + * @category running + * @since 2.0.0 + */ +const runSyncExit = _internal_effect_js__rspack_import_1/* .runSyncExit */.lKS; +/** + * Runs an effect synchronously with provided services, returning an Exit result safely. + * + * **When to use** + * + * Use when you already have a `Context` and need a synchronous `Exit` instead of + * throwing on failure. + * + * **Example** (Running synchronously with services as Exit) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * // Define a logger service + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * logger.log("Computing result...") + * return 42 + * }) + * + * // Prepare context + * const context = Context.make(Logger, { + * log: (msg) => void output.push(`[LOG] ${msg}`) + * }) + * + * const exit = Effect.runSyncExitWith(context)(program) + * + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } else { + * void output.push(`Failure: ${exit.cause}`) + * } + * output // => ["[LOG] Computing result...", "Success: 42"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncExitWith = _internal_effect_js__rspack_import_1/* .runSyncExitWith */.rfH; +/** + * 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. 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" + * ``` + * + * @category constructors + * @since 3.12.0 + */ +const fnUntraced = _internal_effect_js__rspack_import_1/* .fnUntraced */.D9k; +/** + * Creates a reusable traced function from an Effect body. + * + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, and you want + * tracing spans or stack-frame capture. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the + * generator body instead of allocating a fresh generator closure around the + * arguments on every call. Call `Effect.fn(body, ...)` for a generic + * stack-frame boundary without creating a span. Call + * `Effect.fn("operationName", options?)(body, ...)` when that boundary should + * have a readable operation name and the returned `Effect` should create a + * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata + * such as attributes, links, parent or root selection, kind, sampling, and log + * level. Additional arguments after the generator body act like `pipe` + * transforms: each transform receives the previous result and the original + * function arguments. When those transforms return an `Effect`, the returned + * effect includes stack-frame metadata and, for the named form, a tracing span. + * Generator bodies may declare a `this` parameter; pass `{ self }` before the + * body to bind `this` when the function is created. + * + * **Example** (Defining traced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(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.fn("formatLength")( + * 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** (Binding this) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class Counter { + * count = 0 + * + * increment = Effect.fn("Counter.increment")( + * { self: this }, + * function*(this: Counter, by: number) { + * this.count += by + * return yield* Effect.succeed(this.count) + * } + * ) + * } + * + * const counter = new Counter() + * + * // ┌─── Effect.Effect + * // ▼ + * const program = counter.increment(1) + * Effect.runSync(program) // => 1 + * ``` + * + * **Example** (Annotating a traced non-parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => 5 + * ``` + * + * **Example** (Annotating a traced parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("succeed")(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => "hello" + * ``` + * + * @category constructors + * @since 3.11.0 + */ +const fn = _internal_effect_js__rspack_import_1.fn; +// ======================================================================== +// Clock +// ======================================================================== +/** + * Retrieves the `Clock` service from the context and provides it to the + * specified effectful function. + * + * **Example** (Accessing the Clock service) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.clockWith((clock) => + * clock.currentTimeMillis.pipe( + * Effect.map(() => "Clock is available") + * ) + * ) + * + * Effect.runSync(program) // => "Clock is available" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const clockWith = _internal_effect_js__rspack_import_1/* .clockWith */.RKA; +// ======================================================================== +// Logging +// ======================================================================== +/** + * Creates a logger function that logs at the specified level. + * + * **Details** + * + * If no level is provided, the logger uses the fiber's current log level and + * extracts any `Cause` values from the message list. + * + * **Example** (Logging at a dynamic level) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const logWarn = Effect.logWithLevel("Warn") + * + * const program = Effect.gen(function*() { + * yield* logWarn("Cache miss") + * }) + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Warn: Cache miss"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWithLevel = _internal_effect_js__rspack_import_1/* .logWithLevel */.lIX; +/** + * Logs one or more messages using the default log level. + * + * **Example** (Logging at the default level) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = 2 + 2 + * yield* Effect.log("Result:", result) + * return result + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * void output.push(Effect.runSync(runnable)) + * output // => ["Info: Result: 4", 4] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const log = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel())); +/** + * Logs one or more messages at the FATAL level. + * + * **Example** (Logging fatal messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logFatal("Critical system failure") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * Effect.runSync(runnable) + * output // => ["Fatal: Critical system failure"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logFatal = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Fatal"))); +/** + * Logs one or more messages at the WARNING level. + * + * **Example** (Logging warnings) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logWarning("API rate limit approaching") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Warn: API rate limit approaching"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWarning = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Warn"))); +/** + * Logs one or more messages at the ERROR level. + * + * **Example** (Logging errors) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logError("Database connection failed") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Error: Database connection failed"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logError = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Error"))); +/** + * Logs one or more messages at the INFO level. + * + * **Example** (Logging information) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logInfo("Application starting up") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Info: Application starting up"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logInfo = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Info"))); +/** + * Logs one or more messages at the DEBUG level. + * + * **Example** (Logging debug messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logDebug("Debug mode enabled") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Debug: Debug mode enabled"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logDebug = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Debug"))); +/** + * Logs one or more messages at the TRACE level. + * + * **Example** (Logging trace messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logTrace("Entering function processData") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Trace"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Trace: Entering function processData"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logTrace = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Trace"))); +/** + * Adds a logger to the set of loggers which will output logs for this effect. + * + * **Example** (Adding a logger to an effect) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * // Create a custom logger that logs to the console + * const customLogger = Logger.make(({ message }) => + * void output.push(`[CUSTOM]: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * ) + * + * const program = Effect.gen(function*() { + * yield* Effect.log("This will go to both default and custom logger") + * return "completed" + * }) + * + * // Add the custom logger to the effect + * const programWithLogger = Effect.withLogger(program, customLogger) + * + * Effect.runSync(Effect.provide(programWithLogger, Logger.layer([]))) + * output // => ["[CUSTOM]: This will go to both default and custom logger"] + * ``` + * + * @category logging + * @since 4.0.0 + */ +const withLogger = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, logger) => internal.updateService(effect, internal.CurrentLoggers, loggers => new Set([...loggers, logger]))))); +/** + * Adds an annotation to each log line in this effect. + * + * **Example** (Adding log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.log("Starting operation") + * }) + * + * // Add annotations to all log messages + * const annotatedProgram = Effect.annotateLogs(program, { + * userId: "user123", + * operation: "data-processing" + * }) + * + * // Also supports single key-value annotations + * const singleAnnotated = Effect.annotateLogs(program, "requestId", "req-456") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * const run = (effect: Effect.Effect) => + * Effect.runSync(Effect.provide(effect, Logger.layer([logger]))) + * run(annotatedProgram) + * run(singleAnnotated) + * output // => ["Starting operation", "Starting operation"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const annotateLogs = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (effect, ...args) => internal.updateService(effect, CurrentLogAnnotations, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + InternalRecord.assignProperty(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})))); +/** + * Adds log annotations to the current scope. + * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * + * This differs from `annotateLogs`, which only annotates a specific effect. + * `annotateLogsScoped` updates annotations for the entire current `Scope` and + * restores the previous annotations when the scope closes. + * + * **Example** (Adding scoped log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.log("before") + * yield* Effect.annotateLogsScoped({ requestId: "req-123" }) + * yield* Effect.log("inside scope") + * }) + * ) + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["before", "inside scope"] + * ``` + * + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 + */ +const annotateLogsScoped = _internal_effect_js__rspack_import_1/* .annotateLogsScoped */.gsV; +/** + * Adds a span to each log line in this effect. + * + * **Example** (Adding a log span) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const databaseOperation = Effect.gen(function*() { + * yield* Effect.log("Connecting to database") + * yield* Effect.log("Executing query") + * yield* Effect.log("Processing results") + * return "data" + * }) + * + * const httpRequest = Effect.gen(function*() { + * yield* Effect.log("Making HTTP request") + * const data = yield* Effect.withLogSpan(databaseOperation, "db-operation") + * yield* Effect.log("Sending response") + * return data + * }) + * + * const program = Effect.withLogSpan(httpRequest, "http-handler") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * void output.push(Effect.runSync(Effect.provide(program, Logger.layer([logger])))) + * output // => ["Making HTTP request", "Connecting to database", "Executing query", "Processing results", "Sending response", "data"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const withLogSpan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, label) => internal.flatMap(internal.currentTimeMillis, now => internal.updateService(effect, CurrentLogSpans, spans => { + const span = [label, now]; + return [span, ...spans]; +}))))); +// ----------------------------------------------------------------------------- +// Metrics +// ----------------------------------------------------------------------------- +/** + * Updates the `Metric` every time the `Effect` is executed. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Exit` value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Incrementing a metric for each execution) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const counter = Metric.counter("effect_executions", { + * description: "Counts effect executions" + * }).pipe(Metric.withConstantInput(1)) + * + * const program = Effect.succeed("Hello").pipe( + * Effect.track(counter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(counter)).count // => 1 + * ``` + * + * **Example** (Mapping exits before updating a metric) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Metric } from "effect" + * + * // Track different exit types with custom mapping + * const exitTracker = Metric.frequency("exit_types", { + * description: "Tracks success/failure/defect counts" + * }) + * + * const mapExitToString = (exit: Exit.Exit) => { + * if (Exit.isSuccess(exit)) return "success" + * if (Exit.isFailure(exit)) return "failure" + * return "defect" + * } + * + * const effect = Effect.succeed("result").pipe( + * Effect.track(exitTracker, mapExitToString) + * ) + * Effect.runSync(effect) + * Effect.runSync(Metric.value(exitTracker)).occurrences.get("success") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const track = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => onExit(self, exit => { + const input = f === undefined ? exit : internalCall(() => f(exit)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` succeeds with + * a value. + * + * **Details** + * + * Also accepts an optional function which can be used to map the success value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting successful results) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const successCounter = Metric.counter("successes").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.succeed(42).pipe( + * Effect.trackSuccesses(successCounter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(successCounter)).count // => 1 + * ``` + * + * **Example** (Mapping successes before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track successful request sizes + * const requestSizeGauge = Metric.gauge("request_size_bytes") + * + * const program = Effect.succeed("Hello World!").pipe( + * Effect.trackSuccesses(requestSizeGauge, (value: string) => value.length) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(requestSizeGauge)).value // => 12 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackSuccesses = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tap(self, value => { + const input = f === undefined ? value : f(value); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **expected** error. + * + * **Details** + * + * Also accepts an optional function which can be used to map the error value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting expected failures) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const errorCounter = Metric.counter("errors").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.fail("Network timeout").pipe( + * Effect.trackErrors(errorCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorCounter)).count // => 1 + * ``` + * + * **Example** (Mapping errors before tracking) + * + * ```ts import.meta.vitest + * import { Data, Effect, Metric } from "effect" + * + * class ConnectionFailedError extends Data.TaggedError("ConnectionFailedError")<{}> {} + * + * // Track error types using frequency metric + * const errorTypeFrequency = Metric.frequency("error_types") + * + * const program = Effect.fail(new ConnectionFailedError()).pipe( + * Effect.trackErrors(errorTypeFrequency, (error: ConnectionFailedError) => error._tag) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorTypeFrequency)).occurrences.get("ConnectionFailedError") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackErrors = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapError(self, error => { + const input = f === undefined ? error : internalCall(() => f(error)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **unexpected** error (i.e. a defect). + * + * **Details** + * + * Also accepts an optional function which can be used to map the defect value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting defects) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const defectCounter = Metric.counter("defects").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.die("Critical system failure").pipe( + * Effect.trackDefects(defectCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectCounter)).count // => 1 + * ``` + * + * **Example** (Mapping defects before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track defect types using frequency metric + * const defectTypeFrequency = Metric.frequency("defect_types") + * + * const program = Effect.die(new Error("Null pointer exception")).pipe( + * Effect.trackDefects(defectTypeFrequency, (defect: unknown) => { + * if (defect instanceof Error) return defect.constructor.name + * return typeof defect + * }) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectTypeFrequency)).occurrences.get("Error") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDefects = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapDefect(self, defect => { + const input = f === undefined ? defect : internalCall(() => f(defect)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) + * that the wrapped `Effect` took to complete. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Duration` + * that the wrapped `Effect` took to complete into a valid `Input` for the + * `Metric`. + * + * **Example** (Recording execution duration) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const executionTimer = Metric.timer("execution_time") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(executionTimer) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(executionTimer)).count // => 1 + * ``` + * + * **Example** (Mapping duration before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track execution time in milliseconds using custom mapping + * const durationGauge = Metric.gauge("execution_millis") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(durationGauge, () => 1) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(durationGauge)).value // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDuration = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => clockWith(clock => { + const startTime = clock.monotonicTimeNanosUnsafe(); + return onExit(self, () => { + const endTime = clock.monotonicTimeNanosUnsafe(); + const duration = Duration.subtract(Duration.fromInputUnsafe(endTime), Duration.fromInputUnsafe(startTime)); + const input = f === undefined ? duration : internalCall(() => f(duration)); + return Metric.update(metric, input); + }); +})))); +// ----------------------------------------------------------------------------- +// Transactions +// ----------------------------------------------------------------------------- +/** + * Service that holds the current transaction state. + * + * **Details** + * + * It includes a journal that stores non-committed changes to `TxRef` values and + * a retry flag that records whether the transaction should be retried. + * + * **Example** (Building transactions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Transaction class for software transactional memory operations + * const txEffect = Effect.gen(function*() { + * const tx = yield* Effect.Transaction + * // Use transaction for coordinated state changes + * return "Transaction complete" + * }) + * + * const runnable = Effect.provideService(txEffect, Effect.Transaction, { + * retry: false, + * journal: new Map() + * }) + * Effect.runSync(runnable) // => "Transaction complete" + * ``` + * + * @category services + * @since 4.0.0 + */ +class Transaction extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Effect/Transaction"))) {} +/** + * Defines a transaction boundary. Transactions are "all or nothing" with respect to changes + * made to transactional values (i.e. TxRef) that occur within the transaction body. + * + * **Details** + * + * If called inside an active transaction, `tx` composes with the current transaction and reuses + * its journal and retry state instead of creating a nested boundary. + * + * Effect transactions are optimistic with retry. A transaction is retried when + * its body explicitly calls `Effect.txRetry` and any accessed transactional + * value changes, or when any accessed transactional value changes because a + * different transaction commits before the current one. + * + * The outermost `tx` call creates the transaction boundary and commits or rolls back the full + * composed transaction. + * + * **Example** (Running a transaction) + * + * ```ts import.meta.vitest + * import { Effect, TxRef } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ref1 = yield* TxRef.make(0) + * const ref2 = yield* TxRef.make(0) + * + * // Nested tx calls compose into the same transaction + * yield* Effect.tx(Effect.gen(function*() { + * yield* TxRef.set(ref1, 10) + * yield* Effect.tx(TxRef.set(ref2, 20)) + * const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2)) + * void output.push(`Transaction sum: ${sum}`) + * })) + * + * void output.push(`Final ref1: ${yield* TxRef.get(ref1)}`) + * void output.push(`Final ref2: ${yield* TxRef.get(ref2)}`) + * }) + * + * Effect.runSync(program) + * output // => ["Transaction sum: 30", "Final ref1: 10", "Final ref2: 20"] + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const tx = effect => withFiber(fiber => { + let state = Context.getOrUndefined(fiber.context, Transaction); + if (state) { + return effect; + } + // Create transaction state only at the outermost boundary + state = { + journal: new Map(), + retry: false + }; + let result; + return uninterruptibleMask(restore => flatMap(whileLoop({ + while: () => !result, + body: constant(restore(effect).pipe(provideService(Transaction, state), tapCause(() => { + if (!state.retry) return void_; + return restore(awaitPendingTransaction(state)); + }), exit)), + step(exit) { + if (state.retry || !isTransactionConsistent(state)) { + return clearTransaction(state); + } + if (Exit.isSuccess(exit)) { + commitTransaction(fiber, state); + } else { + clearTransaction(state); + } + result = exit; + } + }), () => result)); +}); +const isTransactionConsistent = state => { + for (const [ref, { + version + }] of state.journal) { + if (ref.version !== version) { + return false; + } + } + return true; +}; +const awaitPendingTransaction = state => suspend(() => { + const key = {}; + const refs = Array.from(state.journal.keys()); + const clearPending = () => { + for (const clear of refs) { + clear.pending.delete(key); + } + }; + return callback(resume => { + const onCall = () => { + clearPending(); + resume(void_); + }; + for (const ref of refs) { + ref.pending.set(key, onCall); + } + return sync(clearPending); + }); +}); +function commitTransaction(fiber, state) { + for (const [ref, { + value + }] of state.journal) { + if (value !== ref.value) { + ref.version = ref.version + 1; + ref.value = value; + } + for (const pending of ref.pending.values()) { + fiber.currentDispatcher.scheduleTask(pending, 0); + } + ref.pending.clear(); + } +} +function clearTransaction(state) { + state.retry = false; + state.journal.clear(); +} +/** + * Retries the current transaction by signaling that it must be retried. + * + * **Details** + * + * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. + * + * **Example** (Retrying transactions) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, TxRef } from "effect" + * + * const program = Effect.gen(function*() { + * const ref = yield* TxRef.make(0) + * const update = yield* Deferred.make() + * + * yield* Effect.forkChild( + * Deferred.await(update).pipe(Effect.andThen(Effect.tx(TxRef.set(ref, 1)))) + * ) + * + * return yield* Effect.tx(Effect.gen(function*() { + * const value = yield* TxRef.get(ref) + * if (value === 0) { + * yield* Deferred.succeed(update, undefined) + * return yield* Effect.txRetry + * } + * return value + * })) + * }) + * + * await Effect.runPromise(program) // => 1 + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const txRetry = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(Transaction, state => { + state.retry = true; + return interrupt; +}))); +/** + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const uppercase = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(null, input.toUpperCase())) + * + * const effectfulUppercase = Effect.effectify(uppercase) + * const program = effectfulUppercase("hello") + * + * await Effect.runPromise(program) // => "HELLO" + * ``` + * + * **Example** (Mapping callback errors to typed failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const fail = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(new Error("unavailable"))) + * + * const effectfulFail = Effect.effectify( + * fail, + * (error, args) => new Error(`Failed to process ${args[0]}: ${error.message}`) + * ) + * + * const program = Effect.flip(effectfulFail("hello")) + * + * const error = await Effect.runPromise(program) + * error.message // => "Failed to process hello: unavailable" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const effectify = (fn, onError, onSyncError) => (...args) => callback(resume => { + try { + fn(...args, (err, result) => { + if (err) { + resume(fail(onError ? onError(err, args) : err)); + } else { + resume(succeed(result)); + } + }); + } catch (err) { + resume(onSyncError ? fail(onSyncError(err, args)) : die(err)); + } +}); +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that an effect's success type extends a given type `A`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the success type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Effect.satisfiesSuccessType() + * + * // This works - Effect<42, never, never> extends Effect + * const validEffect = satisfiesNumber(Effect.succeed(42)) + * Effect.runSync(validEffect) // => 42 + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesNumber(Effect.succeed("string")) + * // ^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'number' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => effect => effect; +/** + * Ensures that an effect's error type extends a given type `E`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the error type) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ValidationError extends Data.TaggedError("ValidationError")<{}> {} + * + * // Define a constraint that the error type must be a ValidationError + * const satisfiesError = Effect.satisfiesErrorType() + * + * // This works - Effect extends the constrained type + * const validEffect = satisfiesError(Effect.fail(new ValidationError())) + * Effect.runSync(Effect.flip(validEffect))._tag // => "ValidationError" + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesError(Effect.fail("string error")) + * // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'ValidationError' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => effect => effect; +/** + * Ensures that an effect's requirements type extends a given type `R`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the services type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that requires a string as the requirements type + * const satisfiesStringServices = Effect.satisfiesServicesType() + * + * // This works - effect requires string + * const validEffect: Effect.Effect = Effect.succeed(42) + * const constrainedEffect = satisfiesStringServices(validEffect) + * + * // This would cause a TypeScript compilation error if uncommented: + * // const invalidEffect: Effect.Effect = Effect.succeed(42) + * // const constrainedInvalid = satisfiesStringServices(invalidEffect) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => effect => effect; +/** + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. + * + * **Details** + * + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. + * + * **Example** (Mapping already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the mapping is applied immediately + * const resolved = Effect.succeed(5) + * const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly + * + * // For pending effects, behaves like regular map + * const pending = Effect.delay(Effect.succeed(5), 0) + * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map + * + * await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapEager = _internal_effect_js__rspack_import_1/* .mapEager */.jkJ; +/** + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. + * + * **Example** (Mapping errors eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the error mapping is applied immediately + * const failed = Effect.fail("original error") + * const mapped = Effect.mapErrorEager(failed, (err: string) => `mapped: ${err}`) // Applied eagerly + * + * // For pending effects, behaves like regular mapError + * const pending = Effect.delay(Effect.fail("error"), 0) + * const mappedPending = Effect.mapErrorEager( + * pending, + * (err: string) => `mapped: ${err}` + * ) // Uses regular mapError + * + * void output.push(await Effect.runPromise(Effect.all([ + * Effect.flip(mapped), + * Effect.flip(mappedPending) + * ]))) + * output // => [['mapped: original error', 'mapped: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const mapErrorEager = _internal_effect_js__rspack_import_1/* .mapErrorEager */.Z9x; +/** + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. + * + * **Details** + * + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. + * + * **Example** (Mapping both channels eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved effects, the appropriate mapping is applied immediately + * const success = Effect.succeed(5) + * const mapped = Effect.mapBothEager(success, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onSuccess applied eagerly + * + * const failure = Effect.fail("error") + * const mappedError = Effect.mapBothEager(failure, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onFailure applied eagerly + * + * void output.push(Effect.runSync(mapped)) + * void output.push(Effect.runSync(Effect.flip(mappedError))) + * output // => [10, "Failed: error"] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapBothEager = _internal_effect_js__rspack_import_1/* .mapBothEager */.q7Y; +/** + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. + * + * **Details** + * + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. + * + * **Example** (Flat mapping eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the flatMap is applied immediately + * const resolved = Effect.succeed(5) + * const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly + * + * // For pending effects, behaves like regular flatMap + * const pending = Effect.delay(Effect.succeed(5), 0) + * const flatMappedPending = Effect.flatMapEager( + * pending, + * (n) => Effect.succeed(n * 2) + * ) // Uses regular flatMap + * + * await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapEager = _internal_effect_js__rspack_import_1/* .flatMapEager */.Ab9; +/** + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. + * + * **Example** (Catching failures eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the catch function is applied immediately + * const failed = Effect.fail("original error") + * const recovered = Effect.catchEager( + * failed, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Applied eagerly + * + * // For success effects, returns success as-is + * const success = Effect.succeed(42) + * const unchanged = Effect.catchEager( + * success, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Returns success as-is + * + * // For pending effects, behaves like regular catch + * const pending = Effect.delay(Effect.fail("error"), 0) + * const recoveredPending = Effect.catchEager( + * pending, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Uses regular catch + * + * void output.push(await Effect.runPromise(Effect.all([ + * recovered, + * unchanged, + * recoveredPending + * ]))) + * output // => [['recovered from: original error', 42, 'recovered from: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchEager = _internal_effect_js__rspack_import_1/* .catchEager */.UVN; +/** + * Creates untraced function effects with eager evaluation optimization. + * + * **Details** + * + * Executes generator functions eagerly when all yielded effects are synchronous, + * stopping at the first async effect and deferring to normal execution. + * + * **Example** (Defining eager untraced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const computation = Effect.fnUntracedEager(function*() { + * yield* Effect.succeed(1) + * yield* Effect.succeed(2) + * return "computed eagerly" + * }) + * + * const effect = computation() // Executed immediately if all effects are sync + * Effect.runSync(effect) // => "computed eagerly" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fnUntracedEager = _internal_effect_js__rspack_import_1/* .fnUntracedEager */.vCS; +//# sourceMappingURL=Effect.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + $mh: tryPromise, + ATB: failCause, + Ab9: flatMapEager, + Bqz: flatten, + D9k: fnUntraced, + DYE: suspend, + E2r: callback, + F_Q: die, + GaK: interrupt, + JkU: gen, + KT6: raceFirst, + MY7: runFork, + Mim: tap, + NLW: asVoid, + NS5: exit, + NpQ: runPromiseExit, + OH5: sync, + PfK: provideService, + PyW: succeed, + Q56: acquireRelease, + S5A: onError, + SvU: try_, + TjK: map, + Tyx: catchCause, + Vdx: raceAll, + ZmZ: never, + _OA: context, + ar0: forkIn, + as: as, + cfM: onExit, + dsN: abortSignal, + eJC: runForkWith, + fJG: fail, + hgn: andThen, + i4r: forever, + iMI: whileLoop, + ivC: promise, + khu: matchCauseEffect, + m9E: yieldNow, + qIB: flatMap, + rIH: void_, + sFT: tapError, + yy4: sleep, + zhn: forkChild +}); + + +}, +"./node_modules/effect/dist/Effectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.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 + * + * @category prototypes + * @since 4.0.0 + */ +const Prototype = options => (0,_internal_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: options.label, + [_internal_core_js__rspack_import_0/* .evaluate */._3]: options.evaluate +}); +const Base = /*#__PURE__*/(/* unused pure expression or super */ null && ((() => { + const Base = function () {}; + Base.prototype = /*#__PURE__*/Prototype({ + label: "Effectable", + evaluate(_) { + return this; + } + }); + return Base; +})())); +/** + * Provides an abstract class that can be extended to create an `Effect`. + * + * **When to use** + * + * Use as an abstract base class to define custom classes whose instances behave + * as `Effect` values. + * + * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class + * @category constructors + * @since 2.0.0 + */ +class Class extends (/* unused pure expression or super */ null && (Base)) {} +//# sourceMappingURL=Effectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + b: Prototype +}); + + +}, +"./node_modules/effect/dist/Encoding.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text. + * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes. + * Encode functions return strings directly, while decode functions return + * `Result.Result` so invalid input is reported as an `EncodingError` instead of + * being thrown. + * + * @since 4.0.0 + */ + + + +// ------------------------------------------------------------------------------------- +// EncodingError +// ------------------------------------------------------------------------------------- +/** + * Type identifier stored on `EncodingError` values and used by + * `isEncodingError`. + * + * **When to use** + * + * Use when implementing low-level `EncodingError`-compatible values that need + * to carry the runtime marker. + * + * **Details** + * + * This marker is part of the runtime representation of `EncodingError`. Prefer + * `isEncodingError` when narrowing unknown values. + * + * @see {@link isEncodingError} for the public guard that checks this marker + * + * @category type IDs + * @since 4.0.0 + */ +const EncodingErrorTypeId = "~effect/encoding/EncodingError"; +/** + * Error returned when an encoding or decoding operation cannot process its + * input. + * + * **When to use** + * + * Use when you need to handle or inspect failures from encoding or decoding + * operations. + * + * **Details** + * + * The error records whether the failure happened during encoding or decoding, + * which encoding module reported it, the original input, and a human-readable + * message. + * + * @see {@link isEncodingError} for checking whether a value is an EncodingError + * @category errors + * @since 4.0.0 + */ +class EncodingError extends /*#__PURE__*/(/* unused pure expression or super */ null && (Data.TaggedError("EncodingError"))) { + /** + * Marks this value as an encoding or decoding error for runtime guards. + * + * **When to use** + * + * Use to identify `EncodingError` instances through `isEncodingError`. + * + * @since 4.0.0 + */ + [EncodingErrorTypeId] = EncodingErrorTypeId; +} +/** + * Checks whether a value is an `EncodingError`. + * + * **When to use** + * + * Use to narrow an unknown value before handling it as an `EncodingError` from + * encoding or decoding code. + * + * **Details** + * + * Returns `true` when the value carries the `EncodingErrorTypeId` marker and + * narrows the value to `EncodingError`. + * + * @see {@link EncodingError} for the structured error produced by failed + * encoding and decoding operations + * + * @category guards + * @since 4.0.0 + */ +const isEncodingError = u => hasProperty(u, EncodingErrorTypeId); +// ------------------------------------------------------------------------------------- +// Base64 +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (RFC4648) `string`. + * + * **When to use** + * + * Use to encode text or bytes as a standard padded Base64 string for storage or + * transport. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64 encoding. + * `Uint8Array` inputs are encoded directly. The output uses the standard + * RFC4648 alphabet with `=` padding. + * + * **Example** (Encoding Base64 strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string + * Encoding.encodeBase64("hello") // => "aGVsbG8=" + * + * // Encode binary data + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeBase64(bytes) // => "SGVsbG8=" + * ``` + * + * @see {@link decodeBase64} for decoding standard Base64 to bytes + * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text + * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64 = input => typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input); +/** + * Decodes a base64 (RFC4648) string into bytes safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into bytes without throwing on + * invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64 = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 !== 0) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Length must be a multiple of 4, but is ${length}` + })); + } + const index = stripped.indexOf("="); + if (index !== -1 && (index < length - 2 || index === length - 2 && stripped[length - 1] !== "=")) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Found a '=' character, but it is not at the end` + })); + } + try { + const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0; + const result = new Uint8Array(3 * (length / 4) - missingOctets); + for (let i = 0, j = 0; i < length; i += 4, j += 3) { + const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | getBase64Code(stripped.charCodeAt(i + 3)); + result[j] = buffer >> 16; + result[j + 1] = buffer >> 8 & 0xff; + result[j + 2] = buffer & 0xff; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a base64 (RFC4648) string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64String("aGVsbG8=") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64String = str => Result.map(decodeBase64(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Base64Url +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (URL) `string`. + * + * **When to use** + * + * Use to encode text or bytes as an unpadded Base64Url string for contexts that + * require the URL-safe alphabet. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64Url encoding. + * `Uint8Array` inputs are encoded directly. The output removes `=` padding and + * replaces `+` with `-` and `/` with `_`. + * + * **Example** (Encoding URL-safe Base64) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // URL-safe base64 encoding (uses - and _ instead of + and /) + * Encoding.encodeBase64Url("hello?") // => "aGVsbG8_" + * + * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63]) + * Encoding.encodeBase64Url(bytes) // => "SGVsbG8_" + * ``` + * + * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes + * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text + * @see {@link encodeBase64} for standard padded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64Url = input => typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input); +/** + * Decodes a URL-safe base64 string into bytes safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into bytes without throwing + * on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. Both padded and unpadded URL-safe base64 forms are accepted when + * otherwise valid. + * + * **Example** (Decoding URL-safe Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64Url("SGVsbG8_") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64Url = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 === 1) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: `Length should be a multiple of 4, but is ${length}` + })); + } + if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: "Invalid input" + })); + } + // Some variants allow or require omitting the padding '=' signs + let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped; + sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/"); + return decodeBase64(sanitized); +}; +/** + * Decodes a URL-safe base64 string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. + * + * **Example** (Decoding URL-safe Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64UrlString("aGVsbG8_") // => Result.succeed("hello?") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64UrlString = str => Result.map(decodeBase64Url(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Hex +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a hex `string`. + * + * **When to use** + * + * Use to encode text or bytes as lowercase hexadecimal text. + * + * **Example** (Encoding hex strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string to hex + * Encoding.encodeHex("hello") // => "68656c6c6f" + * + * // Encode binary data to hex + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeHex(bytes) // => "48656c6c6f" + * ``` + * + * @category encoding + * @since 2.0.0 + */ +const encodeHex = input => typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input); +/** + * Generates a random lowercase hexadecimal string, optimized for lengths that + * are multiples of 8. + * + * `length` is not validated. The function generates `length >>> 3` random + * 8-character words, so non-negative lengths below `2 ** 32` are rounded down + * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit + * coercion rules. + * + * This function uses `Math.random()` and is not cryptographically secure. For + * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes` + * method and encode the result with {@link encodeHex}. + * + * @category encoding + * @since 4.0.0 + */ +const randomHex = length => { + let result = ""; + for (let i = length >>> 3; i > 0; i--) { + const word = Math.random() * 0x100000000 >>> 0; + result += byteToHex[word >>> 24] + byteToHex[word >>> 16 & 0xff] + byteToHex[word >>> 8 & 0xff] + byteToHex[word & 0xff]; + } + return result; +}; +/** + * Decodes a hexadecimal string into bytes safely. + * + * **When to use** + * + * Use to decode hexadecimal text into bytes without throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input has an odd length or + * contains invalid hex characters. + * + * **Example** (Decoding hex bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHex("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHex = str => { + const bytes = new TextEncoder().encode(str); + if (bytes.length % 2 !== 0) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: `Length must be a multiple of 2, but is ${bytes.length}` + })); + } + try { + const length = bytes.length / 2; + const result = new Uint8Array(length); + for (let i = 0; i < length; i++) { + const a = fromHexChar(bytes[i * 2]); + const b = fromHexChar(bytes[i * 2 + 1]); + result[i] = a << 4 | b; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a hexadecimal string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode hexadecimal text into UTF-8 text without throwing on invalid + * input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid hex. + * + * **Example** (Decoding hex strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHexString("68656c6c6f") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHexString = str => Result.map(decodeHex(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// internals +// ------------------------------------------------------------------------------------- +const encoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextEncoder())); +const decoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextDecoder())); +const stripCrlf = str => str.replace(/[\n\r]/g, ""); +// Base64 internals +const base64EncodeUint8Array = bytes => { + const length = bytes.length; + let result = ""; + let i; + for (i = 2; i < length; i += 3) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2 | bytes[i] >> 6]; + result += base64abc[bytes[i] & 0x3f]; + } + if (i === length + 1) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4]; + result += "=="; + } + if (i === length) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2]; + result += "="; + } + return result; +}; +function getBase64Code(charCode) { + if (charCode >= base64codes.length) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + const code = base64codes[charCode]; + if (code === 255) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + return code; +} +const base64abc = (/* unused pure expression or super */ null && (["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"])); +const base64codes = (/* unused pure expression or super */ null && ([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51])); +// Base64Url internals +const base64UrlEncodeUint8Array = data => base64EncodeUint8Array(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +// Hex internals +const byteToHex = []; +for (let i = 0; i < 256; i++) { + byteToHex.push(i.toString(16).padStart(2, "0")); +} +const hexEncodeUint8Array = bytes => { + let result = ""; + for (let i = 0; i < bytes.length; i++) { + result += byteToHex[bytes[i]]; + } + return result; +}; +const fromHexChar = byte => { + if (48 <= byte && byte <= 57) { + return byte - 48; + } + if (97 <= byte && byte <= 102) { + return byte - 97 + 10; + } + if (65 <= byte && byte <= 70) { + return byte - 65 + 10; + } + throw new TypeError("Invalid input"); +}; +//# sourceMappingURL=Encoding.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + nw: randomHex +}); + + +}, +"./node_modules/effect/dist/Equal.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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; + } + // Special case for NaN: NaN should be considered equal to NaN + if (selfType === "number" && self !== self && that !== that) { + return true; + } + if (selfType !== "object" && selfType !== "function") { + return false; + } + if (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self) || _internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(that)) { + return false; + } + // For objects and functions, use cached comparison + return withCache(self, that, compareObjects); +} +/** Helper to run comparison with proper visited tracking */ +function withVisitedTracking(self, that, fn) { + const hasLeft = visitedLeft.has(self); + const hasRight = visitedRight.has(that); + // Check for circular references before adding + if (hasLeft && hasRight) { + return true; // Both are circular at the same level + } + if (hasLeft || hasRight) { + return false; // Only one is circular + } + visitedLeft.add(self); + visitedRight.add(that); + const result = fn(); + visitedLeft.delete(self); + visitedRight.delete(that); + return result; +} +const visitedLeft = /*#__PURE__*/new WeakSet(); +const visitedRight = /*#__PURE__*/new WeakSet(); +/** Helper to perform cached object comparison */ +function compareObjects(self, that) { + if (_Hash_js__rspack_import_1/* .hash */.tW(self) !== _Hash_js__rspack_import_1/* .hash */.tW(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) { + if (!(that instanceof RegExp)) return false; + return self.toString() === that.toString(); + } + const selfIsEqual = isEqual(self); + const thatIsEqual = isEqual(that); + if (selfIsEqual !== thatIsEqual) return false; + const bothEquals = selfIsEqual && thatIsEqual; + if (typeof self === "function" && !bothEquals) { + return false; + } + return withVisitedTracking(self, that, () => { + 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 (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) { + return false; + } + if (selfIsDataView) { + const thatDataView = that; + return compareTypedArrays(new Uint8Array(self.buffer, self.byteOffset, self.byteLength), new Uint8Array(thatDataView.buffer, thatDataView.byteOffset, thatDataView.byteLength)); + } + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) { + return false; + } + return compareMaps(self, that); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) { + return false; + } + return compareSets(self, that); + } + return compareRecords(self, that); + }); +} +function withCache(self, that, f) { + // Check cache first + let selfMap = equalityCache.get(self); + if (!selfMap) { + selfMap = new WeakMap(); + equalityCache.set(self, selfMap); + } else if (selfMap.has(that)) { + return selfMap.get(that); + } + // Perform the comparison + const result = f(self, that); + // Cache the result bidirectionally + selfMap.set(that, result); + let thatMap = equalityCache.get(that); + if (!thatMap) { + thatMap = new WeakMap(); + equalityCache.set(that, thatMap); + } + thatMap.set(self, result); + return result; +} +const equalityCache = /*#__PURE__*/new WeakMap(); +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 = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(self); + const thatKeys = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(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; +} +/** @internal */ +function makeCompareMap(keyEquivalence, valueEquivalence) { + return function compareMaps(self, that) { + const thatEntries = Array.from(that); + for (const [selfKey, selfValue] of self) { + let found = false; + for (let i = 0; i < thatEntries.length; i++) { + const [thatKey, thatValue] = thatEntries[i]; + if (keyEquivalence(selfKey, thatKey) && valueEquivalence(selfValue, thatValue)) { + thatEntries[i] = thatEntries[thatEntries.length - 1]; + thatEntries.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareMaps = /*#__PURE__*/makeCompareMap(compareBoth, compareBoth); +/** @internal */ +function makeCompareSet(equivalence) { + return function compareSets(self, that) { + const thatValues = Array.from(that); + for (const selfValue of self) { + let found = false; + for (let i = 0; i < thatValues.length; i++) { + const thatValue = thatValues[i]; + if (equivalence(selfValue, thatValue)) { + thatValues[i] = thatValues[thatValues.length - 1]; + thatValues.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareSets = /*#__PURE__*/makeCompareSet(compareBoth); +/** + * 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 property keyed by + * {@link symbol}. + * - 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 + * @category guards + * @since 2.0.0 + */ +const isEqual = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Wraps {@link equals} as an `Equivalence`. + * + * **When to use** + * + * Use when you want to pass `Equal.equals` to APIs that require an + * `Equivalence`. + * + * **Details** + * + * - Returns a function `(a: A, b: A) => boolean` that delegates to + * {@link equals}. + * - Pure; allocates a thin wrapper on each call. + * + * **Example** (Deduplicating with Equal semantics) + * + * ```ts import.meta.vitest + * import { Array, Equal } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 1], Equal.asEquivalence()) // => [1, 2, 3] + * ``` + * + * @see {@link equals} — the underlying comparison function + * @category instances + * @since 4.0.0 + */ +const asEquivalence = () => equals; +/** + * Creates a proxy that uses reference equality instead of structural equality. + * + * **When to use** + * + * Use when you need to compare a plain object or array by identity without + * mutating the original value. + * + * **Details** + * + * - Returns a `Proxy` wrapping `obj`. The proxy reads through to the + * original, so property access is unchanged. + * - The proxy is registered in an internal WeakSet; {@link equals} returns + * `false` for any pair where at least one operand is in that set (unless + * they are the same reference). + * - Each call creates a **new** proxy, so `byReference(x) !== byReference(x)`. + * - Does **not** mutate the original object (unlike {@link byReferenceUnsafe}). + * + * **Example** (Opting out of structural equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const a = { x: 1 } + * const b = { x: 1 } + * + * Equal.equals(a, b) // => true + * + * const aRef = Equal.byReference(a) + * Equal.equals(aRef, b) // => false + * Equal.equals(aRef, aRef) // => true + * aRef.x // => 1 + * ``` + * + * @see {@link byReferenceUnsafe} — same effect without a proxy (mutates the + * original) + * @see {@link equals} — the comparison function affected by this opt-out + * @category equality + * @since 4.0.0 + */ +const byReference = obj => byReferenceUnsafe(new Proxy(obj, {})); +/** + * Marks an object permanently to use reference equality, without creating a proxy. + * + * **When to use** + * + * Use when you need reference equality without proxy allocation and accept + * permanently marking the original object for reference-only equality. + * + * **Details** + * + * - Adds `obj` to an internal WeakSet. From that point on, {@link equals} + * treats it as reference-only. + * - Returns the **same** object (not a copy or proxy), so + * `byReferenceUnsafe(x) === x`. + * - Does **not** affect the object's prototype, properties, or behavior + * beyond equality checks. + * + * **Gotchas** + * + * The marking is irreversible for the lifetime of the object. + * + * **Example** (Marking an object for reference equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const obj1 = { a: 1, b: 2 } + * const obj2 = { a: 1, b: 2 } + * + * const marked = Equal.byReferenceUnsafe(obj1) + * + * Equal.equals(obj1, obj2) // => false + * Equal.equals(obj1, obj1) // => true + * marked === obj1 // => true + * ``` + * + * @see {@link byReference} — safer alternative that creates a proxy + * @see {@link equals} — the comparison function affected by this opt-out + * @category unsafe + * @since 4.0.0 + */ +const byReferenceUnsafe = obj => { + _internal_equal_js__rspack_import_0/* .byReferenceInstances.add */.J.add(obj); + return obj; +}; +//# sourceMappingURL=Equal.js.map +__webpack_require__.d(__webpack_exports__, { + aI: () => (equals) +}, { + HR: symbol, + Xq: byReferenceUnsafe, + jI: asEquivalence +}); + + +}, +"./node_modules/effect/dist/Equivalence.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Defines reusable equality functions for values of the same type. + * + * An `Equivalence` returns `true` when two `A` values should be treated as + * the same for a particular purpose. This module includes strict equality + * instances for primitive types, constructors for custom comparisons, and + * helpers for tuples, arrays, structs, records, dates, and values compared + * through a derived field. + * + * @since 2.0.0 + */ + + +/** + * Creates a custom equivalence relation with an optimized reference equality check. + * + * **When to use** + * + * Use when you need an equality rule that the built-in instances and input + * mapping helpers cannot express, and you can provide a law-abiding comparison. + * + * **Details** + * + * The returned equivalence first checks reference equality (`===`) for + * performance. If the values are not the same reference, it falls back to the + * provided equivalence function, which must satisfy reflexive, symmetric, and + * transitive properties. + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.make((a, b) => + * a.toLowerCase() === b.toLowerCase() + * ) + * + * caseInsensitive("Hello", "HELLO") // => true + * caseInsensitive("foo", "bar") // => false + * + * // Same reference optimization + * const str = "test" + * caseInsensitive(str, str) // => true + * ``` + * + * **Example** (Comparing numbers with tolerance) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const tolerance = Equivalence.make((a, b) => Math.abs(a - b) < 0.0001) + * + * tolerance(1.0, 1.001) // => false + * tolerance(1.0, 1.00001) // => true + * ``` + * + * @see {@link strictEqual} + * @see {@link mapInput} + * @category constructors + * @since 2.0.0 + */ +const make = isEquivalent => (self, that) => self === that || isEquivalent(self, that); +const isStrictEquivalent = (x, y) => x === y; +/** + * Creates an equivalence relation that uses strict equality (`===`) to compare values. + * + * **When to use** + * + * Use when you need strict equality (`===`) as the comparison. + * + * **Details** + * + * Uses JavaScript's strict equality operator (`===`). Primitives compare by + * value. Objects compare by reference, so only the same object instance is + * equivalent. Use this as a building block for more complex equivalences via + * `mapInput` or `combine`. + * + * **Gotchas** + * + * `NaN !== NaN`, so `NaN` values are never considered equivalent. + * + * **Example** (Comparing primitive types) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const strictEq = Equivalence.strictEqual() + * + * strictEq(1, 1) // => true + * strictEq(1, 2) // => false + * strictEq(NaN, NaN) // => false + * ``` + * + * **Example** (Comparing objects by reference) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const obj = { value: 42 } + * const strictObjEq = Equivalence.strictEqual() + * + * strictObjEq(obj, obj) // => true + * strictObjEq(obj, { value: 42 }) // => false + * ``` + * + * @see {@link make} + * @see `Equal` for structural equality + * @category constructors + * @since 4.0.0 + */ +const strictEqual = () => isStrictEquivalent; +/** + * Equivalence instance for strings using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply case-sensitive string equality. + * + * **Example** (Comparing strings) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.String("hello", "hello") // => true + * Equivalence.String("hello", "world") // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const String = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for numbers. + * + * **When to use** + * + * Use when you need numeric equality that treats NaN as equal to itself. + * + * **Example** (Comparing numbers) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Number(1, 1) // => true + * Equivalence.Number(1, 2) // => false + * Equivalence.Number(NaN, NaN) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)))); +/** + * Equivalence instance for booleans using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply boolean equality. + * + * **Example** (Comparing booleans) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Boolean(true, true) // => true + * Equivalence.Boolean(true, false) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Boolean = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for bigints using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply bigint equality. + * + * **Example** (Comparing bigints) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.BigInt(1n, 1n) // => true + * Equivalence.BigInt(1n, 2n) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const BigInt = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Combines two equivalence relations using logical AND. + * + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** + * + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining name and age equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * } + * + * const nameEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.name + * ) + * + * const ageEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.age + * ) + * + * const personEquivalence = Equivalence.combine(nameEquivalence, ageEquivalence) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Alice", age: 30 } + * const person3 = { name: "Alice", age: 31 } + * + * personEquivalence(person1, person2) // => true + * personEquivalence(person1, person3) // => false + * ``` + * + * @see {@link combineAll} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((x, y) => self(x, y) && that(x, y))))); +/** + * Combines multiple equivalence relations into a single equivalence using logical AND. + * + * **When to use** + * + * Use when you need to combine many `Equivalence` instances from an iterable. + * + * **Details** + * + * Returns `true` only if all equivalences in the collection return `true`. The + * comparison stops at the first equivalence that returns `false`. Empty + * collections return an equivalence that always returns `true`. The result is + * also an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining multiple field equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Point3D { + * x: number + * y: number + * z: number + * } + * + * const xEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.x + * ) + * const yEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.y + * ) + * const zEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.z + * ) + * + * const point3DEq = Equivalence.combineAll([xEq, yEq, zEq]) + * + * const point1 = { x: 1, y: 2, z: 3 } + * const point2 = { x: 1, y: 2, z: 3 } + * const point3 = { x: 1, y: 2, z: 4 } + * + * point3DEq(point1, point2) // => true + * point3DEq(point1, point3) // => false + * ``` + * + * **Example** (Handling empty collections) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * // Empty collection always returns true + * const alwaysEq = Equivalence.combineAll([]) + * alwaysEq("anything", "else") // => true + * ``` + * + * @see {@link combine} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combineAll = collection => make((x, y) => { + for (const equivalence of collection) { + if (!equivalence(x, y)) { + return false; + } + } + return true; +}); +/** + * Transforms an equivalence relation by mapping the input values before comparison. + * + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** + * + * - Applies the transformation function to both values before comparing + * - The transformation function should be pure and have no side effects + * - The resulting equivalence compares the transformed values using the provided equivalence + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings + * + * **Example** (Deriving equivalence from an object property) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface User { + * id: number + * name: string + * email: string + * } + * + * // Create equivalence based on user ID only + * const userByIdEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (user: User) => user.id + * ) + * + * const user1 = { id: 1, name: "Alice", email: "alice@example.com" } + * const user2 = { id: 1, name: "Alice Smith", email: "alice.smith@example.com" } + * const user3 = { id: 2, name: "Bob", email: "bob@example.com" } + * + * userByIdEq(user1, user2) // => true + * userByIdEq(user1, user3) // => false + * ``` + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitiveEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * caseInsensitiveEq("Hello", "HELLO") // => true + * caseInsensitiveEq("Hello", "World") // => false + * ``` + * + * @see {@link combine} + * @see {@link Struct} + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => make((x, y) => self(f(x), f(y)))))); +/** + * Creates an equivalence for tuples with heterogeneous element types. + * + * **When to use** + * + * Use when you need an `Equivalence` for fixed-length tuples with per-position + * equivalences. + * + * **Details** + * + * Tuples must have the same length; different lengths are never equivalent. + * Each equivalence is applied to the corresponding element position. The result + * returns `true` only if all elements are equivalent according to their + * respective equivalences, and it also satisfies reflexive, symmetric, and + * transitive properties. + * + * **Example** (Comparing homogeneous tuples) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringTupleEq = Equivalence.Tuple([ + * Equivalence.strictEqual(), + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ]) + * + * const tuple1 = ["hello", "world", "test"] as const + * const tuple2 = ["hello", "world", "test"] as const + * const tuple3 = ["hello", "world", "different"] as const + * + * stringTupleEq(tuple1, tuple2) // => true + * stringTupleEq(tuple1, tuple3) // => false + * ``` + * + * **Example** (Comparing tuples with custom equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const customTupleEq = Equivalence.Tuple([ + * caseInsensitive, + * caseInsensitive, + * caseInsensitive + * ]) + * + * customTupleEq(["Hello", "World", "Test"], ["HELLO", "WORLD", "TEST"]) // => true + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + if (self.length !== that.length) { + return false; + } + for (let i = 0; i < self.length; i++) { + if (!elements[i](self[i], that[i])) { + return false; + } + } + return true; + }); +} +/** + * @since 4.0.0 + */ +function Array_(item) { + return make((self, that) => { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) { + if (!item(self[i], that[i])) return false; + } + return true; + }); +} + +/** + * Creates an equivalence for objects by comparing their properties using provided equivalences. + * + * **When to use** + * + * Use when you need an `Equivalence` for objects with known, fixed property + * names. + * + * **Details** + * + * Compares only the properties specified in the struct definition; other + * properties are ignored. String and symbol keys are supported via + * `Reflect.ownKeys`. The result returns `true` only if all specified properties + * are equivalent according to their equivalences, and it also satisfies + * reflexive, symmetric, and transitive properties. + * + * **Example** (Comparing structs with different equivalences per field) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * email: string + * } + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const personEq = Equivalence.Struct({ + * name: caseInsensitive, + * age: Equivalence.strictEqual(), + * email: caseInsensitive + * }) + * + * const person1 = { name: "Alice", age: 30, email: "alice@example.com" } + * const person2 = { name: "ALICE", age: 30, email: "ALICE@EXAMPLE.COM" } + * const person3 = { name: "Alice", age: 31, email: "alice@example.com" } + * + * personEq(person1, person2) // => true + * personEq(person1, person3) // => false + * ``` + * + * **Example** (Comparing specific fields) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const nameAgeEq = Equivalence.Struct({ + * name: Equivalence.strictEqual(), + * age: Equivalence.strictEqual() + * }) + * + * // Only compares name and age, ignores other properties + * const obj1 = { name: "Alice", age: 30, extra: "ignored" } + * const obj2 = { name: "Alice", age: 30, extra: "different" } + * nameAgeEq(obj1, obj2) // => true + * ``` + * + * @see {@link Record} + * @see {@link mapInput} + * @see {@link combine} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Reflect.ownKeys(fields); + return make((self, that) => { + for (const key of keys) { + if (!fields[key](self[key], that[key])) return false; + } + return true; + }); +} +/** + * Creates an equivalence for objects by comparing all properties using the same equivalence. + * + * **When to use** + * + * Use when you need to compare records with the same equivalence for every + * property value. + * + * **Details** + * + * - Compares all properties present in both objects + * - Requires both objects to have the same set of keys; different keys result in `false` + * - All property values must be equivalent according to the provided equivalence + * - Supports both string and symbol keys via `Reflect.ownKeys` + * - Empty objects are considered equivalent + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * + * **Example** (Defining records with string values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const record1 = { a: "hello", b: "world" } + * const record2 = { a: "hello", b: "world" } + * const record3 = { a: "hello", b: "different" } + * const record4 = { a: "hello" } // missing key 'b' + * + * stringRecordEq(record1, record2) // => true + * stringRecordEq(record1, record3) // => false + * stringRecordEq(record1, record4) // => false + * ``` + * + * **Example** (Defining records with number values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const numberRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const scores1 = { alice: 100, bob: 85 } + * const scores2 = { alice: 100, bob: 85 } + * const scores3 = { alice: 100, bob: 90 } + * + * numberRecordEq(scores1, scores2) // => true + * numberRecordEq(scores1, scores3) // => false + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Record(value) { + return make((self, that) => { + const selfKeys = Reflect.ownKeys(self); + const thatKeys = Reflect.ownKeys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (const key of selfKeys) { + if (!Object.hasOwn(that, key) || !value(self[key], that[key])) { + return false; + } + } + return true; + }); +} +/** + * Creates a `Reducer` for combining `Equivalence` instances, useful for aggregating equivalences in collections. + * + * **When to use** + * + * Use when you need a reducer that combines equivalences. + * + * **Details** + * + * Returns a reducer that combines equivalences using `combine`. The identity + * element for empty collections is an equivalence that always returns `true`. + * The reducer uses `combineAll` for collections of equivalences and can be used + * with fold operations. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const reducer = Equivalence.makeReducer() + * const equivalences = [ + * Equivalence.strictEqual(), + * Equivalence.make((a, b) => Math.abs(a - b) < 1) + * ] + * + * const combined = reducer.combineAll(equivalences) + * // Combined equivalence requires both conditions to be true + * combined(1, 1) // => true + * combined(1, 1.5) // => false + * ``` + * + * @see {@link combine} Combine two equivalences + * @see {@link combineAll} Combine multiple equivalences + * @see {@link Reducer} Reducer type for collection operations + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => true, combineAll); +} +/** + * Equivalence instance for `Date` objects that compares their `getTime()` values using `Equivalence.Number`. + * + * **When to use** + * + * Use when you need an `Equivalence` for JavaScript date objects by their + * millisecond timestamp. + * + * **Details** + * + * Different `Date` instances that represent the same millisecond timestamp are equivalent. Because `Equivalence.Number` + * treats `NaN` as equal to `NaN`, two invalid `Date` values are also considered equivalent. + * + * **Example** (Comparing Date values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date("2020-01-01T00:00:00.000Z") + * const d2 = new Date("2020-01-01T00:00:00.000Z") + * const d3 = new Date("2021-01-01T00:00:00.000Z") + * const invalidDate1 = new Date("foo") + * const invalidDate2 = new Date("bar") + * + * Equivalence.Date(d1, d2) // => true + * Equivalence.Date(d1, d3) // => false + * Equivalence.Date(invalidDate1, invalidDate2) // => true + * Equivalence.Date(invalidDate1, d1) // => false + * ``` + * + * **Example** (Comparing reference and value equality) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date(0) + * const d2 = new Date(0) + * + * d1 === d2 // => false + * Equivalence.Date(d1, d2) // => true + * ``` + * + * @see {@link Number} for the numeric equivalence applied to each `Date#getTime()` result + * @see {@link mapInput} for deriving an equivalence by mapping inputs before comparison + * @see {@link strictEqual} for reference equality when two values must be the same object + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, d => d.getTime()))); +//# sourceMappingURL=Equivalence.js.map +__webpack_require__.d(__webpack_exports__, { + O3: () => (Array_) +}, { + L8: make +}); + + +}, +"./node_modules/effect/dist/ExecutionPlan.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); + + + + + + +/** + * Runtime type identifier attached to `ExecutionPlan` values and used by + * `isExecutionPlan`. + * + * @category type IDs + * @since 3.16.0 + */ +const TypeId = "~effect/ExecutionPlan"; +/** + * Returns `true` if a value is an `ExecutionPlan` by checking for the + * `ExecutionPlan.TypeId` marker. + * + * **When to use** + * + * Use when accepting an unknown value and you need to narrow it to an + * `ExecutionPlan` before reading plan fields or passing it to plan-consuming + * APIs. + * + * **Gotchas** + * + * This is a structural marker check; it does not validate the marker value or + * the shape of the plan steps. + * + * @see {@link make} for constructing execution plans that satisfy this guard + * @see {@link TypeId} for the runtime marker checked by this guard + * + * @category guards + * @since 3.16.0 + */ +const isExecutionPlan = u => Predicate.hasProperty(u, TypeId); +/** + * Create an `ExecutionPlan`, which can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. + * + * **Example** (Creating an execution plan) + * + * ```ts import.meta.vitest + * import { Context, ExecutionPlan } from "effect" + * + * const ThePlan = ExecutionPlan.make( + * { + * provide: Context.empty(), + * attempts: 2 + * }, + * { + * provide: Context.empty() + * } + * ) + * + * ThePlan.steps.length // => 2 + * ``` + * + * @category constructors + * @since 3.16.0 + */ +const make = (...steps) => makeProto(steps.map((options, i) => { + if (options.attempts !== undefined && options.attempts < 1) { + throw new Error(`ExecutionPlan.make: step[${i}].attempts must be greater than 0`); + } + return { + schedule: options.schedule, + attempts: options.attempts, + while: options.while ? input => effect.suspend(() => { + const result = options.while(input); + return typeof result === "boolean" ? effect.succeed(result) : result; + }) : undefined, + provide: options.provide + }; +})); +const Proto = (/* unused pure expression or super */ null && ({ + [TypeId]: TypeId, + get captureRequirements() { + const self = this; + return effect.contextWith(context => effect.succeed(makeProto(self.steps.map(step => ({ + ...step, + provide: Layer.isLayer(step.provide) ? Layer.provide(step.provide, Layer.succeedContext(context)) : step.provide + }))))); + }, + pipe() { + return pipeArguments(this, arguments); + } +})); +const makeProto = steps => { + const self = Object.create(Proto); + self.steps = steps; + return self; +}; +/** + * Combines multiple execution plans by concatenating their steps in order. + * + * **When to use** + * + * Use to combine separately defined fallback plans into one ordered plan before + * applying it to an effect or stream. + * + * **Details** + * + * The resulting plan tries every step from the first plan, then every step from + * the next plan, and so on. + * + * @see {@link make} for building a plan from individual steps instead of combining existing plans + * + * @category combining + * @since 3.16.0 + */ +const merge = (...plans) => makeProto(plans.flatMap(plan => plan.steps)); +/** + * Context reference containing metadata for the currently running + * execution-plan attempt. + * + * **When to use** + * + * Use to read the active plan step and attempt while code is running under an + * execution plan. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/ExecutionPlan/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + attempt: 0, + stepIndex: 0 + }) +}); +//# sourceMappingURL=ExecutionPlan.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + d3: CurrentMetadata +}); + + +}, +"./node_modules/effect/dist/Exit.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = _internal_core_js__rspack_import_0/* .ExitTypeId */.IH; +/** + * Checks whether an unknown value is an Exit. + * + * **When to use** + * + * Use to validate unknown values at system boundaries and narrow them to + * `Exit`. + * + * **Details** + * + * Does not inspect the contents of the Exit. Returns `true` for both Success + * and Failure exits. + * + * **Example** (Checking if a value is an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.isExit(Exit.succeed(42)) // => true + * Exit.isExit(Exit.fail("err")) // => true + * Exit.isExit("not an exit") // => false + * ``` + * + * @see {@link isSuccess} to check for a successful Exit + * @see {@link isFailure} to check for a failed Exit + * + * @category guards + * @since 2.0.0 + */ +const isExit = _internal_core_js__rspack_import_0/* .isExit */.b9; +/** + * Creates a successful Exit containing the given value. + * + * **When to use** + * + * Use when you need an Exit that contains a known success value. + * + * **Details** + * + * Returns a `Success` with the provided value. Does not perform any + * computation. + * + * **Example** (Creating a successful Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.succeed(42) // => Exit.succeed(42) + * ``` + * + * @see {@link fail} to create a failed Exit + * @see {@link void_ void} for a pre-allocated success with no value + * + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_core_js__rspack_import_0/* .exitSucceed */.xt; +/** + * Creates a failed Exit from a Cause. + * + * **When to use** + * + * Use when you already have a `Cause` and want to wrap it in an Exit + * for advanced error handling where you need full control over the Cause + * structure. + * + * **Details** + * + * Returns a `Failure`. If you only have an error value, use + * {@link fail} instead. + * + * **Example** (Creating a failed Exit from a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link fail} to create a Failure from a plain error value + * @see {@link die} to create a Failure from a defect + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_core_js__rspack_import_0/* .exitFailCause */.cb; +/** + * Creates a failed Exit from a typed error value. + * + * **When to use** + * + * Use when you need to represent an expected typed failure as an `Exit`. + * + * **Details** + * + * The error is wrapped in a `Cause.Fail` internally. + * + * Returns a `Failure`. + * + * **Example** (Creating a failed Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.fail("Something went wrong") // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link succeed} to create a successful Exit + * @see {@link die} to create a Failure from an unexpected defect + * @see {@link failCause} to create a Failure from a full Cause + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .exitFail */.Rk; +/** + * Creates a failed Exit from a defect (unexpected error). + * + * **When to use** + * + * Use when you need unexpected, unrecoverable errors that should not appear in + * the typed error channel. + * + * **Details** + * + * The defect is wrapped in a `Cause.Die` internally. + * + * Returns a `Failure` with `E = never`, since defects do not appear in + * the typed error channel. + * + * **Example** (Creating a defect Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.die("Unexpected error") // => Exit.die("Unexpected error") + * ``` + * + * @see {@link fail} to create a Failure from a typed error + * @see {@link hasDies} to check whether an Exit contains defects + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .exitDie */.V2; +/** + * Creates a failed Exit representing fiber interruption. + * + * **When to use** + * + * Use to signal that a fiber was interrupted. + * + * **Details** + * + * Optionally pass a fiber ID to identify which fiber was interrupted. Returns + * a `Failure` with an `Interrupt` cause. + * + * **Example** (Creating an interruption Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.interrupt(123) // => Exit.interrupt(123) + * ``` + * + * @see {@link hasInterrupts} to check whether an Exit contains interruptions + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .exitInterrupt */._sz; +const void_ = _internal_effect_js__rspack_import_1/* .exitVoid */.x5l; + +/** + * Checks whether an Exit is a Success. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Success` and access the + * `value` property. + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * const exit = Exit.succeed(42) + * + * if (Exit.isSuccess(exit)) { + * exit.value // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .exitIsSuccess */.CoE; +/** + * Checks whether an Exit is a Failure. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Failure` and access the + * `cause` property. + * + * **Example** (Narrowing to failure) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * const exit = Exit.fail("error") + * + * if (Exit.isFailure(exit)) { + * exit.cause // => Cause.fail("error") + * } + * ``` + * + * @see {@link isSuccess} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .exitIsFailure */.VE1; +/** + * Checks whether a failed Exit contains typed errors (Fail reasons). + * + * **When to use** + * + * Use to distinguish typed failures from defects or interruptions. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Fail` reasons in the + * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasFails(Exit.fail("err")) // => true + * Exit.hasFails(Exit.die("bug")) // => false + * Exit.hasFails(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasDies} to check for defects + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .exitHasFails */._mh; +/** + * Checks whether a failed Exit contains defects (Die reasons). + * + * **When to use** + * + * Use to check whether an `Exit` failure cause contains unexpected errors. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Die` reasons in the + * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasDies(Exit.die("bug")) // => true + * Exit.hasDies(Exit.fail("err")) // => false + * Exit.hasDies(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .exitHasDies */.YDM; +/** + * Checks whether a failed Exit contains interruptions (Interrupt reasons). + * + * **When to use** + * + * Use to check whether an `Exit` contains fiber interruption. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Interrupt` reasons in + * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasInterrupts(Exit.interrupt(1)) // => true + * Exit.hasInterrupts(Exit.fail("err")) // => false + * Exit.hasInterrupts(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasDies} to check for defects + * + * @category guards + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .exitHasInterrupts */.lNM; +/** + * Extracts the Success variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Success wrapper. + * + * **Details** + * + * Returns `Result.succeed(success)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for success) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterSuccess(Exit.succeed(42)) // => Result.succeed(Exit.succeed(42)) + * ``` + * + * @see {@link filterFailure} for the inverse + * @see {@link filterValue} to extract the raw value instead of the Success object + * + * @category filtering + * @since 4.0.0 + */ +const filterSuccess = _internal_effect_js__rspack_import_1/* .exitFilterSuccess */.K$2; +/** + * Extracts the success value from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw success value rather than the Success + * wrapper. + * + * **Details** + * + * Returns `Result.succeed(value)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the value) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterValue(Exit.succeed(42)) // => Result.succeed(42) + * ``` + * + * @see {@link filterSuccess} to get the full Success object + * @see {@link getSuccess} to get the value as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterValue = _internal_effect_js__rspack_import_1/* .exitFilterValue */.GUt; +/** + * Extracts the Failure variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(failure)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for failure) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterFailure(Exit.fail("err")) // => Result.succeed(Exit.fail("err")) + * ``` + * + * @see {@link filterSuccess} for the inverse + * @see {@link filterCause} to extract the Cause directly + * + * @category filtering + * @since 4.0.0 + */ +const filterFailure = _internal_effect_js__rspack_import_1/* .exitFilterFailure */.HIt; +/** + * Extracts the Cause from a failed Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw Cause rather than the Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(cause)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Result } from "effect" + * + * Exit.filterCause(Exit.fail("err")) // => Result.succeed(Cause.fail("err")) + * ``` + * + * @see {@link filterFailure} to get the full Failure object + * @see {@link getCause} to get the Cause as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterCause = _internal_effect_js__rspack_import_1/* .exitFilterCause */.yJo; +/** + * Extracts the first typed error value from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(error)` when the Cause contains a Fail reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple errors, the rest + * are ignored. + * + * **Example** (Finding the first typed error) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findError(Exit.fail("not found")) // => Result.succeed("not found") + * Exit.findError(Exit.die("bug")) // => Result.fail(Exit.die("bug")) + * ``` + * + * @see {@link findErrorOption} to get the error as an Option instead + * @see {@link findDefect} to find defects instead + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .exitFindError */._OD; +/** + * Extracts the first defect from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first defect from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(defect)` when the Cause contains a Die reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Die reason. If the Cause has multiple defects, the rest + * are ignored. + * + * **Example** (Finding the first defect) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findDefect(Exit.die("boom")) // => Result.succeed("boom") + * Exit.findDefect(Exit.fail("err")) // => Result.fail(Exit.fail("err")) + * ``` + * + * @see {@link findError} to find typed errors instead + * @see {@link hasDies} to check for defects without extracting them + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .exitFindDefect */.jCT; +/** + * Pattern matches on an Exit, handling both success and failure cases. + * + * **When to use** + * + * Use when you need exhaustive handling of both `Exit` success and failure + * outcomes. + * + * **Details** + * + * Calls `onSuccess` with the value if the Exit is a Success, and calls + * `onFailure` with the Cause if the Exit is a Failure. + * + * **Example** (Matching on an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.match(Exit.succeed(42), { + * onSuccess: (value) => `Got: ${value}`, + * onFailure: () => "Failed" + * }) // => "Got: 42" + * ``` + * + * @see {@link isSuccess} and {@link isFailure} for simple boolean checks + * + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .exitMatch */.Wtn; +/** + * Transforms the success value of an Exit using the given function. + * + * **When to use** + * + * Use to apply a transformation to the value inside a successful Exit + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Mapping over a success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.map(Exit.succeed(21), (x) => x * 2) // => Exit.succeed(42) + * ``` + * + * @see {@link mapError} to transform the error + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .exitMap */.v9O; +/** + * Transforms the typed error of a failed Exit using the given function. + * + * **When to use** + * + * Use to remap typed errors while preserving the Exit structure + * + * **Details** + * + * Successes pass through unchanged. + * + * Allocates a new Exit if the error is transformed. + * + * **Gotchas** + * + * Only transforms typed errors (Fail reasons). If the Cause contains only + * defects or interruptions, the failure passes through unchanged. + * + * **Example** (Mapping over an error) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapError(Exit.fail("bad input"), (error) => error.toUpperCase()) // => Exit.fail("BAD INPUT") + * ``` + * + * @see {@link map} to transform the success value + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .exitMapError */.zPu; +/** + * Transforms both the success value and typed error of an Exit. + * + * **When to use** + * + * Use when you need to remap both channels in one step. + * + * **Details** + * + * `onSuccess` transforms the value if the Exit is a Success. `onFailure` + * transforms the typed error if the Exit is a Failure with a Fail reason. + * Allocates a new Exit. + * + * **Gotchas** + * + * If the Cause contains only defects or interruptions, the failure passes + * through unchanged. + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapBoth(Exit.succeed(42), { + * onSuccess: (x) => String(x), + * onFailure: (error: string) => error.toUpperCase() + * }) // => Exit.succeed("42") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error + * + * @category combinators + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .exitMapBoth */.EkE; +/** + * Discards the success value of an Exit, replacing it with `void`. + * + * **When to use** + * + * Use when you need to discard a successful `Exit` value while preserving + * whether the `Exit` succeeded or failed. + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Discarding the success value) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoid(Exit.succeed(42)) // => Exit.succeed(undefined) + * ``` + * + * @see {@link void_ void} for a pre-allocated void success + * @see {@link asVoidAll} to combine multiple exits into a single void Exit + * + * @category combinators + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .exitAsVoid */.Hox; +/** + * Combines multiple Exit values into a single `Exit`. + * + * **When to use** + * + * Use to validate that all exits in a collection succeeded + * + * **Details** + * + * If all exits are successful, this returns a void success. If any exit is a + * failure, this returns a single failure with all error causes combined. + * + * Iterates over the entire collection. Collects all failure causes, not just + * the first. + * + * **Example** (Combining exits) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoidAll([Exit.succeed(1), Exit.succeed(2), Exit.succeed(3)]) // => Exit.succeed(undefined) + * Exit.asVoidAll([Exit.succeed(1), Exit.fail("err"), Exit.succeed(3)]) // => Exit.fail("err") + * ``` + * + * @see {@link asVoid} to discard the value of a single Exit + * + * @category combinators + * @since 4.0.0 + */ +const asVoidAll = _internal_effect_js__rspack_import_1/* .exitAsVoidAll */.ely; +/** + * Returns the success value of an Exit as an Option. + * + * **When to use** + * + * Use when you need the success value from an `Exit` as an `Option` instead of + * pattern matching. + * + * **Details** + * + * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure. + * + * **Example** (Getting the success value) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.getSuccess(Exit.succeed(42)) // => Option.some(42) + * Exit.getSuccess(Exit.fail("err")) // => Option.none() + * ``` + * + * @see {@link getCause} to extract the Cause of a failure + * @see {@link filterValue} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_effect_js__rspack_import_1/* .exitGetSuccess */.kMI; +/** + * Returns the Cause of a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the failure `Cause` from an `Exit` as an `Option` instead + * of pattern matching. + * + * **Details** + * + * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success. + * + * **Example** (Getting the failure cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Option } from "effect" + * + * Exit.getCause(Exit.fail("err")) // => Option.some(Cause.fail("err")) + * Exit.getCause(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link getSuccess} to extract the success value + * @see {@link filterCause} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getCause = _internal_effect_js__rspack_import_1/* .exitGetCause */.Sv3; +/** + * Returns the first typed error from a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as an `Option`, + * ignoring successes and non-typed failures. + * + * **Details** + * + * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes, + * defect-only failures, and interrupt-only failures return `Option.none()`. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple typed errors, + * the rest are ignored. + * + * **Example** (Getting the first error) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.findErrorOption(Exit.fail("err")) // => Option.some("err") + * Exit.findErrorOption(Exit.die("bug")) // => Option.none() + * Exit.findErrorOption(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link findError} for filter-pipeline usage + * @see {@link getCause} to get the full Cause as an Option + * + * @category getters + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .exitFindErrorOption */.lgw; +//# sourceMappingURL=Exit.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + AT: failCause, + N6: isFailure, + Py: succeed, + oJ: isSuccess, + rI: void_ +}); + + +}, +"./node_modules/effect/dist/Fiber.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = "~effect/Fiber"; +const await_ = _internal_effect_js__rspack_import_0/* .fiberAwait */.zFM; + +/** + * Waits for all fibers in the provided iterable to complete and returns + * an array of their exit values. + * + * **When to use** + * + * Use when you need every fiber outcome as data, including failures and + * interruptions. + * + * **Details** + * + * The returned array is ordered like the input iterable. + * + * **Gotchas** + * + * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you + * want the first failed fiber to fail the returned Effect. + * + * **Example** (Awaiting multiple fiber exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.succeed(1)) + * const fiber2 = yield* Effect.forkChild(Effect.succeed(2)) + * return yield* Fiber.awaitAll([fiber1, fiber2]) + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [Exit.succeed(1), Exit.succeed(2)] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const awaitAll = _internal_effect_js__rspack_import_0/* .fiberAwaitAll */.C6p; +/** + * 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 + * + * @category combinators + * @since 2.0.0 + */ +const join = _internal_effect_js__rspack_import_0/* .fiberJoin */.D7p; +/** + * Waits for all fibers to succeed and returns their values in input order. + * + * **When to use** + * + * Use when you need every fiber to succeed and want the successful values + * rather than the `Exit` values. + * + * **Details** + * + * If any fiber fails, the returned `Effect` fails with that fiber's cause and + * stops waiting for additional results. This does not interrupt the remaining + * fibers. + * + * **Gotchas** + * + * A failure stops waiting, but it does not interrupt any other fibers. Use + * {@link interruptAll} separately when remaining fibers should be stopped. + * + * @see {@link awaitAll} for collecting every fiber outcome as an Exit + * + * @category combinators + * @since 2.0.0 + */ +const joinAll = _internal_effect_js__rspack_import_0/* .fiberJoinAll */.INJ; +/** + * Interrupts a fiber, causing it to stop executing and clean up any + * acquired resources. + * + * **When to use** + * + * Use when you need to cancel a forked fiber and wait for its cleanup to + * complete. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * Interruption is cooperative. A fiber can continue running while it is inside + * uninterruptible work or finalizers. + * + * **Example** (Interrupting a fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild( + * Effect.delay("1 second")(Effect.succeed(42)) + * ) + * yield* Fiber.interrupt(fiber) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAs} for specifying the interrupting fiber ID + * @see {@link await_ await} for observing the interrupted fiber's Exit + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_0/* .fiberInterrupt */.mKq; +/** + * Interrupts a fiber with a specific fiber ID as the interruptor. This allows + * tracking which fiber initiated the interruption. + * + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const targetFiber = yield* Effect.forkChild( + * Effect.delay("5 seconds")(Effect.succeed("task completed")) + * ) + * + * // Interrupt the fiber, specifying fiber ID 123 as the interruptor + * yield* Fiber.interruptAs(targetFiber, 123) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interrupt} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAs */.eGS; +/** + * Interrupts all fibers in the provided iterable, causing them to stop executing + * and clean up any acquired resources. + * + * **When to use** + * + * Use when you need to cancel several forked fibers and wait for their cleanup + * to complete. + * + * **Details** + * + * The current fiber is recorded as the interruptor. The returned Effect + * completes only after all interrupted fibers have completed. + * + * **Gotchas** + * + * Interruption is cooperative for each fiber. The returned Effect can wait for + * uninterruptible work and finalizers in any interrupted fiber. + * + * **Example** (Interrupting multiple fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.never) + * const fiber2 = yield* Effect.forkChild(Effect.never) + * const fiber3 = yield* Effect.forkChild(Effect.never) + * yield* Fiber.interruptAll([fiber1, fiber2, fiber3]) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAllAs} for specifying the interrupting fiber ID + * + * @category interruption + * @since 2.0.0 + */ +const interruptAll = _internal_effect_js__rspack_import_0/* .fiberInterruptAll */.DKo; +/** + * Interrupts all fibers in the provided iterable using the specified fiber ID as the + * interrupting fiber. This allows you to control which fiber is considered the source + * of the interruption, which can be useful for debugging and tracing. + * + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a controlling fiber + * const controllerFiber = yield* Effect.forkChild(Effect.succeed("controller")) + * + * const worker1 = yield* Effect.forkChild(Effect.never) + * const worker2 = yield* Effect.forkChild(Effect.never) + * + * yield* Fiber.interruptAllAs([worker1, worker2], controllerFiber.id) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAll} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAllAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAllAs */.$MQ; +/** + * Checks whether a value is a Fiber. This is a type guard that can be used to + * determine if an unknown value is a Fiber instance. + * + * **When to use** + * + * Use when checking values at boundaries where an unknown value may be a + * runtime fiber. + * + * **Details** + * + * The check looks for the internal Fiber type ID marker and does not inspect + * the fiber's current state. + * + * **Example** (Checking for fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a fiber + * const fiber = yield* Effect.forkChild(Effect.succeed(42)) + * + * // Test if values are fibers + * return [Fiber.isFiber(fiber), Fiber.isFiber("hello"), Fiber.isFiber(42), Fiber.isFiber(null)] + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [true, false, false, false] + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isFiber = u => hasProperty(u, effect.FiberTypeId); +/** + * Returns the current fiber if called from within a fiber context, + * otherwise returns `undefined`. + * + * **When to use** + * + * Use when you need low-level runtime integrations that need access to the currently + * executing fiber. + * + * **Gotchas** + * + * This is a synchronous accessor, not an Effect. It returns `undefined` outside + * an active fiber runtime context. + * + * **Example** (Getting the current fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const current = Fiber.getCurrent() + * return current !== undefined + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => true + * ``` + * + * @category getters + * @since 4.0.0 + */ +const getCurrent = _internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku; +/** + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. + * + * **Details** + * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion + * + * @category resource management + * @since 4.0.0 + */ +const runIn = _internal_effect_js__rspack_import_0/* .fiberRunIn */.vTQ; +//# sourceMappingURL=Fiber.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + G: interrupt, + VO: runIn, + fj: join +}); + + +}, +"./node_modules/effect/dist/Filter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Result.js"); + + + + + +// ------------------------------------------------------------------------------------- +// Constructors +// ------------------------------------------------------------------------------------- +/** + * Creates a Filter from a function that returns either a `pass` or `fail` value. + * + * **Details** + * + * This is the primary constructor for creating custom filters. The function + * should return either `Result.succeed(value)` or `Result.fail(value)`. + * + * **Example** (Creating custom filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create a filter for positive numbers + * const positiveFilter = Filter.make((n: number) => n > 0 ? Result.succeed(n) : Result.fail(n)) + * + * // Create a filter that transforms strings to uppercase + * const uppercaseFilter = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * positiveFilter(1) // => Result.succeed(1) + * uppercaseFilter("ok") // => Result.succeed("OK") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = f => f; +/** + * Creates an effectful Filter from a function that returns an Effect. + * + * **Details** + * + * This constructor is used when the filtering operation needs to perform + * effectful computations, such as async operations, error handling, or accessing + * services from the environment. + * + * **Example** (Creating effectful filters) + * + * ```ts import.meta.vitest + * import { Effect, Filter, Result } from "effect" + * + * // Create an effectful filter that validates async + * const asyncValidate = Filter.makeEffect((id: string) => + * Effect.gen(function*() { + * const isValid = yield* Effect.succeed(id.length > 0) + * return isValid ? Result.succeed(id) : Result.fail(id) + * }) + * ) + * + * await Effect.runPromise(asyncValidate("id")) // => Result.succeed("id") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeEffect = f => f; +/** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping + * @since 4.0.0 + */ +const mapFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => input => Result.mapError(self(input), f)))); +const try_ = f => input => { + try { + return Result.succeed(f(input)); + } catch { + return Result.fail(input); + } +}; + +/** + * Creates a Filter from a predicate or refinement function. + * + * **Details** + * + * This is a convenient way to create filters from boolean-returning functions. + * When the predicate returns true, the input value is passed through unchanged. + * When it returns false, the `fail` type is returned. + * + * **Example** (Creating filters from predicates) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create filter from predicate + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const nonEmptyStrings = Filter.fromPredicate((s: string) => s.length > 0) + * + * // Type refinement + * const isString = Filter.fromPredicate((x: unknown): x is string => + * typeof x === "string" + * ) + * positiveNumbers(1) // => Result.succeed(1) + * nonEmptyStrings("") // => Result.fail("") + * isString("ok") // => Result.succeed("ok") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicate = predicate => input => predicate(input) ? _Result_js__rspack_import_0/* .succeed */.Py(input) : _Result_js__rspack_import_0/* .fail */.fJ(input); +/** + * Creates a `Filter` from a function that returns an `Option`; `Some(value)` + * passes with `value`, and `None` fails with the original input. + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicateOption = predicate => input => { + const o = predicate(input); + return o._tag === "None" ? Result.fail(input) : Result.succeed(o.value); +}; +/** + * Converts a Filter into a predicate function. + * + * **When to use** + * + * Use to reuse a `Filter` with APIs that accept only boolean predicates when + * the pass and fail payloads are not needed. + * + * @see {@link toOption} for keeping passed values and discarding failure values + * @see {@link toResult} for preserving both pass and failure values + * + * @category converting + * @since 4.0.0 + */ +const toPredicate = self => input => !Result.isFailure(self(input)); +/** + * A predefined filter that only passes through string values. + * + * **Example** (Filtering strings) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.string("hello") // => Result.succeed("hello") + * Filter.string(42) // => Result.fail(42) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const string = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isString */.Kg); +/** + * Creates a `Filter` that passes only values strictly equal to the specified + * value using JavaScript `===` comparison. + * + * **When to use** + * + * Use when you need a `Filter` that accepts only the exact primitive value or + * object reference using JavaScript strict equality in a `Filter` / `Result` + * pipeline. + * + * **Gotchas** + * + * `NaN` never passes, even when the expected value is `NaN`, and objects pass + * only when they are the same reference. + * + * @see {@link equals} for structural equality when distinct values with equal + * contents should pass + * + * @category constructors + * @since 4.0.0 + */ +const equalsStrict = value => u => u === value ? Result.succeed(value) : Result.fail(u); +/** + * Creates a `Filter` that passes inputs whose `has(key)` method returns + * `true` for the specified key. + * + * **When to use** + * + * Use to keep inputs that expose a `has` method, such as `Set` or `Map`, when + * they contain a required key. + * + * @see {@link fromPredicate} for custom predicate filters or inputs without a + * `has` method + * @see {@link Predicate.hasProperty} for guarding property presence instead of + * calling an input's `has` method + * + * @category constructors + * @since 4.0.0 + */ +const has = key => input => input.has(key) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that only passes instances of the given constructor. + * + * **When to use** + * + * Use to narrow unknown input to values created by a specific JavaScript + * constructor while keeping the result in the `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when the input satisfies `instanceof constructor`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This uses JavaScript `instanceof` semantics, including prototype-chain and + * realm behavior. + * + * @see {@link fromPredicate} for custom predicate-based narrowing + * + * @category constructors + * @since 4.0.0 + */ +const instanceOf = constructor => u => u instanceof constructor ? Result.succeed(u) : Result.fail(u); +/** + * A predefined filter that only passes through number values. + * + * **Example** (Filtering numbers) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.number(42) // => Result.succeed(42) + * Filter.number("42") // => Result.fail("42") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const number = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isNumber */.Et); +/** + * A predefined filter that only passes through boolean values. + * + * **When to use** + * + * Use when accepting an unknown input only if it is already a boolean and you + * want a `Filter` result rather than a plain predicate result. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBoolean)`, so `true` and `false` + * succeed and non-booleans fail with the original input. + * + * @see {@link Predicate.isBoolean} for the underlying guard + * @see {@link fromPredicate} for custom predicate-based filters + * + * @category constructors + * @since 4.0.0 + */ +const boolean = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBoolean */.Lm); +/** + * A predefined filter that only passes through `bigint` primitive values. + * + * **When to use** + * + * Use to keep primitive big integer values from unknown input while staying in + * the composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBigInt)`, so values where + * `typeof input === "bigint"` succeed and all other inputs fail with the + * original input. + * + * **Gotchas** + * + * This filter does not coerce numbers or strings; `1n` passes while `1` fails. + * + * @see {@link number} for JavaScript `number` values + * @see {@link Predicate.isBigInt} for the underlying guard + * + * @category constructors + * @since 4.0.0 + */ +const bigint = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBigInt */.sI); +/** + * A predefined filter that only passes through Symbol values. + * + * @category constructors + * @since 4.0.0 + */ +const symbol = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isSymbol */.Bm); +/** + * A predefined filter that only passes through Date objects. + * + * **When to use** + * + * Use when you need to narrow unknown input to JavaScript `Date` instances with + * a reusable `Filter`. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isDate)`, so passing values return + * `Result.succeed(input)` and failing values return `Result.fail(input)`. + * + * **Gotchas** + * + * The check uses `instanceof Date`, so invalid `Date` objects still pass; the + * filter does not validate the timestamp. + * + * @see {@link Predicate.isDate} for the underlying guard + * @see {@link instanceOf} for constructor-based filtering + * @see {@link fromPredicate} for custom date checks + * + * @category constructors + * @since 4.0.0 + */ +const date = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isDate */.$P); +/** + * Creates a filter that checks if an input is tagged with a specific tag. + * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors + * @since 4.0.0 + */ +const tagged = function () { + return arguments.length === 0 ? taggedImpl : taggedImpl(arguments[0]); +}; +const taggedImpl = tag => input => Predicate.isTagged(input, tag) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that extracts a reason from a tagged error. + * + * @category constructors + * @since 4.0.0 + */ +const reason = function () { + return arguments.length === 0 ? reasonImpl : reasonImpl(arguments[0], arguments[1]); +}; +const reasonImpl = (tag, reasonTag) => input => { + if (Predicate.isTagged(input, tag) && Predicate.hasProperty(input, "reason") && Predicate.isTagged(input.reason, reasonTag)) { + return Result.succeed(input.reason); + } + return Result.fail(input); +}; +/** + * Creates a filter that only passes values equal to the specified value using structural equality. + * + * **When to use** + * + * Use to accept inputs that are structurally equal to a known expected value + * while staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Delegates to `Equal.equals`. On success it returns `Result.succeed(value)`; + * on failure it returns `Result.fail(input)`. + * + * @see {@link equalsStrict} for JavaScript `===` matching instead of structural + * equality + * @see {@link Equal.equals} for the underlying structural equality semantics + * + * @category constructors + * @since 4.0.0 + */ +const equals = value => u => Equal.equals(u, value) ? Result.succeed(value) : Result.fail(u); +/** + * Combines two filters with logical OR semantics. + * + * @category combinators + * @since 4.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => input => { + const selfResult = self(input); + return Result.isSuccess(selfResult) ? selfResult : that(input); +}))); +/** + * Combines two filters and applies a function to their results. + * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * + * Both filters must succeed (not return `fail`) for the combination to succeed. + * If both filters pass, their outputs are combined using the provided function. + * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators + * @since 4.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => input => { + const leftResult = left(input); + if (Result.isFailure(leftResult)) return leftResult; + const rightResult = right(input); + if (Result.isFailure(rightResult)) return rightResult; + return Result.succeed(f(leftResult.success, rightResult.success)); +}))); +/** + * Combines two filters into a tuple of their results. + * + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) + * positiveAndEven(2) // => Result.succeed([2, 2]) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (leftResult, rightResult) => [leftResult, rightResult])))); +/** + * Combines two filters but only returns the result of the left filter. + * + * **Example** (Keeping the left filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) + * positiveEven(2) // => Result.succeed(2) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, leftResult => leftResult)))); +/** + * Combines two filters but only returns the result of the right filter. + * + * **Example** (Keeping the right filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const doubleNumbers = Filter.make((n: number) => + * n > 0 ? Result.succeed(n * 2) : Result.fail(n) + * ) + * + * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) + * positiveDoubled(2) // => Result.succeed(4) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (_, rightResult) => rightResult)))); +/** + * Composes two filters sequentially, feeding the output of the first into the second. + * + * **Example** (Composing filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const stringFilter = Filter.string + * const nonEmptyUpper = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * + * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) + * stringToUpper("hello") // => Result.succeed("HELLO") + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => input => { + const leftOut = left(input); + if (Result.isFailure(leftOut)) return leftOut; + return right(leftOut.success); +}))); +/** + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. + * + * **Details** + * + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. + * + * @category combinators + * @since 4.0.0 + */ +const composePassthrough = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (left, right) => input => { + const leftOut = left(input); + if (_Result_js__rspack_import_0/* .isFailure */.N6(leftOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + const rightOut = right(leftOut.success); + if (_Result_js__rspack_import_0/* .isFailure */.N6(rightOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + return rightOut; +}); +/** + * Converts a `Filter` into a function that returns `Some` for passed values + * and `None` for filtered-out values. + * + * **When to use** + * + * Use when adapting a `Filter` to `Option`-based code where passed values + * become `Some` and filtered-out inputs become `None`. + * + * @see {@link toResult} for keeping the filter failure value + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toOption = self => input => { + const result = self(input); + return _Result_js__rspack_import_0/* .isFailure */.N6(result) ? _Option_js__rspack_import_3.none() : _Option_js__rspack_import_3.some(result.success); +}; +/** + * Converts a `Filter` into a function that returns the underlying + * `Result.Result` for each input. + * + * **When to use** + * + * Use to adapt a `Filter` to APIs that expect a plain function returning + * `Result`, while preserving both the pass value and the failure value. + * + * @see {@link toOption} for keeping only passed values + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toResult = self => input => { + const result = self(input); + return Result.isFailure(result) ? Result.fail(result.failure) : Result.succeed(result.success); +}; +//# sourceMappingURL=Filter.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Bh: composePassthrough, + zL: toOption +}); + + +}, +"./node_modules/effect/dist/Formatter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.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. + * + * @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. + * - 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} + * @category formatting + * @since 2.0.0 + */ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = 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) { + 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 (_Redactable_js__rspack_import_0/* .symbolRedactable */.uC in v) { + output = recur((0,_Redactable_js__rspack_import_0/* .getRedacted */.f6)(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 && _Predicate_js__rspack_import_1/* .hasProperty */.i5(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 ? `${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(v[k], d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map(k => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(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 an array of property keys as a bracket-notation path string. + * + * @internal + */ +function formatPath(path) { + return path.map(key => `[${formatPropertyKey(key)}]`).join(""); +} +/** + * 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]"; + } +} +/** + * Stringifies a value to JSON safely, silently dropping circular references. + * + * **When to use** + * + * Use when you need valid JSON output, unlike `format`, and the input may + * contain circular references that should be silently omitted rather than + * throwing a `TypeError`. + * + * **Details** + * + * Uses `JSON.stringify` internally with a replacer that tracks the current + * object ancestry. Circular references are replaced with `undefined`, which + * omits them from object output. `Redactable` values are automatically redacted + * before serialization. `BigInt` values are stringified with an `n` suffix. + * Values not supported by JSON otherwise follow standard `JSON.stringify` + * behavior. The `space` parameter controls indentation and defaults to `0`. + * + * **Gotchas** + * + * When the root input is `undefined`, a symbol, or a function, `formatJson` + * returns `"null"` instead of the `undefined` returned by `JSON.stringify`. + * Nested values retain standard `JSON.stringify` behavior. + * + * **Example** (Formatting compact JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * Formatter.formatJson({ name: "Alice", age: 30 }) // => "{\"name\":\"Alice\",\"age\":30}" + * ``` + * + * **Example** (Handling circular references) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const obj: any = { name: "test" } + * obj.self = obj + * Formatter.formatJson(obj) // => "{\"name\":\"test\"}" + * ``` + * + * **Example** (Pretty-printed JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const output = Formatter.formatJson({ name: "Alice", age: 30 }, { space: 2 }) + * output // => "{\n \"name\": \"Alice\",\n \"age\": 30\n}" + * ``` + * + * @see {@link format} + * @see {@link Formatter} + * @category serialization + * @since 4.0.0 + */ +function formatJson(input, options) { + const ancestors = []; + return JSON.stringify(input, function (key, value) { + const original = Object.getOwnPropertyDescriptor(this, key)?.value; + const redacted = _Predicate_js__rspack_import_1/* .hasProperty */.i5(original, _Redactable_js__rspack_import_0/* .symbolRedactable */.uC) ? (0,_Redactable_js__rspack_import_0/* .redact */.E$)(original) : (0,_Redactable_js__rspack_import_0/* .redact */.E$)(value); + if (typeof redacted === "bigint") { + return format(redacted); + } + if (typeof redacted !== "object" || redacted === null) { + return redacted; + } + while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) { + ancestors.pop(); + } + if (ancestors.includes(redacted)) { + return undefined; // circular reference + } + ancestors.push(redacted); + return redacted; + }, options?.space) ?? "null"; +} +//# sourceMappingURL=Formatter.js.map +__webpack_require__.d(__webpack_exports__, { + GP: () => (format), + IB: () => (formatJson) +}); + + +}, +"./node_modules/effect/dist/Function.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { + +/** + * 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 + * ``` + * + * @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) { + // @ts-expect-error + return body.apply(this, arguments); + } + const args = arguments; + return function (self) { + return body(self, ...args); + }; + }; + } +}; +/** + * Applies a function to a given value. + * + * **When to use** + * + * Use to pass a fixed value into a unary function, especially when the function + * is the value flowing through `pipe`. + * + * **Details** + * + * `apply(a)(f)` is equivalent to `f(a)`. + * + * **Example** (Applying an argument to a function) + * + * ```ts import.meta.vitest + * import { Function, pipe, String } from "effect" + * + * pipe(String.length, Function.apply("hello")) // => 5 + * ``` + * + * @see {@link pipe} for building left-to-right pipelines + * + * @category combinators + * @since 2.0.0 + */ +const apply = a => self => self(a); +/** + * 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 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const identity = a => a; +/** + * Ensures that the type of an expression matches some type, + * without changing the resulting type of that expression. + * + * **When to use** + * + * Use to check assignability while preserving the expression's precise inferred + * type. + * + * **Example** (Checking an expression against a type) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const test1 = Function.satisfies()(5 as const) // => 5 + * // ^? const test: 5 + * // @ts-expect-error + * const test2 = Function.satisfies()(5) + * // ^? Argument of type 'number' is not assignable to parameter of type 'string' + * ``` + * + * @see {@link cast} for changing only the static TypeScript type + * + * @category utility types + * @since 2.0.0 + */ +const satisfies = () => b => b; +/** + * Returns the input value with a different static type. + * + * **When to use** + * + * Use when you need an explicit type-level cast and accept that the value is + * returned unchanged at runtime. + * + * **Gotchas** + * + * This is a type-level cast only; it performs no runtime validation or + * conversion. + * + * @see {@link satisfies} for checking assignability without changing the resulting type + * + * @category utility types + * @since 4.0.0 + */ +const cast = (/* unused pure expression or super */ null && (identity)); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constTrue = /*#__PURE__*/constant(true); +/** + * Returns `false` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `false` on every invocation. + * + * **Example** (Returning false from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constFalse() // => false + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constFalse = /*#__PURE__*/constant(false); +/** + * Returns `null` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `null` on every invocation. + * + * **Example** (Returning null from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constNull() // => null + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constNull = /*#__PURE__*/constant(null); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constUndefined = /*#__PURE__*/constant(undefined); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constVoid = constUndefined; +/** + * Reverses the order of arguments for a curried function. + * + * **When to use** + * + * Use to adapt a curried function when its argument groups need to be supplied + * in the opposite order. + * + * **Example** (Flipping curried arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const f = (a: number) => (b: string) => a - b.length + * + * Function.flip(f)("aaa")(2) // => -1 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const flip = f => (...b) => (...a) => f(...a)(...b); +/** + * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. + * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. + * + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const increment = (n: number) => n + 1 + * const square = (n: number) => n * n + * + * Function.compose(increment, square)(2) // => 9 + * ``` + * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => bc(ab(a))))); +/** + * Marks an impossible branch by accepting a `never` value and returning any + * type. + * + * **When to use** + * + * Use when you need a return value in a branch that exhaustive checks prove + * cannot be reached. + * + * **Gotchas** + * + * Calling `absurd` throws, because a value of type `never` should be + * impossible at runtime. + * + * **Example** (Handling impossible values) + * + * ```ts import.meta.vitest + * import { absurd } from "effect" + * + * const handleNever = (value: never) => { + * return absurd(value) // This will throw an error if called + * } + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const absurd = _ => { + throw new Error("Called `absurd` function which should be uncallable"); +}; +/** + * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. + * + * **When to use** + * + * Use to adapt a multi-argument function so it accepts one tuple argument. + * + * **Example** (Converting arguments to a tuple) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const sumTupled = Function.tupled((x: number, y: number): number => x + y) + * + * sumTupled([1, 2]) // => 3 + * ``` + * + * @see {@link untupled} for adapting a tuple-argument function back to multiple arguments + * + * @category combinators + * @since 2.0.0 + */ +const tupled = f => a => f(...a); +/** + * Converts a tupled function back to an uncurried function. + * + * **When to use** + * + * Use to adapt a tuple-argument function so it accepts multiple arguments. + * + * **Example** (Converting a tuple to arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const getFirst = Function.untupled((tuple: [A, B]): A => tuple[0]) + * + * getFirst(1, 2) // => 1 + * ``` + * + * @see {@link tupled} for adapting a multi-argument function to one tuple argument + * + * @category combinators + * @since 2.0.0 + */ +const untupled = f => (...a) => f(a); +function pipe(a, ...args) { + return pipeArguments(a, args); +} +function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) { + switch (arguments.length) { + case 1: + return ab; + case 2: + return function () { + return bc(ab.apply(this, arguments)); + }; + case 3: + return function () { + return cd(bc(ab.apply(this, arguments))); + }; + case 4: + return function () { + return de(cd(bc(ab.apply(this, arguments)))); + }; + case 5: + return function () { + return ef(de(cd(bc(ab.apply(this, arguments))))); + }; + case 6: + return function () { + return fg(ef(de(cd(bc(ab.apply(this, arguments)))))); + }; + case 7: + return function () { + return gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))); + }; + case 8: + return function () { + return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))); + }; + case 9: + return function () { + return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))); + }; + } + return; +} +/** + * Creates a compile-time placeholder for a value of any type. + * + * **When to use** + * + * Use as a temporary typed placeholder while developing incomplete code. + * + * **Gotchas** + * + * `hole` is intended for temporary development use. If the placeholder is + * evaluated at runtime, it throws. + * + * **Example** (Creating a development placeholder) + * + * ```ts import.meta.vitest + * import { hole } from "effect" + * + * // Intentionally not called: `hole` throws if the placeholder is evaluated. + * const buildUser = (id: number): { readonly id: number; readonly name: string } => ({ + * id, + * name: hole() + * }) + * + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const hole = /*#__PURE__*/(/* unused pure expression or super */ null && (cast(absurd))); +/** + * Returns the second argument and discards the first. The SK combinator is + * a fundamental combinator in the lambda calculus and the SKI combinator + * calculus. + * + * **When to use** + * + * Use to discard the first argument and return the second argument. + * + * **Example** (Discarding the first argument) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.SK(0, "hello") // => "hello" + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const SK = (_, b) => b; +/** + * Creates a memoized function whose input is an object, caching results by + * object identity. + * + * **When to use** + * + * Use to reuse the result of a synchronous computation whose output is stable + * for a given object reference. + * + * **Details** + * + * Each memoized wrapper owns a private `WeakMap` keyed by object identity. + * + * **Gotchas** + * + * `undefined` is reserved to represent a cache miss and is therefore not + * supported as a return value. + * + * Structurally equal objects do not share cache entries. If the same object is + * mutated after its first call, later calls still return the cached result for + * that reference. + * + * @category caching + * @since 4.0.0 + */ +function memoize(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + return result; + }; +} +/** + * Creates a memoized idempotent object transformation that caches both inputs + * and their outputs by object identity. + * + * **When to use** + * + * Use when an object transformation is idempotent and its output can be safely + * reused as a fixed point. + * + * **Details** + * + * After computing an input, the returned function caches both the input and + * the output. Calling it with either reference returns the output without + * invoking the supplied function again. + * + * **Gotchas** + * + * The returned function treats each computed output as a fixed point. If + * applying the supplied function to an output would produce an observably + * different value, this memoization changes that behavior. + * + * @see {@link memoize} for memoizing functions without an idempotence requirement + * @category caching + * @since 4.0.0 + */ +function memoizeIdempotent(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + cache.set(result, result); + return result; + }; +} +//# sourceMappingURL=Function.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + D_: identity, + MN: constUndefined, + XR: constNull, + XY: dual, + Yi: constVoid, + dY: constant, + f4: constFalse, + ue: constTrue +}); + + +}, +"./node_modules/effect/dist/Hash.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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. + * + * @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 + * + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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 + * ``` + * + * @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 "boolean": + return string(String(self)); + case "symbol": + return string(String(self)); + case "string": + return string(self); + case "undefined": + return string("undefined"); + case "function": + case "object": + { + if (self === null) { + return string("null"); + } 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 (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self)) { + return random(self); + } + if (hashCache.has(self)) { + return hashCache.get(self); + } + const h = withVisitedTracking(self, () => { + if (isHash(self)) { + return self[symbol](); + } else if (typeof self === "function") { + return random(self); + } else if (self instanceof DataView) { + return array(new Uint8Array(self.buffer, self.byteOffset, self.byteLength)); + } else if (Array.isArray(self) || ArrayBuffer.isView(self)) { + return array(self); + } else if (self instanceof Map) { + return hashMap(self); + } else if (self instanceof Set) { + return hashSet(self); + } + return structure(self); + }); + hashCache.set(self, h); + return h; + } + } + default: + throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`); + } +}; +/** + * 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" + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const random = self => { + if (!randomHashCache.has(self)) { + randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))); + } + return randomHashCache.get(self); +}; +/** + * 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 both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **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 + * + * @category hashing + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => self * 53 ^ b); +/** + * 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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const optimize = n => n & 0xbfffffff | n >>> 1 & 0x40000000; +/** + * 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 the Hash symbol property, + * indicating that it can provide its own hash value implementation. + * + * **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 + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isHash = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Computes a hash value for a number. + * + * **When to use** + * + * Use to hash a JavaScript number with Effect's numeric hash semantics. + * + * **Details** + * + * This function creates a hash value for numeric inputs, handling special cases + * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution + * of hash values across different numeric inputs. + * + * **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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const number = n => { + if (n !== n) { + return string("NaN"); + } + if (n === Infinity) { + return string("Infinity"); + } + if (n === -Infinity) { + return string("-Infinity"); + } + let h = n | 0; + if (h !== n) { + h ^= n * 0xffffffff; + } + while (n > 0xffffffff) { + h ^= n /= 0xffffffff; + } + return optimize(h); +}; +/** + * 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 + * ``` + * + * @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 // => -590673747 + * hash2 // => 284850673 + * + * const person2 = { name: "John", age: 30, city: "Boston" } + * const hash3 = Hash.structureKeys(person2, ["name", "age"]) + * hash1 === hash3 // => true + * ``` + * + * @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) // => -590673747 + * Hash.structure(obj2) // => -590160631 + * Hash.structure(obj3) // => -590673747 + * Hash.structure(obj1) === Hash.structure(obj3) // => true + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const structure = o => structureKeys(o, (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(o)); +const iterableWith = (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** + * + * The implementation folds element hashes from the seed `6151` with XOR and + * then optimizes the final hash. + * + * **Gotchas** + * + * A hash is not an equality proof. Because this implementation uses XOR, + * reordered inputs can produce the same 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) // => 6151 + * Hash.array(arr2) // => 6151 + * Hash.array(arr3) // => 6151 + * Hash.array(arr1) === Hash.array(arr2) // => true + * Hash.array(arr1) === Hash.array(arr3) // => true + * ``` + * + * @see {@link hash} for the general-purpose hash dispatcher + * + * @category hashing + * @since 2.0.0 + */ +const array = /*#__PURE__*/iterableWith(6151, hash); +const hashMap = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const hashSet = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Set"), hash); +const randomHashCache = /*#__PURE__*/new WeakMap(); +const hashCache = /*#__PURE__*/new WeakMap(); +const visitedObjects = /*#__PURE__*/new WeakSet(); +function withVisitedTracking(obj, fn) { + if (visitedObjects.has(obj)) { + return string("[Circular]"); + } + visitedObjects.add(obj); + const result = fn(); + visitedObjects.delete(obj); + return result; +} +//# sourceMappingURL=Hash.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + HR: symbol, + QK: structure, + YO: array, + Yj: string, + ai: number, + kg: combine, + tW: hash, + uN: structureKeys, + yT: random +}); + + +}, +"./node_modules/effect/dist/Inspectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/** + * Controls how values appear in logs and debugging output. + * + * Effect data types use `Inspectable` to provide stable string, JSON, and + * Node.js inspection output. This keeps custom values readable in logs, REPLs, + * test failures, and diagnostics. This module defines the Node inspect symbol, + * the `Inspectable` interface, safe conversion helpers, and shared prototype or + * class implementations for custom values. + * + * @since 2.0.0 + */ + + + +/** + * 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)" + * ``` + * + * @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 + * + * @category converting + * @since 4.0.0 + */ +const toJson = input => { + try { + input = (0,_Redactable_js__rspack_import_0/* .redact */.E$)(input); + if (_Predicate_js__rspack_import_1/* .hasProperty */.i5(input, "toJSON") && _Predicate_js__rspack_import_1/* .isFunction */.Tn(input["toJSON"]) && input["toJSON"].length === 0) { + return input.toJSON(); + } else if (Array.isArray(input)) { + return input.map(toJson); + } + return input; + } catch { + return "[toJSON threw]"; + } +}; +/** + * Converts an unknown value to a string for diagnostics. + * + * **When to use** + * + * Use to produce a diagnostic string from a value whose runtime type is unknown. + * + * **Details** + * + * Strings are returned unchanged. Objects are formatted as JSON using the + * provided whitespace setting when possible, and values that cannot be + * formatted are converted with `String`. + * + * @category converting + * @since 2.0.0 + */ +const toStringUnknown = (u, whitespace = 2) => { + if (typeof u === "string") { + return u; + } + try { + return typeof u === "object" ? (0,_Formatter_js__rspack_import_2/* .formatJson */.IB)(u, { + space: whitespace + }) : (0,_Formatter_js__rspack_import_2/* .format */.GP)(u, { + space: whitespace + }); + } catch { + return String(u); + } +}; +/** + * A base prototype object that implements the {@link Inspectable} interface. + * + * **When to use** + * + * Use as a prototype for plain objects that should share standard inspectable behavior. + * + * **Details** + * + * This object provides default implementations for the {@link Inspectable} methods. + * It can be used as a prototype for objects that want to be inspectable, + * or as a mixin to add inspection capabilities to existing objects. + * + * **Example** (Using the base inspectable prototype) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * // Use as prototype + * const myObject = Object.create(Inspectable.BaseProto) + * myObject.name = "example" + * myObject.value = 42 + * + * myObject.toString() // => "\"[toJSON threw]\"" + * + * // Or extend in a constructor + * function MyClass(this: any, name: string) { + * this.name = name + * } + * MyClass.prototype = Object.create(Inspectable.BaseProto) + * MyClass.prototype.constructor = MyClass + * ``` + * + * @category prototypes + * @since 2.0.0 + */ +const BaseProto = (/* unused pure expression or super */ null && ({ + toJSON() { + return toJson(this); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + }, + toString() { + return format(this.toJSON()); + } +})); +/** + * Provides an abstract base class that implements the Inspectable interface. + * + * **When to use** + * + * Use as a base class for inspectable objects that define their own JSON representation. + * + * **Details** + * + * This class provides a convenient way to create inspectable objects by extending it. + * Subclasses only need to implement the `toJSON()` method, and they automatically + * get proper `toString()` and Node.js inspection support. + * + * **Example** (Extending the inspectable base class) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * class User extends Inspectable.Class { + * constructor( + * public readonly id: number, + * public readonly name: string, + * public readonly email: string + * ) { + * super() + * } + * + * toJSON() { + * return { + * _tag: "User", + * id: this.id, + * name: this.name, + * email: this.email + * } + * } + * } + * + * const user = new User(1, "Alice", "alice@example.com") + * user.toString() // => "{\"_tag\":\"User\",\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\"}" + * user[Inspectable.NodeInspectSymbol]() // => { _tag: "User", id: 1, name: "Alice", email: "alice@example.com" } + * ``` + * + * @category models + * @since 2.0.0 + */ +class Class { + /** + * Node.js custom inspection method. + * + * **When to use** + * + * Use to expose the class JSON representation to Node.js inspection. + * + * @since 2.0.0 + */ + [NodeInspectSymbol]() { + return this.toJSON(); + } + /** + * Returns a formatted string representation of this object. + * + * **When to use** + * + * Use to format the class JSON representation as a string. + * + * @since 2.0.0 + */ + toString() { + return format(this.toJSON()); + } +} +//# sourceMappingURL=Inspectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + FX: NodeInspectSymbol, + ZK: toStringUnknown, + aB: toJson +}); + + +}, +"./node_modules/effect/dist/Iterable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Works with JavaScript values that implement `[Symbol.iterator]`. + * + * Iterables include arrays, strings, generators, sets, and custom lazy + * sequences. The helpers in this module let code transform, search, group, and + * fold iterable values while preserving the input as an iterable instead of + * forcing an array first. + * + * @since 2.0.0 + */ + + + + + + + +/** + * Creates an iterable by applying a function to consecutive integers. + * + * **Details** + * + * The function is called with each index starting from `0`. If no length is + * specified, the iterable is infinite. This is useful for generating + * sequences, patterns, or any indexed data. + * + * **Example** (Generating values by index) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Generate first 5 even numbers + * const evens = Iterable.makeBy((n) => n * 2, { length: 5 }) + * Array.from(evens) // => [0, 2, 4, 6, 8] + * + * // Generate squares + * const squares = Iterable.makeBy((n) => n * n, { length: 4 }) + * Array.from(squares) // => [0, 1, 4, 9] + * + * // Infinite sequence (be careful when consuming!) + * const naturals = Iterable.makeBy((n) => n) + * const first10 = Iterable.take(naturals, 10) + * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeBy = (f, options) => { + const max = options?.length !== undefined ? Math.max(1, Math.floor(options.length)) : Infinity; + return { + [Symbol.iterator]() { + let i = 0; + return { + next() { + if (i < max) { + return { + value: f(i++), + done: false + }; + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns an iterable of integers starting at `start` and increasing by `1`. + * + * **Details** + * + * When `end` is provided and `start <= end`, both endpoints are included. When + * `end` is omitted, the iterable is unbounded. When `start > end`, the + * iterable contains only `start`. + * + * **Example** (Creating a range) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.range(1, 3)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const range = (start, end) => { + if (end === undefined) { + return makeBy(i => start + i); + } + return makeBy(i => start + i, { + length: start <= end ? end - start + 1 : 1 + }); +}; +/** + * Returns a `Iterable` containing a value repeated the specified number of times. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Repeating a value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.replicate("a", 3)) // => ["a", "a", "a"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const replicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (a, n) => makeBy(() => a, { + length: n +})))); +/** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value + * @category constructors + * @since 4.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => flatten(makeBy(() => self, { + length: n +}))))); +/** + * Repeats an iterable without an upper bound. + * + * **When to use** + * + * Use to cycle a reusable iterable without an upper bound when a downstream + * consumer controls how many values are taken. + * + * **Gotchas** + * + * The returned iterable is lazy and should usually be bounded with `take` or + * another terminating consumer before materializing it. + * + * @see {@link repeat} for repeating an iterable a specific number of times + * @see {@link take} for bounding the unbounded result before materializing it + * + * @category constructors + * @since 4.0.0 + */ +const forever = self => repeat(self, Infinity); +/** + * Takes a record and returns an Iterable of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Array.from(Iterable.fromRecord(x)) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = self => ({ + *[Symbol.iterator]() { + for (const key in self) { + if (Object.hasOwn(self, key)) { + yield [key, self[key]]; + } + } + } +}); +/** + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 3, 4] + * const withOne = Iterable.prepend(numbers, 1) + * Array.from(withOne) // => [1, 2, 3, 4] + * + * // Works with any iterable + * const letters = "abc" + * const withZ = Iterable.prepend(letters, "z") + * Array.from(withZ) // => ["z", "a", "b", "c"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => prependAll(self, [head])))); +/** + * Prepends the specified prefix iterable to the beginning of the specified iterable. + * + * **Example** (Prepending another iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.prependAll([1, 2], ["a", "b"])) // => ["a", "b", 1, 2] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => appendAll(that, self)))); +/** + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => appendAll(self, [last])))); +/** + * Concatenates two iterables, combining their elements. + * + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6] + * + * // Works with different iterable types + * const numbers = [1, 2] + * const letters = "abc" + * const mixed = Iterable.appendAll(numbers, letters) + * Array.from(mixed) // => [1, 2, "a", "b", "c"] + * + * // Lazy evaluation - only consumes what's needed + * const infinite = Iterable.range(1) + * const finite = [0, -1, -2] + * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2] + * ``` + * + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => ({ + [Symbol.iterator]() { + const iterA = self[Symbol.iterator](); + let doneA = false; + let iterB; + return { + next() { + if (!doneA) { + const r = iterA.next(); + if (r.done) { + doneA = true; + iterB = that[Symbol.iterator](); + return iterB.next(); + } + return r; + } + return iterB.next(); + } + }; + } +})))); +/** + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Running sum of numbers + * const numbers = [1, 2, 3, 4, 5] + * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n) + * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15] + * + * // Build strings progressively + * const letters = ["a", "b", "c"] + * const progressive = Iterable.scan(letters, "", (acc, letter) => acc + letter) + * Array.from(progressive) // => ["", "a", "ab", "abc"] + * + * // Track maximum values seen so far + * const values = [3, 1, 4, 1, 5, 9, 2] + * const runningMax = Iterable.scan(values, -Infinity, Math.max) + * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => ({ + [Symbol.iterator]() { + let acc = b; + let iterator; + function next() { + if (iterator === undefined) { + iterator = self[Symbol.iterator](); + return { + done: false, + value: acc + }; + } + const result = iterator.next(); + if (result.done) { + return result; + } + acc = f(acc, result.value); + return { + done: false, + value: acc + }; + } + return { + next + }; + } +})))); +/** + * Checks whether an `Iterable` is empty. + * + * **Example** (Checking for emptiness) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.isEmpty([]) // => true + * Iterable.isEmpty([1, 2, 3]) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmpty = self => { + const iterator = self[Symbol.iterator](); + return iterator.next().done === true; +}; +/** + * Returns the number of elements in a `Iterable`. + * + * **Example** (Counting iterable elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.size(numbers) // => 5 + * + * const empty = Iterable.empty() + * Iterable.size(empty) // => 0 + * + * // Works with any iterable + * const letters = "hello" + * Iterable.size(letters) // => 5 + * + * // Note: This consumes the entire iterable + * const range = Iterable.range(1, 100) + * Iterable.size(range) // => 100 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => { + const iterator = self[Symbol.iterator](); + let count = 0; + while (!iterator.next().done) { + count++; + } + return count; +}; +/** + * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.head(numbers) // => Option.some(1) + * + * const empty = Iterable.empty() + * Iterable.head(empty) // => Option.none() + * + * // Safe way to get first element + * const firstEven = Iterable.head( + * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0) + * ) + * firstEven // => Option.some(4) + * + * // Use with Option methods + * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2) + * doubled // => Option.some(10) + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + return result.done ? O.none() : O.some(result.value); +}; +/** + * Gets the first element of an `Iterable` without returning an `Option`. + * + * **When to use** + * + * Use when the `Iterable` is known to be non-empty and direct access to the + * first element is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the `Iterable` is empty. + * + * **Example** (Getting the first element unsafely) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.headUnsafe(numbers) // => 1 + * + * const letters = "hello" + * Iterable.headUnsafe(letters) // => "h" + * + * // Iterable.headUnsafe(Iterable.empty()) + * // throws Error: "headUnsafe: empty iterable" + * + * // Use only when you're certain the iterable is non-empty + * const nonEmpty = Iterable.range(1, 10) + * Iterable.headUnsafe(nonEmpty) // => 1 + * ``` + * + * @category getters + * @since 4.0.0 + */ +const headUnsafe = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + if (result.done) throw new Error("headUnsafe: empty iterable"); + return result.value; +}; +/** + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const firstThree = Iterable.take(numbers, 3) + * Array.from(firstThree) // => [1, 2, 3] + * + * // Taking more than available returns all elements + * const firstTen = Iterable.take(numbers, 10) + * Array.from(firstTen) // => [1, 2, 3, 4, 5] + * + * // Taking 0 or negative returns empty + * const none = Iterable.take(numbers, 0) + * Array.from(none) // => [] + * + * // Useful with infinite iterables + * const naturals = Iterable.range(1) + * const firstFive = Iterable.take(naturals, 5) + * Array.from(firstFive) // => [1, 2, 3, 4, 5] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + let i = 0; + const iterator = self[Symbol.iterator](); + return { + next() { + if (i < n) { + i++; + return iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 4, 6, 8, 3, 10, 12] + * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0) + * Array.from(evenPrefix) // => [2, 4, 6, 8] + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3) + * Array.from(firstThreeByIndex) // => ["a", "b", "c"] + * + * // Stops at first non-matching element + * const mixed = [1, 3, 5, 4, 7, 9] + * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1) + * Array.from(oddPrefix) // => [1, 3, 5] + * + * // Type refinement + * const values: Array = ["a", "b", "c", 1, "d"] + * const stringPrefix = Iterable.takeWhile( + * values, + * (x): x is string => typeof x === "string" + * ) + * Array.from(stringPrefix) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done || !predicate(result.value, i++)) { + return { + done: true, + value: undefined + }; + } + return result; + } + }; + } +})))); +/** + * Drops a max number of elements from the start of an `Iterable` + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const withoutFirstTwo = Iterable.drop(numbers, 2) + * Array.from(withoutFirstTwo) // => [3, 4, 5] + * + * // Dropping more than available returns empty + * const withoutFirstTen = Iterable.drop(numbers, 10) + * Array.from(withoutFirstTen) // => [] + * + * // Dropping 0 or negative returns all elements + * const all = Iterable.drop(numbers, 0) + * Array.from(all) // => [1, 2, 3, 4, 5] + * + * // Combine with take for slicing + * const slice = Iterable.take(Iterable.drop(numbers, 1), 3) + * Array.from(slice) // => [2, 3, 4] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + while (i < n) { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + i++; + } + return iterator.next(); + } + }; + } +})))); +/** + * Returns the first element that satisfies the specified + * predicate, or `None` if no such element exists. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8] + * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) + * firstEven // => Option.some(4) + * + * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10) + * firstGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d"] + * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0) + * atEvenIndex // => Option.some("a") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world"] + * const firstString = Iterable.findFirst( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * firstString // => Option.some("hello") + * + * // Transform during search + * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => { + * const sqrt = Math.sqrt(x) + * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none() + * }) + * findSquareRoot // => Option.some(1) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if ((0,_Predicate_js__rspack_import_1/* .isBoolean */.Lm)(o)) { + if (o) { + return _Option_js__rspack_import_2.some(a); + } + } else { + if (_Option_js__rspack_import_2.isSome(o)) { + return o; + } + } + i++; + } + return _Option_js__rspack_import_2.none(); +}); +/** + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8, 2] + * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0) + * lastEven // => Option.some(2) + * + * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10) + * lastGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0) + * lastAtEvenIndex // => Option.some("e") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world", 3] + * const lastString = Iterable.findLast( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * lastString // => Option.some("world") + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + let last = O.none(); + for (const a of self) { + const o = f(a, i); + if (isBoolean(o)) { + if (o) { + last = O.some(a); + } + } else { + if (O.isSome(o)) { + last = o; + } + } + i++; + } + return last; +}))); +/** + * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. + * + * **Example** (Zipping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * const letters = ["a", "b", "c"] + * const zipped = Iterable.zip(numbers, letters) + * Array.from(zipped) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Different lengths - shorter one determines result length + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const partial = Iterable.zip(short, long) + * Array.from(partial) // => [[1, "a"], [2, "b"]] + * + * // Works with any iterables + * const range = Iterable.range(1, 3) + * const word = "abc" + * const mixed = Iterable.zip(range, word) + * Array.from(mixed) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Create indexed pairs + * const values = ["apple", "banana", "cherry"] + * const indices = Iterable.range(0, 2) + * const indexed = Iterable.zip(indices, values) + * Array.from(indexed) // => [[0, "apple"], [1, "banana"], [2, "cherry"]] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. + * + * **Example** (Zipping with a combining function) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Add corresponding elements + * const a = [1, 2, 3, 4] + * const b = [10, 20, 30, 40] + * const sums = Iterable.zipWith(a, b, (x, y) => x + y) + * Array.from(sums) // => [11, 22, 33, 44] + * + * // Combine strings + * const firstNames = ["John", "Jane", "Bob"] + * const lastNames = ["Doe", "Smith", "Johnson"] + * const fullNames = Iterable.zipWith( + * firstNames, + * lastNames, + * (first, last) => `${first} ${last}` + * ) + * Array.from(fullNames) // => ["John Doe", "Jane Smith", "Bob Johnson"] + * + * // Different lengths - stops at shorter + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const combined = Iterable.zipWith( + * short, + * long, + * (num, letter) => `${num}${letter}` + * ) + * Array.from(combined) // => ["1a", "2b"] + * + * // Complex transformations + * const prices = [10.99, 25.50, 5.00] + * const quantities = [2, 1, 3] + * const totals = Iterable.zipWith(prices, quantities, (price, qty) => { + * return Math.round(price * qty * 100) / 100 // round to 2 decimal places + * }) + * Array.from(totals) // => [21.98, 25.5, 15] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const selfIterator = self[Symbol.iterator](); + const thatIterator = that[Symbol.iterator](); + return { + next() { + const selfResult = selfIterator.next(); + const thatResult = thatIterator.next(); + if (selfResult.done || thatResult.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(selfResult.value, thatResult.value) + }; + } + }; + } +})))); +/** + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * + * If the input is a non-empty array, the result is also a non-empty array. + * + * **Example** (Interspersing separators) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Join numbers with separator + * const numbers = [1, 2, 3, 4] + * const withCommas = Iterable.intersperse(numbers, ",") + * Array.from(withCommas) // => [1, ",", 2, ",", 3, ",", 4] + * + * // Join words with spaces + * const words = ["hello", "world", "from", "effect"] + * const sentence = Iterable.intersperse(words, " ") + * Array.from(sentence).join("") // => "hello world from effect" + * + * // Empty iterable remains empty + * const empty = Iterable.empty() + * const stillEmpty = Iterable.intersperse(empty, "-") + * Array.from(stillEmpty) // => [] + * + * // Single element has no separators added + * const single = [42] + * const noSeparator = Iterable.intersperse(single, "|") + * Array.from(noSeparator) // => [42] + * + * // Build CSS-like strings + * const styles = ["color: red", "font-size: 14px", "margin: 10px"] + * const css = Iterable.intersperse(styles, "; ") + * Array.from(css).join("") // => "color: red; font-size: 14px; margin: 10px" + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let next = iterator.next(); + let emitted = false; + return { + next() { + if (next.done) { + return next; + } else if (emitted) { + emitted = false; + return { + done: false, + value: middle + }; + } + emitted = true; + const result = next; + next = iterator.next(); + return result; + } + }; + } +})))); +/** + * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function. + * + * **Example** (Checking membership with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Custom equivalence for objects + * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id + * const containsById = Iterable.containsWith(byId) + * + * const users = [{ id: 1 }, { id: 2 }] + * const hasUser1 = containsById(users, { id: 1 }) + * hasUser1 // => true + * + * // Case-insensitive string comparison + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive) + * + * const words = ["Hello", "World"] + * const hasHello = containsCaseInsensitive(words, "hello") + * hasHello // => true + * + * // Approximate number comparison + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const containsApprox = Iterable.containsWith(approxEqual) + * + * const values = [1.0, 2.0, 3.0] + * const hasAlmostTwo = containsApprox(values, 2.05) + * hasAlmostTwo // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.contains(numbers, 3) // => true + * Iterable.contains(numbers, 6) // => false + * + * const letters = "hello" + * Iterable.contains(letters, "l") // => true + * Iterable.contains(letters, "x") // => false + * + * // Works with any iterable + * const range = Iterable.range(1, 100) + * Iterable.contains(range, 50) // => true + * Iterable.contains(range, 150) // => false + * + * // Curried version + * const containsThree = Iterable.contains(3) + * containsThree([1, 2, 3]) // => true + * containsThree([4, 5, 6]) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of + * the `Iterable`. + * + * **Example** (Chunking an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + * const chunks = Iterable.chunksOf(numbers, 3) + * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + * + * // Last chunk can be shorter + * const uneven = [1, 2, 3, 4, 5, 6, 7] + * const chunks2 = Iterable.chunksOf(uneven, 3) + * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]] + * + * // Chunk size larger than iterable + * const small = [1, 2] + * const chunks3 = Iterable.chunksOf(small, 5) + * Array.from(chunks3) // => [[1, 2]] + * + * // Process data in batches + * const data = Iterable.range(1, 100) + * const batches = Iterable.chunksOf(data, 10) + * const batchSums = Iterable.map( + * batches, + * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n) + * ) + * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255] + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const safeN = Math.max(1, Math.floor(n)); + return { + [Symbol.iterator]() { + let iterator = self[Symbol.iterator](); + return { + next() { + if (iterator === undefined) { + return { + done: true, + value: undefined + }; + } + const chunk = []; + for (let i = 0; i < safeN; i++) { + const result = iterator.next(); + if (result.done) { + iterator = undefined; + return chunk.length === 0 ? { + done: true, + value: undefined + } : { + done: false, + value: chunk + }; + } + chunk.push(result.value); + } + return { + done: false, + value: chunk + }; + } + }; + } + }; +}))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group consecutive equal numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.groupWith(numbers, (a, b) => a === b) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * // Case-insensitive grouping of strings + * const words = ["Apple", "APPLE", "banana", "Banana", "cherry"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const groupedWords = Iterable.groupWith(words, caseInsensitive) + * Array.from(groupedWords) // => [["Apple", "APPLE"], ["banana", "Banana"], ["cherry"]] + * + * // Group by approximate equality + * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2 + * const groupedFloats = Iterable.groupWith(floats, approxEqual) + * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]] + * + * // Only groups consecutive elements + * const scattered = [1, 2, 1, 2, 1] + * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b) + * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]] + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let nextResult; + return { + next() { + let result; + if (nextResult !== undefined) { + if (nextResult.done) { + return { + done: true, + value: undefined + }; + } + result = nextResult; + nextResult = undefined; + } else { + result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + } + const chunk = [result.value]; + while (true) { + const next = iterator.next(); + if (next.done || !isEquivalent(result.value, next.value)) { + nextResult = next; + return { + done: false, + value: chunk + }; + } + chunk.push(next.value); + } + } + }; + } +})))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s. + * + * **Example** (Grouping consecutive elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.group(numbers) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * const letters = "aabbccaa" + * const groupedLetters = Iterable.group(letters) + * Array.from(groupedLetters) // => [["a", "a"], ["b", "b"], ["c", "c"], ["a", "a"]] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A", value: 1 }, + * { type: "A", value: 1 }, + * { type: "B", value: 2 }, + * { type: "A", value: 1 } + * ] + * const groupedObjects = Iterable.group(objects) + * Array.from(groupedObjects).length // => 3 + * // Note: Only consecutive equal objects are grouped together + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a key) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group by string length + * const words = ["a", "bb", "ccc", "dd", "eee", "f"] + * const byLength = Iterable.groupBy(words, (word) => word.length.toString()) + * byLength // => { "1": ["a", "f"], "2": ["bb", "dd"], "3": ["ccc", "eee"] } + * + * // Group by first letter + * const names = ["Alice", "Bob", "Charlie", "David", "Anna", "Betty"] + * const byFirstLetter = Iterable.groupBy(names, (name) => name[0]) + * byFirstLetter // => { A: ["Alice", "Anna"], B: ["Bob", "Betty"], C: ["Charlie"], D: ["David"] } + * + * // Group by category + * const items = [ + * { name: "apple", category: "fruit" }, + * { name: "carrot", category: "vegetable" }, + * { name: "banana", category: "fruit" }, + * { name: "broccoli", category: "vegetable" } + * ] + * const byCategory = Iterable.groupBy(items, (item) => item.category) + * Object.keys(byCategory) // => ["fruit", "vegetable"] + * + * // Group numbers by even/odd + * const numbers = [1, 2, 3, 4, 5, 6] + * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? "even" : "odd") + * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] } + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const constEmpty = { + [Symbol.iterator]() { + return constEmptyIterator; + } +}; +const constEmptyIterator = { + next() { + return { + done: true, + value: undefined + }; + } +}; +/** + * Creates an empty iterable that yields no elements. + * + * **When to use** + * + * Use when you need an empty iterable as a typed "no data" value or a base + * case for iterable operations. + * + * **Example** (Creating an empty iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.empty()) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => constEmpty; +/** + * Creates an iterable containing a single element. + * + * **When to use** + * + * Use to wrap a single value in an iterable context so it can be combined + * with other iterable operations. + * + * **Example** (Wrapping a single value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const single = Iterable.of(42) + * Array.from(single) // => [42] + * + * // Useful for creating homogeneous sequences + * const sequences = [ + * Iterable.of("hello"), + * Iterable.range(1, 3), + * Iterable.empty() + * ] + * + * // Can be used with flatMap for conditional inclusion + * const numbers = [1, 2, 3, 4, 5] + * const evensOnly = Iterable.flatMap( + * numbers, + * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty() + * ) + * Array.from(evensOnly) // => [2, 4] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element of an iterable using a function. + * + * **Details** + * + * This is one of the most fundamental operations for working with iterables. + * It applies a transformation function to each element, creating a new iterable + * with the transformed values. The operation is lazy, so elements are only + * transformed when the iterable is consumed. + * + * **Example** (Mapping elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Transform numbers to their squares + * const numbers = [1, 2, 3, 4, 5] + * const squares = Iterable.map(numbers, (x) => x * x) + * Array.from(squares) // => [1, 4, 9, 16, 25] + * + * // Use index in transformation + * const indexed = Iterable.map(["a", "b", "c"], (char, i) => `${i}: ${char}`) + * Array.from(indexed) // => ["0: a", "1: b", "2: c"] + * + * Array.from(Iterable.map( + * Iterable.map([1, 2, 3], (x) => x * 2), + * (x) => x + 1 + * )) // => [3, 5, 7] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(result.value, i++) + }; + } + }; + } +})))); +/** + * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. + * + * **Example** (Flat mapping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Expand each number to a range + * const numbers = [1, 2, 3] + * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n)) + * Array.from(expanded) // => [1, 1, 2, 1, 2, 3] + * + * // Split strings into characters + * const words = ["hi", "bye"] + * const chars = Iterable.flatMap(words, (word) => word) + * Array.from(chars) // => ["h", "i", "b", "y", "e"] + * + * // Conditional expansion with empty iterables + * const values = [1, 2, 3, 4, 5] + * const evenMultiples = Iterable.flatMap( + * values, + * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : [] + * ) + * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12] + * + * // Use index in transformation + * const letters = ["a", "b", "c"] + * const indexed = Iterable.flatMap( + * letters, + * (letter, i) => Iterable.replicate(letter, i + 1) + * ) + * Array.from(indexed) // => ["a", "b", "b", "c", "c", "c"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatten(map(self, f))))); +/** + * Flattens an Iterable of Iterables into a single Iterable + * + * **Example** (Flattening nested iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Flatten nested arrays + * const nested = [[1, 2], [3, 4], [5, 6]] + * const flat = Iterable.flatten(nested) + * Array.from(flat) // => [1, 2, 3, 4, 5, 6] + * + * // Flatten different iterable types + * const mixed: Array> = ["ab", "cd"] + * const flatMixed = Iterable.flatten(mixed) + * Array.from(flatMixed) // => ["a", "b", "c", "d"] + * + * // Flatten deeply nested (only one level) + * const deepNested = [[[1, 2]], [[3, 4]]] + * const oneLevelFlat = Iterable.flatten(deepNested) + * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]] + * // [[1, 2], [3, 4]] (still contains arrays) + * + * // Empty iterables are handled correctly + * const withEmpty = [[1, 2], [], [3, 4], []] + * const flatWithEmpty = Iterable.flatten(withEmpty) + * Array.from(flatWithEmpty) // => [1, 2, 3, 4] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = self => ({ + [Symbol.iterator]() { + const outerIterator = self[Symbol.iterator](); + let innerIterator; + function next() { + while (true) { + if (innerIterator === undefined) { + const next = outerIterator.next(); + if (next.done) { + return next; + } + innerIterator = next.value[Symbol.iterator](); + } + const result = innerIterator.next(); + if (!result.done) { + return result; + } + innerIterator = undefined; + } + } + return { + next + }; + } +}); +/** + * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. + * + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse strings to numbers, keeping only valid ones + * const strings = ["1", "2", "invalid", "4", "not-a-number"] + * const numbers = Iterable.filterMap(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 4] + * + * // Extract specific properties from objects + * const users = [ + * { name: "Alice", age: 25, email: "alice@example.com" }, + * { name: "Bob", age: 17, email: undefined }, + * { name: "Charlie", age: 30, email: "charlie@example.com" }, + * { name: "David", age: 16, email: undefined } + * ] + * const adultEmails = Iterable.filterMap( + * users, + * (user) => + * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid + * ) + * Array.from(adultEmails) // => ["alice@example.com", "charlie@example.com"] + * + * // Use index in transformation + * const items = ["a", "b", "c", "d", "e"] + * const evenIndexItems = Iterable.filterMap( + * items, + * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid + * ) + * Array.from(evenIndexItems) // => ["0: a", "2: c", "4: e"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Transforms all elements of the `Iterable` for as long as the specified function succeeds. + * + * **Example** (Filtering and transforming until failure) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse numbers until we hit an invalid one + * const strings = ["1", "2", "3", "invalid", "4", "5"] + * const numbers = Iterable.filterMapWhile(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 3] + * + * // Take elements while they meet a condition and transform them + * const values = [2, 4, 6, 7, 8, 10] + * const doubledEvens = Iterable.filterMapWhile( + * values, + * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid + * ) + * Array.from(doubledEvens) // => [4, 8, 12] + * + * // Process with index until condition fails + * const letters = ["a", "b", "c", "d", "e"] + * const indexedUntilC = Iterable.filterMapWhile( + * letters, + * (letter, i) => letter !== "c" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid + * ) + * Array.from(indexedUntilC) // => ["0: a", "1: b"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMapWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Retrieves the `Some` values from an `Iterable` of `Option`s. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (O.isSome(result.value)) { + return { + done: false, + value: result.value.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the failure values from an iterable of + * `Result`s, skipping successful results. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getFailures([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => ["err"] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isFailure(result.value)) { + return { + done: false, + value: result.value.failure + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the success values from an iterable of + * `Result`s, skipping failed results. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getSuccesses([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => [1, 2] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isSuccess(result.value)) { + return { + done: false, + value: result.value.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Filters an iterable to only include elements that match a predicate. + * + * **Details** + * + * This function creates a new iterable containing only the elements for which + * the predicate function returns true. Like map, this operation is lazy and + * elements are only tested when the iterable is consumed. + * + * **Example** (Filtering elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Filter even numbers + * const numbers = [1, 2, 3, 4, 5, 6] + * const evens = Iterable.filter(numbers, (x) => x % 2 === 0) + * Array.from(evens) // => [2, 4, 6] + * + * // Filter with index + * const items = ["a", "b", "c", "d"] + * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1) + * Array.from(oddPositions) // => ["b", "d"] + * + * // Type refinement + * const mixed: Array = ["hello", 42, "world", 100] + * const onlyStrings = Iterable.filter( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * Array.from(onlyStrings) // => ["hello", "world"] + * + * // Combine with map + * const processed = Iterable.map( + * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2), + * (x) => x * 10 + * ) + * Array.from(processed) // => [30, 40, 50] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (predicate(result.value, i++)) { + return { + done: false, + value: result.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})); +/** + * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. + * + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (Flat mapping nullable results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Extract valid elements from nullable function results + * const data = ["1", "2", "invalid", "4"] + * const parsed = Iterable.flatMapNullishOr(data, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? null : num * 2 + * }) + * Array.from(parsed) // => [2, 4, 8] + * + * // Safe property access + * const objects = [ + * { nested: { value: 10 } }, + * { nested: null }, + * { nested: { value: 20 } }, + * {} + * ] + * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value) + * Array.from(values) // => [10, 20] + * + * // Working with Map.get (returns undefined for missing keys) + * const map = new Map([ + * ["a", 1], + * ["b", 2], + * ["c", 3] + * ]) + * const keys = ["a", "x", "b", "y", "c"] + * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key)) + * Array.from(foundValues) // => [1, 2, 3] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => filterMap(self, a => { + const b = f(a); + return b == null ? R.failVoid : R.succeed(b); +})))); +/** + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 3, 5, 7, 8] + * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0) + * hasEven // => true + * + * const allOdd = [1, 3, 5, 7] + * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0) + * hasEvenInAllOdd // => false + * + * // With index + * const letters = ["a", "b", "c"] + * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2) + * hasElementAtIndex2 // => true + * + * // Early termination - stops at first match + * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1) + * const hasEvenInInfiniteOdds = Iterable.some( + * Iterable.take(infiniteOdds, 1000), + * (x) => x % 2 === 0 + * ) + * hasEvenInInfiniteOdds // => false + * + * // Type guard usage + * const mixed: Array = [1, 2, "hello"] + * const hasString = Iterable.some( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * hasString // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i++)) { + return true; + } + } + return false; +}))); +/** + * Generates an iterable by repeatedly applying a function that produces the + * next element and state. + * + * **Details** + * + * This is useful for creating iterables from a generating function that + * maintains state. The function should return `Option.some([value, nextState])` + * to continue or `Option.none()` to stop. + * + * **Example** (Unfolding state into values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * // Generate Fibonacci sequence + * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]])) + * const first10Fib = Iterable.take(fibonacci, 10) + * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + * + * // Generate powers of 2 up to a limit + * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none()) + * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + * + * // Generate countdown + * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none()) + * Array.from(countdown) // => [5, 4, 3, 2, 1] + * + * // Generate collatz sequence + * const collatz = Iterable.unfold(7, (n) => { + * if (n === 1) return Option.none() + * const next = n % 2 === 0 ? n / 2 : n * 3 + 1 + * return Option.some([n, next]) + * }) + * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => ({ + [Symbol.iterator]() { + let next = b; + return { + next() { + const ab = f(next); + if (O.isNone(ab)) { + return { + done: true, + value: undefined + }; + } + const [a, b] = ab.value; + next = b; + return { + done: false, + value: a + }; + } + }; + } +}); +/** + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Collect each visited element + * const numbers = [1, 2, 3, 4, 5] + * const visited: Array = [] + * Iterable.forEach(numbers, (n) => visited.push(n)) + * visited // => [1, 2, 3, 4, 5] + * + * // Use index in the callback + * const letters = ["a", "b", "c"] + * const indexed: Array = [] + * Iterable.forEach(letters, (letter, i) => { + * indexed.push(`${i}: ${letter}`) + * }) + * indexed // => ["0: a", "1: b", "2: c"] + * + * // Side effects with any iterable + * const results: Array = [] + * Iterable.forEach(Iterable.range(1, 5), (n) => { + * results.push(n * n) + * }) + * results // => [1, 4, 9, 16, 25] + * + * // Process in chunks + * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2) + * const processed: Array> = [] + * Iterable.forEach(data, (chunk) => { + * processed.push(Array.from(chunk)) + * }) + * processed // => [[1, 2], [3, 4], [5, 6]] + * ``` + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + f(a, i++); + } +}))); +/** + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** + * + * This function applies a reducing function against an accumulator and each element + * of the iterable (from left to right) to reduce it to a single value. + * + * **Example** (Reducing an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Sum all numbers + * const numbers = [1, 2, 3, 4, 5] + * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n) + * sum // => 15 + * + * // Find maximum value + * const values = [3, 1, 4, 1, 5, 9, 2] + * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9 + * + * // Build an object from key-value pairs + * const pairs = [["a", 1], ["b", 2], ["c", 3]] as const + * const obj = Iterable.reduce( + * pairs, + * {} as Record, + * (acc, [key, value]) => { + * acc[key] = value + * return acc + * } + * ) + * obj // => { a: 1, b: 2, c: 3 } + * + * // Use index in the reducer + * const letters = ["a", "b", "c"] + * const indexed = Iterable.reduce( + * letters, + * [] as Array, + * (acc, letter, i) => { + * acc.push(`${i}: ${letter}`) + * return acc + * } + * ) + * indexed // => ["0: a", "1: b", "2: c"] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + if (Array.isArray(self)) { + return self.reduce(f, b); + } + let i = 0; + let result = b; + for (const n of self) { + result = f(result, n, i++); + } + return result; +}))); +/** + * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. + * + * **Example** (Deduplicating adjacent elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicates with custom equality + * const numbers = [1, 1, 2, 2, 3, 1, 1] + * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b) + * Array.from(dedupedNumbers) // => [1, 2, 3, 1] + * + * // Case-insensitive deduplication + * const words = ["Hello", "HELLO", "world", "World", "test"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive) + * Array.from(dedupedWords) // => ["Hello", "world", "test"] + * + * // Deduplication by object property + * const users = [ + * { id: 1, name: "Alice" }, + * { id: 1, name: "Alice Updated" }, // different name, same id + * { id: 2, name: "Bob" }, + * { id: 2, name: "Bob" }, + * { id: 3, name: "Charlie" } + * ] + * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id + * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId) + * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3] + * + * // Approximate numeric equality + * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual) + * Array.from(dedupedFloats) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let first = true; + let last; + function next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + if (first) { + first = false; + last = result.value; + return result; + } + const current = result.value; + if (isEquivalent(last, current)) { + return next(); + } + last = current; + return result; + } + return { + next + }; + } +})))); +/** + * Deduplicates adjacent elements that are identical. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicate numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const deduped = Iterable.dedupeAdjacent(numbers) + * Array.from(deduped) // => [1, 2, 3, 1] + * + * // Remove adjacent duplicate characters + * const letters = "aabbccaa" + * const dedupedLetters = Iterable.dedupeAdjacent(letters) + * Array.from(dedupedLetters) // => ["a", "b", "c", "a"] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A" }, + * { type: "A" }, + * { type: "B" }, + * { type: "B" }, + * { type: "A" } + * ] + * const dedupedObjects = Iterable.dedupeAdjacent(objects) + * Array.from(dedupedObjects, (object) => object.type) // => ["A", "B", "A"] + * + * // Clean up streaming data + * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100] + * const cleanedData = Iterable.dedupeAdjacent(sensorData) + * Array.from(cleanedData) // => [100, 101, 102, 100] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Zips this Iterable crosswise with the specified Iterable using the specified combiner. + * + * **Example** (Combining cartesian products) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Create coordinate pairs + * const xs = [1, 2] + * const ys = ["a", "b", "c"] + * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`) + * Array.from(coordinates) // => ["(1,a)", "(1,b)", "(1,c)", "(2,a)", "(2,b)", "(2,c)"] + * + * // Generate all combinations of options + * const sizes = ["S", "M", "L"] + * const colors = ["red", "blue"] + * const products = Iterable.cartesianWith( + * sizes, + * colors, + * (size, color) => ({ size, color }) + * ) + * Array.from(products, ({ color, size }) => `${size}:${color}`) // => ["S:red", "S:blue", "M:red", "M:blue", "L:red", "L:blue"] + * + * // Mathematical operations on all pairs + * const a = [1, 2, 3] + * const b = [10, 20] + * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y) + * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60] + * + * // Create test data combinations + * const userTypes = ["admin", "user"] + * const features = ["read", "write", "delete"] + * const testCases = Iterable.cartesianWith( + * userTypes, + * features, + * (user, feature) => `${user}_can_${feature}` + * ) + * Array.from(testCases) // => ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const cache = []; + let iterator; + let done = false; + const replay = { + [Symbol.iterator]() { + let index = 0; + return { + next() { + if (index < cache.length) { + return { + done: false, + value: cache[index++] + }; + } + if (done) { + return { + done: true, + value: undefined + }; + } + iterator ??= that[Symbol.iterator](); + const result = iterator.next(); + if (result.done) { + done = true; + return { + done: true, + value: undefined + }; + } + cache.push(result.value); + index++; + return result; + } + }; + } + }; + return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator](); + } +})))); +/** + * Zips this Iterable crosswise with the specified Iterable. + * + * **Example** (Generating cartesian pairs) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // All pairs of numbers and letters + * const numbers = [1, 2, 3] + * const letters = ["a", "b"] + * const pairs = Iterable.cartesian(numbers, letters) + * Array.from(pairs) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]] + * + * // Generate coordinate grid + * const x = [0, 1, 2] + * const y = [0, 1] + * const grid = Iterable.cartesian(x, y) + * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]] + * + * // All combinations for testing + * const browsers = ["chrome", "firefox"] + * const devices = ["desktop", "mobile", "tablet"] + * const testMatrix = Iterable.cartesian(browsers, devices) + * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => ["chrome:desktop", "chrome:mobile", "chrome:tablet", "firefox:desktop", "firefox:mobile", "firefox:tablet"] + * + * // Empty iterable results in empty cartesian product + * const empty = Iterable.empty() + * const withEmpty = Iterable.cartesian([1, 2], empty) + * Array.from(withEmpty) // => [] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +/** + * Computes how many elements of the iterable pass the given predicate. + * + * **Example** (Counting matching elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + let i = 0; + for (const a of self) { + if (f(a, i)) { + count++; + } + i++; + } + return count; +}))); +//# sourceMappingURL=Iterable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + BK: headUnsafe, + i8: findFirst, + pb: filter +}); + + +}, +"./node_modules/effect/dist/Latch.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + +/** + * Creates a `Latch` synchronously, outside of `Effect`. + * + * **When to use** + * + * Use when you need to allocate a `Latch` synchronously outside an Effect + * workflow. + * + * **Details** + * + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch unsafely) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Latch } from "effect" + * + * const latch = Latch.makeUnsafe(false) + * const waiter = latch.await.pipe(Effect.as("opened")) + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild(waiter) + * yield* latch.open + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "opened" + * ``` + * + * @see {@link make} for creating a latch inside Effect code + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = _internal_effect_js__rspack_import_0/* .makeLatchUnsafe */.zzk; +/** + * Creates a `Latch` inside `Effect`. + * + * **When to use** + * + * Use to create a latch for coordinating fibers inside Effect code. + * + * **Details** + * + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Latch } from "effect" + * + * const program = Effect.gen(function*() { + * const latch = yield* Latch.make(false) + * const waiter = latch.await.pipe(Effect.as("opened")) + * + * const fiber = yield* Effect.forkChild(waiter) + * yield* latch.open + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "opened" + * ``` + * + * @see {@link makeUnsafe} for synchronous allocation outside Effect code + * + * @category constructors + * @since 4.0.0 + */ +const make = _internal_effect_js__rspack_import_0/* .makeLatch */.Fbb; +/** + * Opens the latch and releases fibers waiting on it. + * + * **When to use** + * + * Use to open a latch and release all fibers that are waiting on it. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from closed to open, or `false` if it was already open. + * + * @see {@link openUnsafe} for a synchronous variant + * @see {@link release} to release waiting fibers without opening the latch + * + * @category combinators + * @since 4.0.0 + */ +const open = self => self.open; +/** + * Opens the latch synchronously and releases fibers waiting on it. + * + * **When to use** + * + * Use when you need synchronous code to open a latch immediately and release + * the fibers waiting on it. + * + * **Details** + * + * Returns `true` when this call changed the latch from closed to open, or + * `false` if it was already open. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link open} for the effectful variant + * @see {@link release} to release waiting fibers without opening the latch + * @see {@link closeUnsafe} for the synchronous inverse operation + * + * @category unsafe + * @since 4.0.0 + */ +const openUnsafe = self => self.openUnsafe(); +/** + * Releases the fibers currently waiting on a closed latch without opening it. + * + * **When to use** + * + * Use to let the fibers currently waiting on a latch proceed while keeping the + * latch closed for future waiters. + * + * **Details** + * + * The returned effect succeeds with `true` when release was requested while + * the latch was closed, or `false` if the latch was already open. Future + * waiters still suspend until the latch is opened or released again. + * + * @see {@link open} for opening the latch for current and future waiters + * + * @category combinators + * @since 4.0.0 + */ +const release = self => self.release; +const _await = self => self.await; + +/** + * Closes the latch so future `await` and `whenOpen` calls suspend. + * + * **When to use** + * + * Use to re-enable waiting on a latch after it was opened, so later `await` + * and `whenOpen` calls suspend again. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from open to closed, or `false` if it was already closed. + * + * @see {@link closeUnsafe} for a synchronous variant + * @see {@link open} for opening the latch for current and future waiters + * + * @category combinators + * @since 4.0.0 + */ +const close = self => self.close; +/** + * Closes the latch synchronously so future `await` and `whenOpen` calls + * suspend. + * + * **When to use** + * + * Use to close a latch synchronously when the state change must happen outside + * an `Effect`. + * + * **Details** + * + * Returns `true` when this call changed the latch from open to closed, or + * `false` if it was already closed. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link close} for the effectful variant + * @see {@link openUnsafe} to synchronously open the latch and release waiting + * fibers + * + * @category unsafe + * @since 4.0.0 + */ +const closeUnsafe = self => self.closeUnsafe(); +/** + * Waits on the latch, then runs the provided effect. + * + * **When to use** + * + * Use to gate another effect so it starts only after the latch is opened or + * the current waiters are released. + * + * **Details** + * + * If the latch is open, the effect runs immediately. If it is closed, the + * returned effect suspends until the latch is opened or the current waiters are + * released. The provided effect's success, failure, and requirements are + * preserved. + * + * @see `await` for waiting without running another effect + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch + * + * @category combinators + * @since 4.0.0 + */ +const whenOpen = (...args) => { + if (args.length === 1) { + const [self] = args; + return effect => self.whenOpen(effect); + } + const [self, effect] = args; + return self.whenOpen(effect); +}; +/** + * Checks whether the latch is currently open or closed. + * + * **When to use** + * + * Use to check the state of the latch without suspending or changing its state. + * + * @category predicates + * @since 4.0.0 + */ +const isOpen = self => self.isOpen(); +//# sourceMappingURL=Latch.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L8: make, + LZ: makeUnsafe +}); + + +}, +"./node_modules/effect/dist/Layer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Deferred_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Deferred.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Scope_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Scope.js"); + + + + + + + + + + + + +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const memoMapReuse = (entry, scope) => { + entry.observers++; + return _internal_effect_js__rspack_import_0/* .andThen */.hgn(_internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, exit => entry.finalizer(exit)), entry.effect); +}; +/** + * Returns `true` if the specified value is a `Layer`, `false` otherwise. + * + * **Example** (Checking whether a value is a layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * const notALayer = { someProperty: "value" } + * + * Layer.isLayer(dbLayer) // => true + * Layer.isLayer(notALayer) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isLayer = u => hasProperty(u, TypeId); +const LayerProto = { + [TypeId]: { + _ROut: _Function_js__rspack_import_1/* .identity */.D_, + _E: _Function_js__rspack_import_1/* .identity */.D_, + _RIn: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_2/* .pipeArguments */.tT)(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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuild = build => fromBuildUnsafe((memoMap, scope) => { + const layerScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope); + return _internal_effect_js__rspack_import_0/* .onExit */.cfM(build(memoMap, layerScope), exit => exit._tag === "Failure" ? _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit) : _internal_effect_js__rspack_import_0/* ["void"] */.rIH); +}); +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuildMemo = build => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +const memoMapBuild = (memoMap, layer, scope, build) => { + const layerScope = _Scope_js__rspack_import_3/* .makeUnsafe */.LZ(); + const deferred = _Deferred_js__rspack_import_4/* .makeUnsafe */.LZ(); + const entry = { + observers: 1, + effect: _Deferred_js__rspack_import_4/* ["await"] */.Tx(deferred), + finalizer: exit => _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + entry.observers--; + if (entry.observers === 0) { + memoMap.map.delete(layer); + return _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit); + } + return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + }) + }; + memoMap.map.set(layer, entry); + return _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, entry.finalizer).pipe(_internal_effect_js__rspack_import_0/* .flatMap */.qIB(() => build(memoMap, layerScope)), _internal_effect_js__rspack_import_0/* .onExit */.cfM(exit => { + entry.effect = exit; + return _Deferred_js__rspack_import_4/* .done */.Vw(deferred, exit); + })); +}; +class MemoMapImpl { + 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) { + return memoMapReuse(local, scope); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + const existing = this.get(layer, scope); + if (existing) { + return existing; + } + return memoMapBuild(this, layer, scope, build); + }); + } +} +/** + * 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" + * ``` + * + * @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 + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMapUnsafe = parent => new MemoMapImpl(parent); +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a memo map safely within an Effect + * const program = Effect.gen(function*() { + * const memoMap = yield* Layer.makeMemoMap + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeMemoMap = /*#__PURE__*/(/* unused pure expression or super */ null && (internalEffect.sync(makeMemoMapUnsafe))); +/** + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. + * + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMap = parent => internalEffect.sync(() => forkMemoMapUnsafe(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 + * + * @category services + * @since 3.13.0 + */ +class CurrentMemoMap extends /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl()("effect/Layer/CurrentMemoMap") { + static forkOrCreate(self) { + const current = _Context_js__rspack_import_5/* .getOrUndefined */.Y6(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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithMemoMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, memoMap, scope) => _internal_effect_js__rspack_import_0/* .provideService */.PfK(_internal_effect_js__rspack_import_0/* .map */.TjK(self.build(memoMap, scope), _Context_js__rspack_import_5/* .add */.WQ(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** + * Builds a layer into a scoped value. + * + * **Example** (Building a layer into a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Build a layer to get its services + * const program = Effect.gen(function*() { + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * + * // Build the layer into Context - automatically manages scope and memoization + * const context = yield* Layer.build(dbLayer) + * + * // Extract the specific service from the built layer + * const database = Context.get(context, Database) + * + * return yield* database.query("SELECT * FROM users") + * }) + * + * Effect.runSync(Effect.scoped(program)) // => "result" + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const build = self => core.withFiber(fiber => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), Context.getUnsafe(fiber.context, Scope.Scope))); +/** + * 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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithScope = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, scope) => _internal_core_js__rspack_import_6/* .withFiber */.R6(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 + * + * @category constructors + * @since 2.0.0 + */ +const succeed = function () { + if (arguments.length === 1) { + return resource => succeedContext(Context.make(arguments[0], resource)); + } + return succeedContext(Context.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 + * + * @category constructors + * @since 2.0.0 + */ +const succeedContext = context => fromBuildUnsafe(constant(internalEffect.succeed(context))); +/** + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. + * + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. + * + * **Example** (Disabling optional lifecycle work) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Option } from "effect" + * + * const Service = Context.Service("Service") + * const context = Effect.runSync(Effect.scoped(Layer.build(Layer.empty))) + * Context.getOption(context, Service) // => Option.none() + * ``` + * + * @see {@link effectDiscard} for running an effect while providing no services + * + * @category constructors + * @since 2.0.0 + */ +const empty = /*#__PURE__*/(/* unused pure expression or super */ null && (succeedContext(/*#__PURE__*/Context.empty()))); +/** + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeed` where the service value is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.sync(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 succeed} for constructing layers from static values + * + * @category constructors + * @since 2.0.0 + */ +const sync = function () { + if (arguments.length === 1) { + return evaluate => syncContext(() => Context.make(arguments[0], evaluate())); + } + return syncContext(() => Context.make(arguments[0], arguments[1]())); +}; +/** + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeedContext` where the `Context` is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.syncContext(() => + * 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 sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * + * @category constructors + * @since 2.0.0 + */ +const syncContext = evaluate => fromBuildMemo(constant(internalEffect.sync(evaluate))); +/** + * 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 + * + * @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(internalEffect.map(effect, value => Context.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 + * + * @category constructors + * @since 2.0.0 + */ +const effectContext = effect => fromBuildMemo((_, scope) => Scope.provide(effect, scope)); +/** + * Constructs a layer from an effect, discarding its value and providing no + * services. + * + * **When to use** + * + * Use when layer construction should run an Effect for its side effects while providing no + * services. + * + * **Example** (Running an effect during layer construction) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const logs: Array = [] + * const initLayer = Layer.effectDiscard( + * Effect.sync(() => { + * logs.push("Initializing application...") + * }) + * ) + * Effect.runSync(Effect.scoped(Layer.build(initLayer))) + * logs // => ["Initializing application..."] + * ``` + * + * @see {@link empty} for a no-op layer that performs no construction work + * + * @category constructors + * @since 2.0.0 + */ +const effectDiscard = effect => effectContext(internalEffect.as(effect, Context.empty())); +/** + * Constructs a layer lazily using the specified factory. + * + * **Details** + * + * The factory is evaluated only when the suspended layer is first built, and + * the result is memoized with normal layer sharing semantics. + * + * **Example** (Choosing a layer lazily) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const useProd = true + * + * const layer = Layer.suspend(() => + * useProd + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") + * ) + * Effect.runSync(Effect.provide(Config, layer)) // => "https://api.example.com" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = evaluate => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope))); +/** + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** + * + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. + * + * **Example** (Unwrapping an effectful layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layerEffect = Effect.succeed( + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * ) + * + * const unwrappedLayer = Layer.unwrap(layerEffect) + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, unwrappedLayer)) // => "result" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const unwrap = self => { + const service = Context.Service("effect/Layer/unwrap"); + return flatMap(effect(service)(self), Context.get(service)); +}; +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope, "parallel"); + return _internal_effect_js__rspack_import_0/* .forEach */.jJl(layers, layer => layer.build(memoMap, _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(parentScope, "sequential")), { + concurrency: layers.length + }).pipe(_internal_effect_js__rspack_import_0/* .map */.TjK(context => _Context_js__rspack_import_5/* .mergeAll */.Um(...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 + * + * @category zipping + * @since 2.0.0 + */ +const mergeAll = (...layers) => fromBuild((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 + * + * @category zipping + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => mergeAll(self, ...(Array.isArray(that) ? that : [that]))))); +const provideWith = (self, that, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), context => self.build(memoMap, scope).pipe(internalEffect.provideContext(context), internalEffect.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 + * + * @category providing services + * @since 2.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, identity)))); +/** + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) + * + * ```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") {} + * + * class UserService extends Context.Service Effect.Effect<{ + * id: string + * name: string + * }> + * }>()("UserService") {} + * + * // 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 and merge all services together + * const allServicesLayer = userServiceLayer.pipe( + * Layer.provideMerge(Layer.mergeAll(databaseLayer, loggerLayer)) + * ) + * + * // Now the resulting layer provides UserService, Database, AND Logger + * const program = Effect.gen(function*() { + * const userService = yield* UserService + * const logger = yield* Logger // Still available! + * const database = yield* Database // Still available! + * + * const user = yield* userService.getUser("123") + * yield* logger.log(`Found user: ${user.name}`) + * + * return user + * }).pipe( + * Effect.provide(allServicesLayer) + * ) + * Effect.runSync(program) // => { id: "123", name: "DB: SELECT * FROM users WHERE id = 123" } + * logs // => ["[LOG] Looking up user 123", "[LOG] Found user: DB: SELECT * FROM users WHERE id = 123"] + * ``` + * + * @see {@link provide} for keeping dependency services private + * + * @category providing services + * @since 2.0.0 + */ +const provideMerge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, (self, that) => Context.merge(that, self))))); +/** + * Constructs a layer dynamically based on the output of this layer. + * + * **Example** (Creating services from layer output) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Logger extends Context.Service Effect.Effect + * }>()("Logger") {} + * + * const logs: Array = [] + * + * // Base config layer + * const configLayer = Layer.succeed(Config, { + * dbUrl: "postgres://localhost:5432/mydb", + * logLevel: "debug" + * }) + * + * // Dynamically create services based on config + * const dynamicServiceLayer = configLayer.pipe( + * Layer.flatMap((context) => { + * const config = Context.get(context, Config) + * + * // Create database layer based on config + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => + * Effect.succeed( + * `Querying ${config.dbUrl}: ${sql}` + * )) + * }) + * + * // Create logger layer based on config + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => + * config.logLevel === "debug" + * ? Effect.sync(() => logs.push(`[DEBUG] ${msg}`)) + * : Effect.sync(() => logs.push(msg)) + * ) + * }) + * + * // Return combined layer + * return Layer.mergeAll(dbLayer, loggerLayer) + * }) + * ) + * + * // Use the dynamic services + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Starting database query") + * const result = yield* database.query("SELECT * FROM users") + * + * return result + * }).pipe( + * Effect.provide(dynamicServiceLayer) + * ) + * Effect.runSync(program) // => "Querying postgres://localhost:5432/mydb: SELECT * FROM users" + * logs // => ["[DEBUG] Starting database query"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => f(context).build(memoMap, scope)))))); +/** + * Performs the specified effect if this layer succeeds. + * + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => Scope.provide(internalEffect.as(f(context), context), scope)))))); +/** + * Performs the specified effect if this layer fails. + * + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), error => Scope.provide(internalEffect.andThen(f(error), internalEffect.fail(error)), scope)))))); +/** + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** + * + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. + * + * **Details** + * + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => Scope.provide(internalEffect.andThen(f(cause), internalEffect.failCause(cause)), scope)))))); +/** + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Exit, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Layer that can fail during construction + * const error = new DatabaseError({ message: "Connection failed" }) + * const flakyDatabaseLayer = Layer.effect( + * Database, + * Effect.fail(error) + * ) + * + * // Convert failures to fiber death - removes error from type + * const reliableDatabaseLayer = flakyDatabaseLayer.pipe(Layer.orDie) + * + * // Now the layer type is Layer - no error in type + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(reliableDatabaseLayer) + * ) + * + * Effect.runSync(Effect.exit(program)) // => Exit.die(error) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), e => onError(e).build(memoMap, scope)))))); + +/** + * Recovers from specific tagged errors. + * + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class ConfigError extends Data.TaggedError("ConfigError") {} + * + * class Config extends Context.Service()("Config") {} + * + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) + * + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) + * + * const recovered = configLayer.pipe( + * Layer.catchTag("ConfigError", () => fallbackLayer) + * ) + * const program = Config.useSync((config) => config.apiUrl) + * Effect.runSync(Effect.provide(program, recovered)) // => "http://localhost" + * ``` + * + * @see {@link catchCause} for recovering with access to the full cause + * + * @category error handling + * @since 4.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, k, f) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchTag(self.build(memoMap, scope), k, error => f(error).build(memoMap, scope)))))); +/** + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) + * + * const databaseWithFallback = primaryDatabaseLayer.pipe( + * Layer.catchCause(() => { + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(databaseWithFallback) + * ) + * + * await Effect.runPromise(program) // => "Memory: SELECT * FROM users" + * ``` + * + * @see {@link catchTag} for recovering from specific tagged errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => onError(cause).build(memoMap, scope)))))); +/** + * Updates a service in the context with a new implementation. + * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * + * **Details** + * + * This function modifies the existing implementation of a service in the + * context. It retrieves the current service, applies the provided + * transformation function `f`, and replaces the old service with the + * transformed one. + * + * @category providing services + * @since 3.13.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (layer, service, f) => provide(layer, effect(service, internalEffect.map(service, f)))))); +/** + * Creates a fresh version of this layer that will not be shared. + * + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Ref } from "effect" + * + * class Counter extends Context.Service()("Counter") {} + * + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const compareIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * return left.counterId === right.counterId + * }) + * + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) + * + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * return { id } + * })) + * + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * const sharedResult = yield* Effect.provide(compareIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * const freshResult = yield* Effect.provide(compareIds, fresh) + * + * return { shared: sharedResult, fresh: freshResult } + * }) + * + * await Effect.runPromise(program) // => { shared: true, fresh: false } + * ``` + * + * @category layers + * @since 2.0.0 + */ +const fresh = self => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope)); +/** + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) + * + * ```ts import.meta.vitest + * import { Context, Deferred, Effect, Fiber, Layer, Ref } from "effect" + * + * class HttpServer extends Context.Service()("HttpServer") {} + * + * const program = Effect.gen(function*() { + * const events = yield* Ref.make>([]) + * const started = yield* Deferred.make() + * + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { + * yield* Ref.update(events, (events) => [...events, "Starting HTTP server..."]) + * yield* Deferred.succeed(started, undefined) + * return { port: 3000 } + * })) + * + * const fiber = yield* Effect.forkChild(Layer.launch(serverLayer)) + * yield* Deferred.await(started) + * yield* Fiber.interrupt(fiber) + * return yield* Ref.get(events) + * }) + * + * await Effect.runPromise(program) // => ["Starting HTTP server..."] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const launch = self => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never)); +/** + * Creates a mock layer for testing purposes. You can provide a partial + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class UserService extends Context.Service Effect.Effect<{ id: string; name: string }, Error> + * readonly deleteUser: (id: string) => Effect.Effect + * readonly updateUser: ( + * id: string, + * data: object + * ) => Effect.Effect<{ id: string; name: string }, Error> + * }>()("UserService") {} + * + * // Create a partial mock - only implement what you need for testing + * const testUserLayer = Layer.mock(UserService, { + * config: { apiUrl: "https://test-api.com" }, // Required - non-Effect property + * getUser: (id: string) => Effect.succeed({ id, name: "Test User" }) // Mock implementation + * // deleteUser and updateUser are omitted - will throw UnimplementedError if called + * }) + * + * // Use in tests + * const testProgram = Effect.gen(function*() { + * const userService = yield* UserService + * + * // This works - we provided an implementation + * const user = yield* userService.getUser("123") + * + * // This would throw - we didn't implement deleteUser + * // yield* userService.deleteUser("123") // UnimplementedError + * + * return user.name + * }).pipe( + * Effect.provide(testUserLayer) + * ) + * Effect.runSync(testProgram) // => "Test User" + * ``` + * + * @category testing + * @since 3.17.0 + */ +const mock = function () { + if (arguments.length === 1) { + return implementation => mockImpl(arguments[0], implementation); + } + return mockImpl(arguments[0], arguments[1]); +}; +const mockImpl = (service, implementation) => succeed(service)(new Proxy({ + ...implementation +}, { + get(target, prop, _receiver) { + if (prop in target) { + return target[prop]; + } + const prevLimit = getStackTraceLimit(); + setStackTraceLimit(2); + const error = new Error(`${service.key}: Unimplemented method "${prop.toString()}"`); + setStackTraceLimit(prevLimit); + error.name = "UnimplementedError"; + return makeUnimplemented(error); + }, + has: constTrue +})); +const makeUnimplemented = error => { + const dead = Object.assign(internalEffect.die(error), { + [StreamTypeId]: StreamTypeId, + channel: { + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead), + pipe() { + return pipeArguments(this, arguments); + } + }, + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead) + }); + function unimplemented() { + return dead; + } + // @effect-diagnostics-next-line floatingEffect:off + Object.assign(unimplemented, dead); + Object.setPrototypeOf(unimplemented, Object.getPrototypeOf(dead)); + return unimplemented; +}; +const StreamTypeId = "~effect/Stream"; +const ChannelTypeId = "~effect/Channel"; +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the success + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) + * + * ```ts import.meta.vitest + * import { Context, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.succeed(NumberService, 42) + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Layer.satisfiesSuccessType() + * + * // This works - Layer<42, never, never> extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => layer => layer; +/** + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the error + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const typeErrorLayer = Layer.effectDiscard(Effect.fail(new TypeError("boom"))) + * + * // Define a constraint that the error type must be an Error + * const satisfiesError = Layer.satisfiesErrorType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesError(typeErrorLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => layer => layer; +/** + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.effectDiscard(Effect.asVoid(NumberService)) + * + * // Define a constraint that the service requirements must be numbers + * const satisfiesNumber = Layer.satisfiesServicesType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => layer => layer; +/** + * Constructs a new `Layer` which creates a span and registers it as the current + * parent span. + * + * **Details** + * + * This allows you to create a traced scope for layer construction, making all + * operations within the layer constructor part of the same trace span. The span + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const logs: Array = [] + * + * // Create a traced layer - all operations performed during construction of + * // the `Database` service are part of the "database-init" span + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * // These operations are traced under "database-init" span + * logs.push("Connecting to database") + * logs.push("Database connected") + * + * const parentSpan = yield* Effect.currentParentSpan + * logs.push((parentSpan as Tracer.Span).name) + * + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.provide(Layer.span("database-init", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Span ${span.name} ended with: ${exit._tag}`)) + * }))) + * + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => "Result: SELECT 1" + * logs // => ["Connecting to database", "Database connected", "database-init", "Span database-init ended with: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const span = (name, options) => { + options = internalTracer.addSpanStackTrace(options); + return effect(Tracer.ParentSpan, options?.onEnd ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options)); +}; +/** + * Constructs a layer that provides an existing span as the current parent span. + * + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Referencing an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a layer that uses an existing span as parent + * const databaseLayer = Layer.effect( + * Database, + * Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * + * return { + * spanId: parentSpan.spanId, + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * }) + * ).pipe(Layer.provide(Layer.parentSpan(Tracer.externalSpan({ + * spanId: "42", + * traceId: "000" + * })))) + * const program = Database.use((database) => + * Effect.map(database.query("SELECT 1"), (result) => ({ spanId: database.spanId, result }))) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => { spanId: "42", result: "Result: SELECT 1" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const parentSpan = span => succeedContext(Tracer.ParentSpan.context(span)); +/** + * Wraps a `Layer` with a new tracing span, making all operations in the layer + * constructor part of the named trace span. + * + * **Details** + * + * This creates a new span for the layer's construction and execution. The span + * is automatically ended when the layer's scope is closed. This is useful for + * tracking the lifecycle and performance of layer initialization. + * + * **Example** (Wrapping a layer with a span) + * + * ```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 = [] + * + * // Create layers with tracing + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.withSpan("database-initialization", { + * attributes: { dbType: "postgres" } + * })) + * + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) + * }).pipe(Layer.withSpan("logger-initialization")) + * + * // Combine traced layers + * const appLayer = Layer.mergeAll(databaseLayer, loggerLayer).pipe( + * Layer.withSpan("app-initialization", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Application initialization completed: ${exit._tag}`)) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Application ready") + * return yield* database.query("SELECT * FROM users") + * }).pipe(Effect.provide(appLayer)) + * Effect.runSync(program) // => "Result: SELECT * FROM users" + * logs // => ["Application ready", "Application initialization completed: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = internalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); + } + return self => unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); +}; +/** + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Cache extends Context.Service Effect.Effect + * }>()("Cache") {} + * + * // Create layers + * const DatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) + * } + * })) + * + * const CacheLayer = Layer.effect(Cache, Effect.gen(function*() { + * return { + * get: Effect.fn("Cache.get")((key: string) => Effect.succeed(`Cache: ${key}`)) + * } + * })) + * + * // Use with an existing parent span from Effect.withSpan + * const program = Effect.withSpan("application-startup")( + * Effect.gen(function*() { + * const parentSpan = yield* Tracer.ParentSpan + * + * // Both layers will be children of "application-startup" span + * const AppLayer = Layer.mergeAll(DatabaseLayer, CacheLayer).pipe( + * Layer.withParentSpan(parentSpan) + * ) + * + * const context = yield* Layer.build(AppLayer) + * const database = Context.get(context, Database) + * const cache = Context.get(context, Cache) + * + * const dbResult = yield* database.query("SELECT * FROM users") + * const cacheResult = yield* cache.get("user:123") + * + * return { dbResult, cacheResult } + * }) + * ) + * Effect.runSync(Effect.scoped(program)) // => { dbResult: "DB: SELECT * FROM users", cacheResult: "Cache: user:123" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = function () { + const dataFirst = isLayer(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = identity; + if (span._tag === "Span") { + options = internalTracer.addSpanStackTrace(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + const parentSpanLayer = parentSpan(span); + if (dataFirst) { + return provide(provideStackFrame(arguments[0]), parentSpanLayer); + } + return self => provide(provideStackFrame(self), parentSpanLayer); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : constUndefined; + return updateService(CurrentStackFrame, parent => ({ + name, + stack, + parent + })); +}; +//# sourceMappingURL=Layer.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + H7: buildWithMemoMap, + LT: buildWithScope, + Um: mergeAll, + j6: makeMemoMapUnsafe +}); + + +}, +"./node_modules/effect/dist/MutableList.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Mutable lists for collecting ordered values and draining them from the front. + * A `MutableList` can append values to the end, prepend values to the + * beginning, take one or more values from the front, inspect its contents as an + * array, filter values, remove values, and clear itself. All operations update + * the same list object in place and keep its `length` field current. Taking + * from an empty list returns the `Empty` symbol. + * + * @since 4.0.0 + */ + +/** + * Defines the unique symbol used to represent an empty result when taking elements from a MutableList. + * This symbol is returned by `take` when the list is empty, allowing for safe type checking. + * + * **When to use** + * + * Use to detect that `take` returned no element before handling the result as a + * list item. + * + * **Example** (Checking for empty results) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * + * MutableList.take(list) === MutableList.Empty // => true + * ``` + * + * @category symbols + * @since 4.0.0 + */ +const Empty = /*#__PURE__*/Symbol.for("effect/MutableList/Empty"); +/** + * Creates an empty MutableList. + * + * **Example** (Creating an empty mutable list) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * + * list.length // => 0 + * MutableList.append(list, "first") + * MutableList.take(list) // => "first" + * list.length // => 0 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = () => ({ + head: undefined, + tail: undefined, + length: 0 +}); +const emptyBucket = () => ({ + array: [], + mutable: true, + offset: 0, + next: undefined +}); +/** + * Appends an element to the end of the MutableList. + * This operation is optimized for high-frequency usage. + * + * **Example** (Appending elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * MutableList.append(list, 2) + * MutableList.append(list, 3) + * + * MutableList.toArray(list) // => [1, 2, 3] + * list.length // => 3 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const append = (self, message) => { + if (!self.tail) { + self.head = self.tail = emptyBucket(); + } else if (!self.tail.mutable) { + self.tail.next = emptyBucket(); + self.tail = self.tail.next; + } + self.tail.array.push(message); + self.length++; +}; +/** + * Prepends an element to the beginning of the MutableList. + * This operation is optimized for high-frequency usage. + * + * **Example** (Prepending elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, "last") + * MutableList.prepend(list, "third") + * MutableList.prepend(list, "second") + * MutableList.prepend(list, "first") + * + * MutableList.toArray(list) // => ["first", "second", "third", "last"] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const prepend = (self, message) => { + self.head = { + array: [message], + mutable: true, + offset: 0, + next: self.head + }; + if (!self.tail) self.tail = self.head; + self.length++; +}; +/** + * Prepends all elements from an iterable to the beginning of the MutableList. + * The elements are added in order, so the first element in the iterable becomes + * the new head of the list. + * + * **Example** (Prepending multiple elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 4) + * MutableList.append(list, 5) + * MutableList.prependAll(list, [1, 2, 3]) + * + * MutableList.toArray(list) // => [1, 2, 3, 4, 5] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const prependAll = (self, messages) => prependAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)); +/** + * Prepends all elements from a ReadonlyArray to the beginning of the MutableList. + * This is an optimized version that can reuse the array when mutable=true. + * + * **When to use** + * + * Use when prepending a trusted array directly is worth the optimized path and + * you can transfer ownership of the input when enabling mutation. + * + * **Gotchas** + * + * When mutable=true, ownership of the input array transfers to the list. Do not + * read or modify the array afterward. + * + * **Example** (Transferring an array when prepending) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 4) + * const items = [1, 2, 3] + * MutableList.prependAllUnsafe(list, items, true) + * + * MutableList.toArray(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const prependAllUnsafe = (self, messages, mutable = false) => { + self.head = { + array: messages, + mutable, + offset: 0, + next: self.head + }; + self.length += self.head.array.length; +}; +/** + * Appends all elements from an iterable to the end of the MutableList. + * Returns the number of elements added. + * + * **Example** (Appending multiple elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * MutableList.append(list, 2) + * + * MutableList.appendAll(list, [3, 4, 5]) // => 3 + * MutableList.toArray(list) // => [1, 2, 3, 4, 5] + * list.length // => 5 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const appendAll = (self, messages) => appendAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)); +/** + * Appends all elements from a ReadonlyArray to the end of the MutableList. + * This is an optimized version that can reuse the array when mutable=true. + * Returns the number of elements added. + * + * **When to use** + * + * Use when appending a trusted array directly is worth the optimized path and + * you can transfer ownership of the input when enabling mutation. + * + * **Gotchas** + * + * When mutable=true, ownership of the input array transfers to the list. Do not + * read or modify the array afterward. + * + * **Example** (Transferring an array when appending) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * const items = [2, 3, 4] + * MutableList.appendAllUnsafe(list, items, true) // => 3 + * + * MutableList.toArray(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const appendAllUnsafe = (self, messages, mutable = false) => { + if (messages.length === 0) { + return 0; + } + const chunk = { + array: messages, + mutable, + offset: 0, + next: undefined + }; + if (self.head) { + self.tail = self.tail.next = chunk; + } else { + self.head = self.tail = chunk; + } + self.length += messages.length; + return messages.length; +}; +/** + * Removes all elements from the MutableList, resetting it to an empty state. + * This operation is highly optimized and releases all internal memory. + * + * **Example** (Clearing a mutable list) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5]) + * + * MutableList.clear(list) + * + * MutableList.toArray(list) // => [] + * list.length // => 0 + * MutableList.take(list) === MutableList.Empty // => true + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const clear = self => { + self.head = self.tail = undefined; + self.length = 0; +}; +/** + * Takes up to N elements from the beginning of the MutableList and returns them as an array. + * The taken elements are removed from the list. This operation is optimized for performance + * and includes zero-copy optimizations when possible. + * + * **Example** (Taking batches) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + * + * MutableList.takeN(list, 3) // => [1, 2, 3] + * MutableList.toArray(list) // => [4, 5, 6, 7, 8, 9, 10] + * list.length // => 7 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const takeN = (self, n) => { + if (n <= 0 || !self.head) return []; + n = Math.min(n, self.length); + if (n === self.length && self.head?.offset === 0 && !self.head.next) { + const array = self.head.array; + clear(self); + return array; + } + const array = new Array(n); + let index = 0; + let chunk = self.head; + while (chunk) { + while (chunk.offset < chunk.array.length) { + array[index++] = chunk.array[chunk.offset]; + if (chunk.mutable) chunk.array[chunk.offset] = undefined; + chunk.offset++; + if (index === n) { + self.head = chunk; + self.length -= n; + if (self.length === 0) clear(self); + return array; + } + } + chunk = chunk.next; + } + clear(self); + return array; +}; +/** + * Removes up to `n` elements from the beginning of the `MutableList` without + * returning them. + * + * **When to use** + * + * Use to discard a bounded number of values from the head of a `MutableList` + * when the removed values are not needed. + * + * **Details** + * + * If `n` is less than or equal to zero, or the list is empty, the list is left + * unchanged. If `n` is greater than or equal to the current length, the list is + * cleared. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * @see {@link clear} for removing every value from the list + * + * @category mutations + * @since 4.0.0 + */ +const takeNVoid = (self, n) => { + if (n <= 0 || !self.head) return; + n = Math.min(n, self.length); + if (n === self.length && self.head?.offset === 0 && !self.head.next) { + clear(self); + return; + } + let count = 0; + let chunk = self.head; + while (chunk) { + const size = chunk.array.length - chunk.offset; + if (count + size > n) { + chunk.offset += n - count; + self.head = chunk; + self.length -= n; + return; + } + count += size; + chunk = chunk.next; + } + clear(self); + return; +}; +/** + * Takes all elements from the MutableList and returns them as an array. + * The list becomes empty after this operation. This is equivalent to takeN(list, list.length). + * + * **Example** (Draining all elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["apple", "banana", "cherry"]) + * + * MutableList.takeAll(list) // => ["apple", "banana", "cherry"] + * list.length // => 0 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const takeAll = self => takeN(self, self.length); +/** + * Takes a single element from the beginning of the MutableList. + * Returns the element if available, or the Empty symbol if the list is empty. + * The taken element is removed from the list. + * + * **Example** (Taking one element) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["first", "second", "third"]) + * + * MutableList.take(list) // => "first" + * MutableList.toArray(list) // => ["second", "third"] + * list.length // => 2 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const take = self => { + if (!self.head) return Empty; + const message = self.head.array[self.head.offset]; + if (self.head.mutable) self.head.array[self.head.offset] = undefined; + self.head.offset++; + self.length--; + if (self.head.offset === self.head.array.length) { + if (self.head.next) { + self.head = self.head.next; + } else { + clear(self); + } + } + return message; +}; +/** + * Copies up to `n` elements from the beginning of the `MutableList` into a new + * array without modifying the list. + * + * **When to use** + * + * Use when you need to inspect or snapshot a bounded prefix of the list without + * consuming it. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * + * @category converting + * @since 4.0.0 + */ +const toArrayN = (self, n) => { + if (n <= 0) return []; + const length = Math.min(n, self.length); + const out = new Array(length); + let index = 0; + let bucket = self.head; + while (bucket) { + for (let i = bucket.offset; i < bucket.array.length; i++) { + out[index++] = bucket.array[i]; + if (index === length) return out; + } + bucket = bucket.next; + } + return out; +}; +/** + * Copies all current elements of the `MutableList` into a new array without + * modifying the list. + * + * **When to use** + * + * Use when you need a snapshot of all current elements while keeping the list + * unchanged. + * + * @see {@link takeAll} for converting all elements to an array and clearing the list + * + * @category converting + * @since 4.0.0 + */ +const toArray = self => toArrayN(self, self.length); +/** + * Filters the MutableList in place, keeping only elements that satisfy the predicate. + * This operation modifies the list and rebuilds its internal structure for efficiency. + * + * **Example** (Filtering in place) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + * + * MutableList.filter(list, (n) => n % 2 === 0) + * + * MutableList.toArray(list) // => [2, 4, 6, 8, 10] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const filter = (self, f) => { + const array = []; + let chunk = self.head; + while (chunk) { + for (let i = chunk.offset; i < chunk.array.length; i++) { + if (f(chunk.array[i], i)) { + array.push(chunk.array[i]); + } + } + chunk = chunk.next; + } + if (array.length === 0) { + clear(self); + return; + } + self.head = self.tail = { + array, + mutable: true, + offset: 0, + next: undefined + }; + self.length = array.length; +}; +/** + * Removes all occurrences of a value from the `MutableList` using JavaScript + * strict equality semantics. + * + * **When to use** + * + * Use when in-place removal should use JavaScript identity/strict equality + * rather than Effect structural equality. + * + * **Details** + * + * The list is modified in place. + * + * **Gotchas** + * + * Values are compared with `!==`, so this does not use Effect structural + * equality. + * + * **Example** (Removing matching values) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["apple", "banana", "apple", "cherry", "apple"]) + * + * MutableList.remove(list, "apple") + * + * MutableList.toArray(list) // => ["banana", "cherry"] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const remove = (self, value) => filter(self, v => v !== value); +//# sourceMappingURL=MutableList.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + BC: append, + IU: clear, + L8: make, + h0: takeAll, + s: take +}); + + +}, +"./node_modules/effect/dist/Option.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var _Combiner_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Combiner.js"); +/* import */ var _Equal_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Equivalence_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equivalence.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_doNotation_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _internal_option_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_record_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _internal_result_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/* import */ var _Order_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Predicate_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Reducer_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Reducer.js"); +/** + * Models a value that may be present or absent. + * + * An `Option` is `Some` when a value is available and `None` when it is + * not. This lets code handle missing values explicitly instead of relying on + * `null` or `undefined`. The module includes helpers for creating, checking, + * transforming, combining, and extracting optional values, plus conversions to + * and from common nullable or result-like shapes. It also includes `Option.gen` + * for writing small generator-based computations that stop at the first `None`. + * + * @since 2.0.0 + */ + + + + + + + + + + + +const TypeId = "~effect/data/Option"; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const none = () => _internal_option_js__rspack_import_0/* .none */.dv; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const some = _internal_option_js__rspack_import_0/* .some */.zN; +/** + * Determines whether the given value is an `Option`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries, such as type-narrowing + * in union types. + * + * **Details** + * + * - Returns `true` for both `Some` and `None` instances + * - Acts as a type guard, narrowing the input to `Option` + * + * **Example** (Checking if a value is an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isOption(Option.some(1)) // => true + * Option.isOption(Option.none()) // => true + * Option.isOption({}) // => false + * ``` + * + * @see {@link isNone} to check for `None` specifically + * @see {@link isSome} to check for `Some` specifically + * + * @category guards + * @since 2.0.0 + */ +const isOption = _internal_option_js__rspack_import_0/* .isOption */.oL; +/** + * 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. + * + * @category guards + * @since 2.0.0 + */ +const isNone = _internal_option_js__rspack_import_0/* .isNone */.$I; +/** + * Checks whether an `Option` contains a value (`Some`). + * + * **When to use** + * + * Use when you need to branch on a present `Option` before accessing `.value`. + * + * **Details** + * + * - Acts as a type guard, narrowing to `Some` + * + * **Example** (Checking for Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isSome(Option.some(1)) // => true + * Option.isSome(Option.none()) // => false + * ``` + * + * @see {@link isNone} for the opposite check. + * + * @category guards + * @since 2.0.0 + */ +const isSome = _internal_option_js__rspack_import_0/* .isSome */.Ru; +/** + * Pattern-matches on an `Option`, handling both `None` and `Some` cases. + * + * **When to use** + * + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. + * + * **Details** + * + * - If `None`, calls `onNone` and returns its result + * - If `Some`, calls `onSome` with the value and returns its result + * - Supports the `dual` API (data-last and data-first) + * + * **Example** (Matching on an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.match(Option.some(1), { + * onNone: () => "Option is empty", + * onSome: (value) => `Option has a value: ${value}` + * }) // => "Option has a value: 1" + * ``` + * + * @see {@link getOrElse} for unwrapping with a default + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onNone, + onSome +}) => isNone(self) ? onNone() : onSome(self.value)); +/** + * Converts an `Option`-returning function into a type guard (refinement). + * + * **When to use** + * + * Use when you need to turn an `Option`-returning parser into a type-narrowing + * predicate, such as for `Array.prototype.filter`. + * + * **Details** + * + * - Returns `true` when the original function returns `Some` + * - Returns `false` when the original function returns `None` + * - Narrows the input type to `B` on success + * + * **Example** (Converting a parser to a type guard) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * type MyData = string | number + * + * const parseString = (data: MyData): Option.Option => + * typeof data === "string" ? Option.some(data) : Option.none() + * + * // ┌─── (a: MyData) => a is string + * // ▼ + * const isString = Option.toRefinement(parseString) + * + * isString("a") // => true + * isString(1) // => false + * ``` + * + * @see {@link liftPredicate} for the reverse direction + * + * @category converting + * @since 2.0.0 + */ +const toRefinement = f => a => isSome(f(a)); +/** + * Wraps the first element of an `Iterable` in a `Some`, or returns `None` if + * the iterable is empty. + * + * **When to use** + * + * Use when you need to safely extract the head of a collection, including + * generators or lazy iterables. + * + * **Details** + * + * - Only consumes the first element; does not iterate the rest + * - Returns `None` for empty iterables + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromIterable([1, 2, 3]) // => Option.some(1) + * Option.fromIterable([]) // => Option.none() + * ``` + * + * @see {@link toArray} for the inverse direction + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = collection => { + for (const a of collection) { + return some(a); + } + return none(); +}; +/** + * Converts a `Result` into an `Option`, keeping only the success value. + * + * **When to use** + * + * Use when you need to discard a `Result` failure and keep only the success + * value as an `Option`. + * + * **Details** + * + * - `Success` becomes `Some` with the success value + * - `Failure` becomes `None` and the failure value is discarded + * + * **Example** (Extracting the success side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * Option.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_2/* .getSuccess */.Oz; +/** + * Converts a `Result` into an `Option`, keeping only the failure value. + * + * **When to use** + * + * Use when you need to discard a `Result` success and keep only the failure + * value as an `Option`. + * + * **Details** + * + * - `Failure` becomes `Some` with the failure value + * - `Success` becomes `None` and the success value is discarded + * + * **Example** (Extracting the failure side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getFailure(Result.succeed("ok")) // => Option.none() + * Option.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_2/* .getFailure */.L8; +/** + * Extracts the value from a `Some`, or evaluates a fallback thunk on `None`. + * + * **When to use** + * + * Use when providing a default value for an absent `Option` + * - Unwrapping with lazy evaluation of the fallback + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → calls `onNone()` and returns its result + * - `onNone` is only called when needed (lazy) + * + * **Example** (Unwrapping with a fallback) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(1).pipe(Option.getOrElse(() => 0)) // => 1 + * Option.none().pipe(Option.getOrElse(() => 0)) // => 0 + * ``` + * + * @see {@link getOrNull} to fall back to `null` + * @see {@link getOrUndefined} to fall back to `undefined` + * @see {@link getOrThrow} to throw on `None` + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? onNone() : self.value); +/** + * Returns the fallback `Option` if `self` is `None`; otherwise returns `self`. + * + * **When to use** + * + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → evaluates and returns `that()` + * - `that` is lazily evaluated + * + * **Example** (Providing a fallback Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElse(() => Option.some("b"))) // => Option.some("b") + * Option.some("a").pipe(Option.orElse(() => Option.some("b"))) // => Option.some("a") + * ``` + * + * @see {@link orElseSome} to wrap the fallback value in `Some` automatically + * @see {@link firstSomeOf} to pick the first `Some` from a collection + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? that() : self); +/** + * Returns `Some` of the fallback value if `self` is `None`; otherwise returns + * `self`. + * + * **When to use** + * + * Use when providing a default plain value (not an `Option`) as fallback + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → calls `onNone()`, wraps result in `Some`, and returns it + * + * **Example** (Providing a fallback value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElseSome(() => "b")) // => Option.some("b") + * Option.some("a").pipe(Option.orElseSome(() => "b")) // => Option.some("a") + * ``` + * + * @see {@link orElse} when the fallback is itself an `Option` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSome = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? some(onNone()) : self); +/** + * Returns the first available value and marks whether it came from the fallback. + * + * **When to use** + * + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. + * + * **Details** + * + * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) + * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) + * - Both `None` → `None` + * + * **Example** (Tracking value source) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const fallback = () => Option.some("fallback") + * + * Option.orElseResult(Option.some("primary"), fallback) // => Option.some(Result.fail("primary")) + * Option.orElseResult(Option.none(), fallback) // => Option.some(Result.succeed("fallback")) + * ``` + * + * @see {@link orElse} for the simpler variant without source tracking + * + * @category error handling + * @since 4.0.0 + */ +const orElseResult = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? map(that(), _internal_result_js__rspack_import_2/* .succeed */.Py) : map(self, _internal_result_js__rspack_import_2/* .fail */.fJ)); +/** + * Returns the first `Some` found in an iterable of `Option`s, or `None` if + * all are `None`. + * + * **When to use** + * + * Use when you need the first available `Some` value from a priority list. + * + * **Details** + * + * - Short-circuits on the first `Some` + * - Returns `None` only when every element is `None` + * + * **Example** (Finding the first Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.firstSomeOf([ + * Option.none(), + * Option.some(1), + * Option.some(2) + * ]) // => Option.some(1) + * ``` + * + * @see {@link orElse} for a two-option fallback + * + * @category error handling + * @since 2.0.0 + */ +const firstSomeOf = collection => { + let out = none(); + for (out of collection) { + if (isSome(out)) { + return out; + } + } + return out; +}; +/** + * Converts a nullable value (`null` or `undefined`) into an `Option`. + * + * **When to use** + * + * Use when you need JavaScript nullish values to become absence at an API + * boundary while all other values, including falsy ones, remain present. + * + * **Details** + * + * - `null` or `undefined` → `None` + * - Any other value → `Some` (typed as `NonNullable`) + * + * **Example** (Converting nullable values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullishOr(undefined) // => Option.none() + * Option.fromNullishOr(null) // => Option.none() + * Option.fromNullishOr(1) // => Option.some(1) + * ``` + * + * @see {@link fromNullOr} to only treat `null` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * @see {@link liftNullishOr} to lift a nullable-returning function + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? none() : some(a); +/** + * Converts a possibly `undefined` value into an `Option`, leaving `null` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `undefined` as absent while preserving `null` + * as a meaningful value. + * + * **Details** + * + * - `undefined` → `None` + * - Any other value (including `null`) → `Some` + * + * **Example** (Converting possibly undefined values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromUndefinedOr(undefined) // => Option.none() + * Option.fromUndefinedOr(null) // => Option.some(null) + * Option.fromUndefinedOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromNullOr} to only treat `null` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromUndefinedOr = a => a === undefined ? none() : some(a); +/** + * Converts a possibly `null` value into an `Option`, leaving `undefined` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `null` as absent while preserving + * `undefined` as a meaningful value. + * + * **Details** + * + * - `null` → `None` + * - Any other value (including `undefined`) → `Some` + * + * **Example** (Converting possibly null values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullOr(null) // => Option.none() + * Option.fromNullOr(undefined) // => Option.some(undefined) + * Option.fromNullOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromNullOr = a => a === null ? none() : some(a); +/** + * Lifts a function that may return `null` or `undefined` into one that returns + * an `Option`. + * + * **When to use** + * + * Use to wrap existing nullable-returning functions for use in `Option` pipelines + * + * **Details** + * + * - Calls the original function with the given arguments + * - Wraps the result via {@link fromNullishOr} + * + * **Example** (Lifting a parser) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): number | undefined => { + * const n = parseFloat(s) + * return isNaN(n) ? undefined : n + * } + * + * const parseOption = Option.liftNullishOr(parse) + * + * parseOption("1") // => Option.some(1) + * parseOption("not a number") // => Option.none() + * ``` + * + * @see {@link fromNullishOr} for converting a single value + * @see {@link liftThrowable} for functions that throw instead + * + * @category converting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Extracts the value from a `Some`, or returns `null` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect `null`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `null` + * + * **Example** (Unwrapping to null) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrNull(Option.some(1)) // => 1 + * Option.getOrNull(Option.none()) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constNull */.XR); +/** + * Extracts the value from a `Some`, or returns `undefined` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect + * `undefined`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `undefined` + * + * **Example** (Unwrapping to undefined) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrUndefined(Option.some(1)) // => 1 + * Option.getOrUndefined(Option.none()) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constUndefined */.MN); +/** + * Lifts a function that may throw into one that returns an `Option`. + * + * **When to use** + * + * Use to wrap exception-throwing APIs (e.g. `JSON.parse`) for safe usage + * + * **Details** + * + * - If the function returns normally → `Some` with the result + * - If the function throws → `None` (exception is swallowed) + * + * **Example** (Lifting JSON.parse) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = Option.liftThrowable(JSON.parse) + * + * parse("1") // => Option.some(1) + * parse("") // => Option.none() + * ``` + * + * @see {@link liftNullishOr} for nullable-returning functions + * + * @category converting + * @since 2.0.0 + */ +const liftThrowable = f => (...a) => { + try { + return some(f(...a)); + } catch { + return none(); + } +}; +/** + * Extracts the value from a `Some`, or throws a custom error for `None`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws the value returned by `onNone()` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrowWith(Option.some(1), () => new Error("missing")) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrowWith(Option.none(), () => new Error("missing")), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "missing" + * ``` + * + * @see {@link getOrThrow} for a version with a default error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => { + if (isSome(self)) { + return self.value; + } + throw onNone(); +}); +/** + * Extracts the value from a `Some`, or throws a default `Error` for `None`. + * + * **When to use** + * + * Use when you need quick fail-fast unwrapping of an `Option` and a generic + * error is acceptable. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws `new Error("getOrThrow called on a None")` + * + * **Example** (Throwing a default error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrow(Option.some(1)) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrow(Option.none()), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "getOrThrow called on a None" + * ``` + * + * @see {@link getOrThrowWith} for a custom error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/getOrThrowWith(() => new Error("getOrThrow called on a None")); +/** + * Transforms the value inside a `Some` using the provided function, leaving + * `None` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. + * + * **Details** + * + * - `Some` → applies `f` and wraps the result in a new `Some` + * - `None` → returns `None` unchanged + * + * **Example** (Mapping over an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.map(Option.some(2), (n) => n * 2) // => Option.some(4) + * Option.map(Option.none(), (n: number) => n * 2) // => Option.none() + * ``` + * + * @see {@link flatMap} when `f` returns an `Option` + * @see {@link as} to replace the value with a constant + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : some(f(self.value))); +/** + * Replaces the value inside a `Some` with a constant, leaving `None` unchanged. + * + * **When to use** + * + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Replacing a value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.as(Option.some(42), "new value") // => Option.some("new value") + * Option.as(Option.none(), "new value") // => Option.none() + * ``` + * + * @see {@link asVoid} to replace with `undefined` + * @see {@link map} for a general transformation + * + * @category mapping + * @since 2.0.0 + */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => map(self, () => b)); +/** + * Replaces the value inside a `Some` with `void` (`undefined`), leaving `None` + * unchanged. + * + * **When to use** + * + * Use when you need to discard a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Voiding the value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.asVoid(Option.some(42)) // => Option.some(undefined) + * Option.asVoid(Option.none()) // => Option.none() + * ``` + * + * @see {@link as} to replace with a specific constant + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = /*#__PURE__*/as(undefined); +const void_ = /*#__PURE__*/some(undefined); + +/** + * Applies a function that returns an `Option` to the value of a `Some`, + * flattening the result. Returns `None` if the input is `None`. + * + * **When to use** + * + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. + * + * **Details** + * + * - `Some` → applies `f` to the value and returns its `Option` result + * - `None` → returns `None` without calling `f` + * - Equivalent to `map` followed by {@link flatten} + * + * **Example** (Chaining optional lookups) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface User { + * readonly name: string + * readonly address: Option.Option<{ readonly street: Option.Option }> + * } + * + * const user: User = { + * name: "John", + * address: Option.some({ street: Option.some("123 Main St") }) + * } + * + * user.address.pipe( + * Option.flatMap((addr) => addr.street) + * ) // => Option.some("123 Main St") + * ``` + * + * @see {@link map} when `f` returns a plain value + * @see {@link andThen} for a more flexible variant + * @see {@link flatten} to unwrap a nested `Option>` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : f(self.value)); +/** + * Chains a second computation onto an `Option`. The second value can be a + * plain value, an `Option`, or a function returning either. + * + * **When to use** + * + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. + * + * **Details** + * + * - If `self` is `None`, returns `None` immediately + * - If `f` is a function, calls it with the `Some` value + * - If `f` returns an `Option`, returns it as-is; if a plain value, wraps in `Some` + * - If `f` is not a function, uses it directly (same wrapping rules) + * + * **Example** (Chaining with andThen) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * // Chain with a function returning Option + * Option.andThen(Option.some(5), (x) => Option.some(x * 2)) // => Option.some(10) + * + * // Chain with a static value + * Option.andThen(Option.some(5), "hello") // => Option.some("hello") + * + * // Chain with None - skips + * Option.andThen(Option.none(), (x) => Option.some(x * 2)) // => Option.none() + * ``` + * + * @see {@link flatMap} for the standard monadic bind + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => { + const b = (0,_Predicate_js__rspack_import_3/* .isFunction */.Tn)(f) ? f(a) : f; + return isOption(b) ? b : some(b); +})); +/** + * Combines {@link flatMap} with {@link fromNullishOr}: applies a function that + * may return `null`/`undefined` to the value of a `Some`. + * + * **When to use** + * + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. + * + * **Details** + * + * - `None` → `None` + * - `Some` → applies `f`, then wraps via {@link fromNullishOr} + * + * **Example** (Navigating optional properties) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface Employee { + * company?: { address?: { street?: { name?: string } } } + * } + * + * const emp: Employee = { + * company: { address: { street: { name: "high street" } } } + * } + * + * Option.some(emp).pipe( + * Option.flatMapNullishOr((e) => e.company?.address?.street?.name) + * ) // => Option.some("high street") + * ``` + * + * @see {@link flatMap} when the function already returns `Option` + * @see {@link fromNullishOr} for single-value conversion + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : fromNullishOr(f(self.value))); +/** + * Flattens a nested `Option>` into `Option`. + * + * **When to use** + * + * Use when you need to remove one layer of nested `Option`. + * + * **Details** + * + * - `Some(Some(value))` → `Some(value)` + * - `Some(None)` → `None` + * - `None` → `None` + * + * **Example** (Flattening nested Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.flatten(Option.some(Option.some("value"))) // => Option.some("value") + * Option.flatten(Option.some(Option.none())) // => Option.none() + * ``` + * + * @see {@link flatMap} which is `map` + `flatten` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/flatMap(_Function_js__rspack_import_1/* .identity */.D_); +/** + * Sequences two `Option`s, keeping the value from the second if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. + * + * **Details** + * + * - Both `Some` → returns `that` + * - Either `None` → returns `None` + * + * **Example** (Keeping the second value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipRight(Option.some(1), Option.some("hello")) // => Option.some("hello") + * Option.zipRight(Option.none(), Option.some("hello")) // => Option.none() + * ``` + * + * @see {@link zipLeft} to keep the first value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipRight = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => flatMap(self, () => that)); +/** + * Sequences two `Option`s, keeping the value from the first if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. + * + * **Details** + * + * - Both `Some` → returns `self` + * - Either `None` → returns `None` + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipLeft(Option.some("hello"), Option.some(1)) // => Option.some("hello") + * Option.zipLeft(Option.some("hello"), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipRight} to keep the second value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipLeft = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => tap(self, () => that)); +/** + * Composes two `Option`-returning functions into a single function that chains + * them together. + * + * **When to use** + * + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. + * + * **Details** + * + * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value + * - Short-circuits to `None` if either function returns `None` + * + * **Example** (Composing parsers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): Option.Option => + * isNaN(Number(s)) ? Option.none() : Option.some(Number(s)) + * + * const double = (n: number): Option.Option => + * n > 0 ? Option.some(n * 2) : Option.none() + * + * const parseAndDouble = Option.composeK(parse, double) + * + * parseAndDouble("42") // => Option.some(84) + * parseAndDouble("not a number") // => Option.none() + * ``` + * + * @see {@link flatMap} for single-step chaining + * + * @category sequencing + * @since 2.0.0 + */ +const composeK = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (afb, bfc) => a => flatMap(afb(a), bfc)); +/** + * Runs a side-effecting `Option`-returning function on the value of a `Some`, + * returning the original `Option` if the function returns `Some`, or `None` + * if it returns `None`. + * + * **When to use** + * + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. + * + * **Details** + * + * - `None` → `None` + * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` + * + * **Example** (Validating without transforming) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const getInteger = (n: number) => + * Number.isInteger(n) ? Option.some(n) : Option.none() + * + * Option.tap(Option.some(1), getInteger) // => Option.some(1) + * Option.tap(Option.some(1.14), getInteger) // => Option.none() + * ``` + * + * @see {@link flatMap} when you want to transform the value + * @see {@link filter} for predicate-based filtering + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => map(f(a), () => a))); +/** + * Combines two `Option`s into a `Some` containing a tuple `[A, B]` if both + * are `Some`. + * + * **When to use** + * + * Use when you need to require two `Option` values to both be `Some` and keep + * both values as a tuple. + * + * **Details** + * + * - Both `Some` → `Some([a, b])` + * - Either `None` → `None` + * + * **Example** (Pairing two Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.product(Option.some("hello"), Option.some(42)) // => Option.some(["hello", 42]) + * Option.product(Option.none(), Option.some(42)) // => Option.none() + * ``` + * + * @see {@link zipWith} to combine with a function instead of a tuple + * @see {@link all} to combine many `Option`s + * + * @category combining + * @since 2.0.0 + */ +const product = (self, that) => isSome(self) && isSome(that) ? some([self.value, that.value]) : none(); +/** + * Combines a primary `Option` with an iterable of `Option`s into a tuple if + * all are `Some`. + * + * **When to use** + * + * Use when you need several `Option` values of the same type to all be `Some` + * and return them as a non-empty tuple. + * + * **Details** + * + * - All `Some` → `Some([self.value, ...rest])` + * - Any `None` → `None` + * + * **Example** (Combining many Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const first = Option.some(1) + * const rest = [Option.some(2), Option.some(3)] + * + * Option.productMany(first, rest) // => Option.some([1, 2, 3]) + * Option.productMany(first, [Option.some(2), Option.none()]) // => Option.none() + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link all} for tuples, structs, and iterables + * + * @category combining + * @since 2.0.0 + */ +const productMany = (self, collection) => { + if (isNone(self)) { + return none(); + } + const out = [self.value]; + for (const o of collection) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); +}; +/** + * Combines a structure of `Option`s (tuple, struct, or iterable) into a single + * `Option` containing the unwrapped structure. + * + * **When to use** + * + * Use when you need to combine multiple `Option` values into one while + * preserving the input shape, with any `None` making the result `None`. + * + * **Details** + * + * - Tuple input → `Option` of a tuple with the same length + * - Struct input → `Option` of a struct with the same keys + * - Iterable input → `Option` of an `Array` + * - Any `None` in the input → entire result is `None` + * + * **Example** (Combining a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * // ┌─── Option<[string, number]> + * // ▼ + * const tuple = Option.all([maybeName, maybeAge]) // => Option.some(["John", 25]) + * + * // ┌─── Option<{ name: string; age: number; }> + * // ▼ + * const struct = Option.all({ name: maybeName, age: maybeAge }) // => Option.some({ name: "John", age: 25 }) + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link productMany} for a homogeneous collection + * + * @category combining + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const o of input) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const o = input[key]; + if (isNone(o)) { + return none(); + } + _internal_record_js__rspack_import_4/* .assignProperty */.x(out, key, o.value); + } + return some(out); +}; +/** + * Combines two `Option`s using a provided function. + * + * **When to use** + * + * Use when you need to combine two present `Option` values into a computed + * result. + * + * **Details** + * + * - Both `Some` → applies `f(a, b)` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Combining with a function) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipWith( + * Option.some("John"), + * Option.some(25), + * (name, age) => ({ name: name.toUpperCase(), age }) + * ) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link product} to combine into a tuple instead + * @see {@link lift2} to lift a binary function + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, that, f) => map(product(self, that), ([a, b]) => f(a, b))); +/** + * Reduces an iterable of `Option`s to a single value, skipping `None` entries. + * + * **When to use** + * + * Use when you need to aggregate values from a collection where some may be + * absent. + * + * **Details** + * + * - Iterates through the collection, applying `f` only to `Some` values + * - `None` values are skipped entirely + * - Returns the accumulated result + * + * **Example** (Summing present values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * const items = [Option.some(1), Option.none(), Option.some(2), Option.none()] + * + * pipe(items, Option.reduceCompact(0, (b, a) => b + a)) // => 3 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduceCompact = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, b, f) => { + let out = b; + for (const oa of self) { + if (isSome(oa)) { + out = f(out, oa.value); + } + } + return out; +}); +/** + * Converts an `Option` into an `Array`. + * + * **When to use** + * + * Use when you need to pass an `Option` to array-based APIs or spread optional + * values into collections. + * + * **Details** + * + * - `Some` → single-element array `[value]` + * - `None` → empty array `[]` + * + * **Example** (Converting to an array) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.toArray(Option.some(1)) // => [1] + * Option.toArray(Option.none()) // => [] + * ``` + * + * @see {@link fromIterable} for the inverse direction + * + * @category converting + * @since 2.0.0 + */ +const toArray = self => isNone(self) ? [] : [self.value]; +/** + * Splits an `Option` into two `Option`s using a function that returns a `Result`. + * + * **When to use** + * + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. + * + * **Details** + * + * - `None` → `[None, None]` + * - `Some` where `f` returns `Err` → `[Some(error), None]` + * - `Some` where `f` returns `Ok` → `[None, Some(value)]` + * + * **Example** (Partitioning by Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => { + * const n = Number(s) + * return isNaN(n) ? Result.fail("Not a number") : Result.succeed(n) + * } + * + * Option.partitionMap(Option.some("42"), parseNumber) // => [Option.none(), Option.some(42)] + * Option.partitionMap(Option.some("abc"), parseNumber) // => [Option.some("Not a number"), Option.none()] + * Option.partitionMap(Option.none(), parseNumber) // => [Option.none(), Option.none()] + * ``` + * + * @see {@link filter} for simple predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const partitionMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return [none(), none()]; + } + const e = f(self.value); + return _internal_result_js__rspack_import_2/* .isFailure */.N6(e) ? [some(e.failure), none()] : [none(), some(e.success)]; +}); +/** + * Transforms and filters an `Option` using a `Filter` callback. + * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * + * The callback returns a `Result`: `Result.succeed` keeps and transforms the + * value, while `Result.fail` discards it. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.filterMap( + * Option.some(2), + * (n) => (n % 2 === 0 ? Result.succeed(`Even: ${n}`) : Result.failVoid) + * ) // => Option.some("Even: 2") + * ``` + * + * @see {@link filter} for predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return none(); + } + const next = f(self.value); + return _internal_result_js__rspack_import_2/* .isSuccess */.oJ(next) ? some(next.success) : none(); +}); +/** + * Filters an `Option` using a predicate. Returns `None` if the predicate is + * not satisfied or the input is `None`. + * + * **When to use** + * + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. + * + * **Details** + * + * - `None` → `None` + * - `Some` where `predicate(value)` is `true` → `Some(value)` + * - `Some` where `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Filtering with a predicate) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const removeEmpty = (input: Option.Option) => + * Option.filter(input, (value) => value !== "") + * + * removeEmpty(Option.some("hello")) // => Option.some("hello") + * removeEmpty(Option.some("")) // => Option.none() + * removeEmpty(Option.none()) // => Option.none() + * ``` + * + * @see {@link filterMap} to transform and filter simultaneously + * @see {@link exists} to test without filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => isNone(self) ? none() : predicate(self.value) ? some(self.value) : none()); +/** + * Creates an `Equivalence` for `Option` from an `Equivalence` for `A`. + * + * **When to use** + * + * Use when you need equality to treat two `None` values as equal and compare + * two `Some` values with a supplied equality rule. + * + * **Details** + * + * - `None` vs `None` → `true` + * - `Some` vs `None` (or vice versa) → `false` + * - `Some(a)` vs `Some(b)` → delegates to the provided `Equivalence` + * + * **Example** (Comparing Options) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const eq = Option.makeEquivalence(Equivalence.strictEqual()) + * + * eq(Option.some(1), Option.some(1)) // => true + * eq(Option.some(1), Option.some(2)) // => false + * eq(Option.none(), Option.none()) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = isEquivalent => _Equivalence_js__rspack_import_5/* .make */.L8((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value)); +/** + * Creates an `Order` for `Option` from an `Order` for `A`. + * + * **When to use** + * + * Use when you need to sort `Some` and `None` values, with `None` ordered + * before present values and present values compared by a supplied ordering + * rule. + * + * **Details** + * + * - `None` is considered less than any `Some` + * - Two `Some` values are compared using the provided `Order` + * - Two `None` values are equal (returns `0`) + * + * **Example** (Ordering Options) + * + * ```ts import.meta.vitest + * import { Number as N, Option } from "effect" + * + * const ord = Option.makeOrder(N.Order) + * + * ord(Option.none(), Option.some(1)) // => -1 + * ord(Option.some(1), Option.none()) // => 1 + * ord(Option.some(1), Option.some(2)) // => -1 + * ``` + * + * @category sorting + * @since 4.0.0 + */ +const makeOrder = O => _Order_js__rspack_import_6/* .make */.L8((self, that) => isSome(self) ? isSome(that) ? O(self.value, that.value) : 1 : -1); +/** + * Lifts a binary function to operate on two `Option` values. + * + * **When to use** + * + * Use when you need to reuse an existing binary function with two `Option` + * values. + * + * **Details** + * + * - Both `Some` → applies `f` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Lifting addition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const addOptions = Option.lift2((a: number, b: number) => a + b) + * + * addOptions(Option.some(2), Option.some(3)) // => Option.some(5) + * addOptions(Option.some(2), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipWith} for a non-lifted variant + * + * @category lifting + * @since 2.0.0 + */ +const lift2 = f => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => zipWith(self, that, f)); +/** + * Lifts a `Predicate` or `Refinement` into the `Option` context: returns + * `Some(value)` when the predicate holds, `None` otherwise. + * + * **When to use** + * + * Use to convert a boolean check into an `Option`-returning function + * - Validating input and wrapping it in `Option` + * + * **Details** + * + * - `predicate(value)` is `true` → `Some(value)` + * - `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Validating positive numbers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parsePositive = Option.liftPredicate((n: number) => n > 0) + * + * parsePositive(1) // => Option.some(1) + * parsePositive(-1) // => Option.none() + * ``` + * + * @see {@link filter} to apply a predicate to an existing `Option` + * @see {@link toRefinement} for the inverse direction + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (b, predicate) => predicate(b) ? some(b) : none()); +/** + * Checks whether an `Option` contains a value equivalent to the given one, using a + * custom `Equivalence`. + * + * **When to use** + * + * Use when you need to test whether an `Option` contains a value using a + * custom equality check. + * + * **Details** + * + * - `Some` where `isEquivalent(value, a)` is `true` → `true` + * - `Some` where not equivalent, or `None` → `false` + * + * **Example** (Checking with custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const check = Option.containsWith(Equivalence.strictEqual()) + * + * Option.some(2).pipe(check(2)) // => true + * Option.some(1).pipe(check(2)) // => false + * Option.none().pipe(check(2)) // => false + * ``` + * + * @see {@link contains} for a version using default equality + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, a) => isNone(self) ? false : isEquivalent(self.value, a)); +/** + * Checks whether an `Option` contains a value equal to the given one, using default + * structural equality. + * + * **When to use** + * + * Use when you need a quick membership test for an `Option` value using + * standard equality. + * + * **Details** + * + * - `Some` where `Equal.equals(value, a)` is `true` → `true` + * - `Some` where not equal, or `None` → `false` + * + * **Example** (Checking containment) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(2).pipe(Option.contains(2)) // => true + * Option.some(1).pipe(Option.contains(2)) // => false + * Option.none().pipe(Option.contains(2)) // => false + * ``` + * + * @see {@link containsWith} for custom equality + * @see {@link exists} to test with a predicate + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/containsWith(/*#__PURE__*/_Equal_js__rspack_import_7/* .asEquivalence */.jI()); +/** + * Checks whether the value in a `Some` satisfies a predicate or refinement. + * + * **When to use** + * + * Use to check a condition on an optional value without unwrapping + * + * **Details** + * + * - `None` → `false` + * - `Some` where `predicate(value)` is `true` → `true` + * - `Some` where `predicate(value)` is `false` → `false` + * - With a refinement, narrows the `Option` type on `true` + * + * **Example** (Testing a condition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * + * Option.some(2).pipe(Option.exists(isEven)) // => true + * Option.some(1).pipe(Option.exists(isEven)) // => false + * Option.none().pipe(Option.exists(isEven)) // => false + * ``` + * + * @see {@link filter} to keep or discard based on a predicate + * @see {@link contains} to test for a specific value + * + * @category predicates + * @since 2.0.0 + */ +const exists = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, refinement) => isNone(self) ? false : refinement(self.value)); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Gives a name to the value of an `Option`, creating a single-key record + * inside `Some`. Starting point for the do notation pipeline. + * + * **When to use** + * + * Use when you need to start an `Option` do notation chain by naming the first + * value. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.some(2), + * Option.bindTo("x"), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting with an empty record + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bindTo */.Jr(map); +const let_ = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .let_ */.zM(map); + +/** + * Adds an `Option` value to the do notation record under a given name. If the + * `Option` is `None`, the whole pipeline short-circuits to `None`. + * + * **When to use** + * + * Use when you need to sequence `Option` computations in do notation. + * + * **Example** (Binding Option values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting the chain + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bind */.oI(map, flatMap); +/** + * Provides an `Option` containing an empty record `{}`, used as the starting point for + * do notation chains. + * + * **When to use** + * + * Use when you need to start an `Option` do notation pipeline before adding + * bindings. + * + * **Example** (Building Option pipelines with do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/some({}); +/** + * Provides generator-based syntax for `Option`, similar to `async`/`await` but for + * optional values. Yielding a `None` short-circuits the generator to `None`. + * + * **When to use** + * + * Use when you need generator syntax for a sequence of `Option` steps that + * should short-circuit on `None`. + * + * **Details** + * + * - Each `yield*` unwraps a `Some` value or short-circuits to `None` + * - The return value is wrapped in `Some` + * - No `Effect` runtime is needed + * + * **Example** (Sequencing Option computations with generator syntax) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * Option.gen(function*() { + * const name = (yield* maybeName).toUpperCase() + * const age = yield* maybeAge + * return { name, age } + * }) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link Do} / {@link bind} for the do notation alternative + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isNone(current)) { + return current; + } + state = iterator.next(current.value); + } + return some(state.value); +}; +/** + * Creates a `Reducer` for `Option` that prioritizes the first non-`None` + * value and combines values when both are `Some`. + * + * **When to use** + * + * Use to build an `Option` reducer that falls back to the first available value + * when either side may be absent. + * + * **Details** + * + * - `None` + `None` → `None` + * - `Some(a)` + `None` → `Some(a)` + * - `None` + `Some(b)` → `Some(b)` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * - Initial value is `None` + * + * **Example** (Reducing with first-wins semantics) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducer(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.none(), Option.some(2)]) // => Option.some(3) + * ``` + * + * @see {@link makeReducerFailFast} for fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducer(combiner) { + return _Reducer_js__rspack_import_9/* .make */.L((self, that) => { + if (isNone(self)) return that; + if (isNone(that)) return self; + return some(combiner.combine(self.value, that.value)); + }, none()); +} +/** + * Creates a `Combiner` for `Option` with fail-fast semantics: returns `None` + * if either operand is `None`. + * + * **When to use** + * + * Use when you need an `Option` combiner that returns `None` unless both + * operands are `Some`. + * + * **Details** + * + * - `None` + anything → `None` + * - anything + `None` → `None` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * + * **Example** (Fail-fast combining) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const combiner = Option.makeCombinerFailFast(Number.ReducerSum) + * combiner.combine(Option.some(1), Option.some(2)) // => Option.some(3) + * combiner.combine(Option.some(1), Option.none()) // => Option.none() + * ``` + * + * @see {@link makeReducerFailFast} to get a full `Reducer` + * + * @category constructors + * @since 4.0.0 + */ +function makeCombinerFailFast(combiner) { + return _Combiner_js__rspack_import_10/* .make */.L8((self, that) => { + if (isNone(self) || isNone(that)) return none(); + return some(combiner.combine(self.value, that.value)); + }); +} +/** + * Creates a `Reducer` for `Option` by lifting an existing `Reducer` with + * fail-fast semantics. + * + * **When to use** + * + * Use when you need to reduce `Option` values with fail-fast semantics, where + * any `None` aborts the entire result instead of being skipped. + * + * **Details** + * + * - Initial value is `Some(reducer.initialValue)` + * - Combines only when both operands are `Some` + * - Any `None` causes the result to become `None` immediately + * + * **Example** (Fail-fast reducing) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducerFailFast(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.some(2)]) // => Option.some(3) + * reducer.combineAll([Option.some(1), Option.none()]) // => Option.none() + * ``` + * + * @see {@link makeCombinerFailFast} for just the combiner + * @see {@link makeReducer} for non-fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducerFailFast(reducer) { + const combine = makeCombinerFailFast(reducer).combine; + const initialValue = some(reducer.initialValue); + return _Reducer_js__rspack_import_9/* .make */.L(combine, initialValue, collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + if (isNone(out)) return out; + } + return out; + }); +} +//# sourceMappingURL=Option.js.map +__webpack_require__.d(__webpack_exports__, { + makeCombinerFailFast: () => (makeCombinerFailFast), + makeReducer: () => (makeReducer), + makeReducerFailFast: () => (makeReducerFailFast) +}, { + Do: Do, + all: all, + andThen: andThen, + as: as, + asVoid: asVoid, + bind: bind, + bindTo: bindTo, + composeK: composeK, + contains: contains, + containsWith: containsWith, + exists: exists, + filter: filter, + filterMap: filterMap, + firstSomeOf: firstSomeOf, + flatMap: flatMap, + flatMapNullishOr: flatMapNullishOr, + flatten: flatten, + fromIterable: fromIterable, + fromNullOr: fromNullOr, + fromNullishOr: fromNullishOr, + fromUndefinedOr: fromUndefinedOr, + gen: gen, + getFailure: getFailure, + getOrElse: getOrElse, + getOrNull: getOrNull, + getOrThrow: getOrThrow, + getOrThrowWith: getOrThrowWith, + getOrUndefined: getOrUndefined, + getSuccess: getSuccess, + isNone: isNone, + isOption: isOption, + isSome: isSome, + "let": let_, + lift2: lift2, + liftNullishOr: liftNullishOr, + liftPredicate: liftPredicate, + liftThrowable: liftThrowable, + makeEquivalence: makeEquivalence, + makeOrder: makeOrder, + map: map, + match: match, + none: none, + orElse: orElse, + orElseResult: orElseResult, + orElseSome: orElseSome, + partitionMap: partitionMap, + product: product, + productMany: productMany, + reduceCompact: reduceCompact, + some: some, + tap: tap, + toArray: toArray, + toRefinement: toRefinement, + "void": void_, + zipLeft: zipLeft, + zipRight: zipRight, + zipWith: zipWith +}); + + +}, +"./node_modules/effect/dist/Order.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/** + * Defines comparison functions for ordered values. + * + * An `Order` compares two `A` values and returns whether the first is less + * than, equal to, or greater than the second. Orders are used for sorting, + * choosing minimum or maximum values, checking ranges, and building ordered data + * structures. This module includes built-in orders, constructors for custom + * orders, tools for reversing and combining comparisons, tuple and struct + * helpers, comparison predicates, clamping, and reducer support. + * + * @since 2.0.0 + */ + + +/** + * Creates a new `Order` instance from a comparison function. + * + * **When to use** + * + * Use when you need a sorting rule not covered by the built-in orders or input + * mapping helpers, and you can provide a total comparison. + * + * **Details** + * + * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns + * `0` without calling the comparison function. The comparison function should + * return `-1`, `0`, or `1`, and the returned order satisfies total ordering + * laws when the comparison function does. + * + * **Example** (Creating an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.make<{ name: string; age: number }>((self, that) => { + * if (self.age < that.age) return -1 + * if (self.age > that.age) return 1 + * return 0 + * }) + * + * byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1 + * byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1 + * ``` + * + * @see {@link mapInput} to transform an order by mapping the input type + * @see {@link combine} to combine multiple orders + * @category constructors + * @since 2.0.0 + */ +function make(compare) { + return (self, that) => self === that ? 0 : compare(self, that); +} +/** + * Order instance for strings that compares them lexicographically using JavaScript's `<` operator. + * + * **When to use** + * + * Use when you need lexicographic string ordering. + * + * **Details** + * + * Uses lexicographic dictionary ordering. The empty string is less than any + * non-empty string, and comparisons are case-sensitive. + * + * **Example** (Ordering strings) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.String("apple", "banana") // => -1 + * Order.String("banana", "apple") // => 1 + * Order.String("apple", "apple") // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a string property + * @see {@link Struct} to combine with other orders for struct comparison + * @category instances + * @since 4.0.0 + */ +const String = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for numbers that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for numbers. + * + * **Details** + * + * `0` is considered equal to `-0`. All `NaN` values are considered equal to + * each other, and any `NaN` is considered less than any non-`NaN` number. All + * other values use standard numeric comparison. + * + * **Example** (Ordering numbers) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Number(1, 1) // => 0 + * Order.Number(1, 2) // => -1 + * Order.Number(2, 1) // => 1 + * + * Order.Number(0, -0) // => 0 + * Order.Number(NaN, 1) // => -1 + * ``` + * + * @see {@link mapInput} to compare objects by a number property + * @see {@link BigInt} for bigint comparisons + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/make((self, that) => { + if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0; + if (globalThis.Number.isNaN(self)) return -1; // NaN < any number + if (globalThis.Number.isNaN(that)) return 1; // any number > NaN + return self < that ? -1 : 1; +}); +/** + * Order instance for booleans where `false` is considered less than `true`. + * + * **When to use** + * + * Use when you need boolean ordering where `false` comes before `true`. + * + * **Details** + * + * `false` is less than `true`, and equal values return `0`. + * + * **Example** (Ordering booleans) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Boolean(false, true) // => -1 + * Order.Boolean(true, false) // => 1 + * Order.Boolean(true, true) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a boolean property + * @category instances + * @since 4.0.0 + */ +const Boolean = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for bigints that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for `bigint` values. + * + * **Details** + * + * Uses standard numeric comparison for bigint values and handles arbitrarily + * large integers. + * + * **Example** (Ordering BigInts) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.BigInt(1n, 2n) // => -1 + * Order.BigInt(2n, 1n) // => 1 + * Order.BigInt(1n, 1n) // => 0 + * ``` + * + * @see {@link Number} for regular number comparisons + * @see {@link mapInput} to compare objects by a bigint property + * @category instances + * @since 4.0.0 + */ +const BigInt = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Creates a new `Order` that reverses the comparison order of the input `Order`. + * + * **When to use** + * + * Use when you need the reverse of an existing order. + * + * **Details** + * + * Returns a new order that swaps the arguments before comparison. If the + * original order returns `-1`, the flipped order returns `1`, and vice versa. + * Equal comparisons remain `0`. + * + * **Example** (Reversing an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const flip = Order.flip(Order.Number) + * + * flip(1, 2) // => 1 + * flip(2, 1) // => -1 + * flip(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine orders for multi-criteria comparison + * @category combinators + * @since 4.0.0 + */ +function flip(O) { + return make((self, that) => O(that, self)); +} +/** + * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, + * and if the values are equal, then compares using the second `Order`. + * + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** + * + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. + * + * **Example** (Combining two Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * const byAgeAndName = Order.combine(byAge, byName) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * const person3 = { name: "Charlie", age: 25 } + * + * byAgeAndName(person1, person2) // => -1 + * byAgeAndName(person1, person3) // => 1 + * ``` + * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((a1, a2) => { + const out = self(a1, a2); + if (out !== 0) { + return out; + } + return that(a1, a2); +})))); +/** + * Creates an `Order` that considers all values as equal. + * + * **When to use** + * + * Use when you need an order that treats all values as equal. + * + * **Details** + * + * Always returns `0` regardless of input values, making it useful as a neutral + * element in order composition. + * + * **Example** (Ordering with an always-equal Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const alwaysEqualOrder = Order.alwaysEqual() + * + * alwaysEqualOrder(1, 2) // => 0 + * alwaysEqualOrder(2, 1) // => 0 + * alwaysEqualOrder(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine with other orders + * @category constructors + * @since 4.0.0 + */ +function alwaysEqual() { + return make(() => 0); +} +/** + * Combines all `Order` instances in the provided collection into a single `Order`. + * The resulting `Order` compares using each `Order` in sequence until a non-zero result is found. + * + * **When to use** + * + * Use when you need tie-breaking across a variable number of orders. + * + * **Details** + * + * Applies orders in iteration order and short-circuits on the first non-zero + * result. It returns `0` only if all orders return `0`. + * + * **Example** (Combining multiple Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * + * const combinedOrder = Order.combineAll([byAge, byName]) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * + * combinedOrder(person1, person2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link makeReducer} to create a reducer for combining orders + * @category combining + * @since 2.0.0 + */ +function combineAll(collection) { + return make((a1, a2) => { + let out = 0; + for (const O of collection) { + out = O(a1, a2); + if (out !== 0) { + return out; + } + } + return out; + }); +} +/** + * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that + * maps values of type `B` to values of type `A`. + * + * **When to use** + * + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. + * + * **Example** (Mapping Input) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byLength = Order.mapInput(Order.Number, (s: string) => s.length) + * + * byLength("a", "bb") // => -1 + * byLength("bb", "a") // => 1 + * byLength("aa", "bb") // => 0 + * ``` + * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => make((b1, b2) => self(f(b1), f(b2)))); +/** + * Order instance for `Date` objects that compares them chronologically by their timestamp. + * + * **When to use** + * + * Use when you need chronological ordering for JavaScript date values. + * + * **Details** + * + * Compares dates by their underlying timestamp in milliseconds since the epoch. + * Earlier dates are less than later dates. Invalid dates are compared through + * their `getTime()` result. + * + * **Example** (Ordering Dates) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const date1 = new Date("2023-01-01") + * const date2 = new Date("2023-01-02") + * + * Order.Date(date1, date2) // => -1 + * Order.Date(date2, date1) // => 1 + * Order.Date(date1, date1) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a date property + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, date => date.getTime()))); +/** + * Creates an `Order` for a tuple type based on orders for each element. + * + * **When to use** + * + * Use when you need fixed-length tuple ordering with per-position orders. + * + * **Details** + * + * Compares tuples element-by-element using the corresponding order and stops at + * the first non-zero comparison result. Tuples must have the same length as the + * order collection, and the result is `0` only if all elements are equal. + * + * **Example** (Ordering tuples) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const tupleOrder = Order.Tuple([Order.Number, Order.String]) + * + * tupleOrder([1, "a"], [2, "b"]) // => -1 + * tupleOrder([1, "b"], [1, "a"]) // => 1 + * tupleOrder([1, "a"], [1, "a"]) // => 0 + * ``` + * + * @see {@link Array} to compare arrays with length consideration + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + const len = elements.length; + for (let i = 0; i < len; i++) { + const o = elements[i](self[i], that[i]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * @since 4.0.0 + */ +function Array_(O) { + return make((self, that) => { + const aLen = self.length; + const bLen = that.length; + const len = Math.min(aLen, bLen); + for (let i = 0; i < len; i++) { + const o = O(self[i], that[i]); + if (o !== 0) { + return o; + } + } + return Number(aLen, bLen); + }); +} + +/** + * Creates an `Order` for structs by applying the given `Order`s to each property in sequence. + * + * **When to use** + * + * Use when you need multi-field ordering for objects with known properties. + * + * **Details** + * + * Compares structs field-by-field in the key order of the fields object and + * stops at the first non-zero comparison result. Field order matters: earlier + * fields take precedence. The result is `0` only if all fields are equal. + * + * **Example** (Ordering structs) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const personOrder = Order.Struct({ + * name: Order.String, + * age: Order.Number + * }) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 25 } + * const person3 = { name: "Alice", age: 25 } + * + * personOrder(person1, person2) // => -1 + * personOrder(person1, person3) // => 1 + * personOrder(person1, person1) // => 0 + * ``` + * + * @see {@link combine} to combine orders manually + * @see {@link mapInput} to extract and compare by a single property + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return make((self, that) => { + for (const key of keys) { + const o = fields[key](self[key], that[key]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * Checks whether one value is strictly less than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1`, meaning the first value is less + * than the second. Equal or greater values return `false`. + * + * **Example** (Checking less-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanNumber = Order.isLessThan(Order.Number) + * + * isLessThanNumber(1, 2) // => true + * isLessThanNumber(2, 1) // => false + * isLessThanNumber(1, 1) // => false + * ``` + * + * @see {@link isLessThanOrEqualTo} for non-strict less than or equal + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThan = O => dual(2, (self, that) => O(self, that) === -1); +/** + * Checks whether one value is strictly greater than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1`, meaning the first value is greater + * than the second. Equal or lesser values return `false`. + * + * **Example** (Checking greater-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanNumber = Order.isGreaterThan(Order.Number) + * + * isGreaterThanNumber(2, 1) // => true + * isGreaterThanNumber(1, 2) // => false + * isGreaterThanNumber(1, 1) // => false + * ``` + * + * @see {@link isGreaterThanOrEqualTo} for non-strict greater than or equal + * @see {@link isLessThan} for strict less than + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = O => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, that) => O(self, that) === 1); +/** + * Checks whether one value is less than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than-or-equal predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1` or `0`, and returns `false` only if + * the order returns `1`. + * + * **Example** (Checking less-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number) + * + * isLessThanOrEqualToNumber(1, 2) // => true + * isLessThanOrEqualToNumber(1, 1) // => true + * isLessThanOrEqualToNumber(2, 1) // => false + * ``` + * + * @see {@link isLessThan} for strict less than + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== 1); +/** + * Checks whether one value is greater than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than-or-equal predicate using an + * `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1` or `0`, and returns `false` only if + * the order returns `-1`. + * + * **Example** (Checking greater-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number) + * + * isGreaterThanOrEqualToNumber(2, 1) // => true + * isGreaterThanOrEqualToNumber(1, 1) // => true + * isGreaterThanOrEqualToNumber(1, 2) // => false + * ``` + * + * @see {@link isGreaterThan} for strict greater than + * @see {@link isLessThanOrEqualTo} for less than or equal + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== -1); +/** + * Returns the minimum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the smaller of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as less than or equal to the other value. If + * values are equal, the first argument is returned. + * + * **Example** (Selecting the minimum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const minNumber = Order.min(Order.Number) + * + * minNumber(1, 2) // => 1 + * minNumber(2, 1) // => 1 + * minNumber(1, 1) // => 1 + * ``` + * + * @see {@link max} for the maximum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const min = O => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that); +/** + * Returns the maximum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the larger of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as greater than or equal to the other value. + * If values are equal, the first argument is returned. + * + * **Example** (Selecting the maximum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const maxNumber = Order.max(Order.Number) + * + * maxNumber(1, 2) // => 2 + * maxNumber(2, 1) // => 2 + * maxNumber(1, 1) // => 1 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const max = O => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that); +/** + * Restricts a value between a minimum and a maximum according to the given order. + * + * **When to use** + * + * Use when you need to clamp a value to an inclusive range according to an + * `Order`. + * + * **Details** + * + * Returns the value itself when it is between minimum and maximum, inclusive. + * Values below the range return minimum, and values above the range return + * maximum. The minimum must be less than or equal to the maximum according to + * the order. + * + * **Example** (Clamping values) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const clamp = Order.clamp(Order.Number)({ minimum: 1, maximum: 5 }) + * + * clamp(3) // => 3 + * clamp(0) // => 1 + * clamp(6) // => 5 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link max} for the maximum of two values + * @see {@link isBetween} to check if a value is within a range + * @category comparisons + * @since 2.0.0 + */ +const clamp = O => dual(2, (self, options) => min(O)(options.maximum, max(O)(options.minimum, self))); +/** + * Checks whether a value is between a minimum and a maximum (inclusive) according to the given order. + * + * **When to use** + * + * Use when you need range checks that respect domain-specific ordering, such as + * dates, versions, or custom priorities, instead of JavaScript numeric + * comparison. + * + * **Details** + * + * Returns `true` when the value is greater than or equal to minimum and less + * than or equal to maximum. Values outside the range return `false`. Both + * bounds are inclusive. + * + * **Example** (Checking ranges) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const betweenNumber = Order.isBetween(Order.Number) + * + * betweenNumber(5, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(1, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(10, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(0, { minimum: 1, maximum: 10 }) // => false + * betweenNumber(11, { minimum: 1, maximum: 10 }) // => false + * ``` + * + * @see {@link clamp} to clamp a value to a range + * @see {@link isLessThanOrEqualTo} for less than or equal check + * @see {@link isGreaterThanOrEqualTo} for greater than or equal check + * @category predicates + * @since 4.0.0 + */ +const isBetween = O => dual(2, (self, options) => !isLessThan(O)(self, options.minimum) && !isGreaterThan(O)(self, options.maximum)); +/** + * Creates a `Reducer` for combining `Order` instances, useful for aggregating orders in collections. + * + * **When to use** + * + * Use when you need a reducer that combines orders. + * + * **Details** + * + * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as + * the identity element for empty collections, and uses `combineAll` for + * combining collections of orders. The reducer can be used with fold operations + * on collections. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const reducer = Order.makeReducer() + * const orders = [Order.Number, Order.flip(Order.Number)] + * + * const combined = reducer.combineAll(orders) + * combined(1, 2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link combineAll} to combine multiple orders + * @see {@link Reducer} for reducing orders as a collection operation + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => 0, combineAll); +} +//# sourceMappingURL=Order.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make), + O3: () => (Array_) +}, { + wN: Number, + yJ: isGreaterThan, + zQ: mapInput +}); + + +}, +"./node_modules/effect/dist/Pipeable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * 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. + * + * @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 + * ``` + * + * @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; + } + } +}; +/** + * Reusable prototype that implements `Pipeable.pipe`. + * + * **When to use** + * + * Use when classes or object prototypes can reuse this value when they need the + * standard pipe implementation backed by `pipeArguments`. + * + * @category prototypes + * @since 3.15.0 + */ +const Prototype = (/* unused pure expression or super */ null && ({ + pipe() { + return pipeArguments(this, arguments); + } +})); +/** + * Provides a base constructor whose instances implement the standard `Pipeable.pipe` + * method. + * + * **When to use** + * + * Use when you need to define a class that supports Effect-style method + * chaining through `.pipe(...)`. + * + * @category constructors + * @since 3.15.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function PipeableBase() {} + PipeableBase.prototype = Prototype; + return PipeableBase; +}())); +/** + * Returns a subclass of the provided class that adds the standard `pipe` + * method. + * + * **When to use** + * + * Use to add pipe support to an existing class without extending a base class + * or modifying its prototype. + * + * **Details** + * + * The original constructor and instance members are preserved, and the added + * method delegates to `pipeArguments`. + * + * @see {@link Prototype} for a reusable prototype object + * @see {@link Class} for a base constructor to extend + * @category constructors + * @since 4.0.0 + */ +const Mixin = klass => class extends klass { + pipe() { + return pipeArguments(this, arguments); + } +}; +//# sourceMappingURL=Pipeable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + tT: pipeArguments +}); + + +}, +"./node_modules/effect/dist/Predicate.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.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. + * + * @since 2.0.0 + */ + +/** + * Transforms the input of a predicate using a mapping function. + * + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. + * + * **Details** + * + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. + * + * **Example** (Checking string length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isLongerThan2 = Predicate.mapInput((s: string) => s.length)( + * (n: number) => n > 2 + * ) + * + * isLongerThan2("hello") // => true + * ``` + * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => b => self(f(b))))); +/** + * Checks whether a readonly array has exactly `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking exact length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isPair = Predicate.isTupleOf(2) + * + * isPair([1, 2]) // => true + * ``` + * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length === n))); +/** + * Checks whether a readonly array has at least `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking minimum length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAtLeast2 = Predicate.isTupleOfAtLeast(2) + * + * hasAtLeast2([1, 2, 3]) // => true + * ``` + * + * @see {@link isTupleOf} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOfAtLeast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length >= n))); +/** + * Checks whether a value is truthy. + * + * **When to use** + * + * Use when you want a predicate that mirrors JavaScript truthiness and filters + * out falsy values like `0`, `""`, and `false`. + * + * **Details** + * + * This uses `!!input` and treats `0`, `""`, `false`, `null`, and `undefined` + * as false. + * + * **Example** (Filtering truthy values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, 1, "", "ok", false] + * const truthy = values.filter(Predicate.isTruthy) // => [1, "ok"] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNullish} + * @category predicates + * @since 2.0.0 + */ +function isTruthy(input) { + return !!input; +} +/** + * Checks whether a value is a `Set`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Set` values. + * + * **Details** + * + * Uses `instanceof Set`. + * + * **Example** (Guarding a Set) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Set([1, 2]) + * + * if (Predicate.isSet(data)) { + * data.size // => 2 + * } + * ``` + * + * @see {@link isMap} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isSet(input) { + return input instanceof Set; +} +/** + * Checks whether a value is a `Map`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Map` values. + * + * **Details** + * + * Uses `instanceof Map`. + * + * **Example** (Guarding a Map) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Map([["a", 1]]) + * + * if (Predicate.isMap(data)) { + * data.size // => 1 + * } + * ``` + * + * @see {@link isSet} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isMap(input) { + return input instanceof Map; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isString(input) { + return typeof input === "string"; +} +/** + * Checks whether a value is a `number`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * number. + * + * **Details** + * + * Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`. + * + * **Example** (Guarding numbers) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 42 + * + * if (Predicate.isNumber(data)) { + * data + 1 // => 43 + * } + * ``` + * + * @see {@link isBigInt} + * @see {@link isString} + * @category guards + * @since 2.0.0 + */ +function isNumber(input) { + return typeof input === "number"; +} +/** + * Checks whether a value is a `boolean`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * boolean. + * + * **Details** + * + * Uses `typeof input === "boolean"`. + * + * **Example** (Guarding booleans) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = true + * + * if (Predicate.isBoolean(data)) { + * data ? "yes" : "no" // => "yes" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBoolean(input) { + return typeof input === "boolean"; +} +/** + * Checks whether a value is a `bigint`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * bigint. + * + * **Details** + * + * Uses `typeof input === "bigint"`. + * + * **Example** (Guarding bigints) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 1n + * + * if (Predicate.isBigInt(data)) { + * data + 2n // => 3n + * } + * ``` + * + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBigInt(input) { + return typeof input === "bigint"; +} +/** + * Checks whether a value is a `symbol`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * symbol. + * + * **Details** + * + * Uses `typeof input === "symbol"`. + * + * **Example** (Guarding symbols) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Symbol.for("id") + * + * if (Predicate.isSymbol(data)) { + * data.description // => "id" + * } + * ``` + * + * @see {@link isPropertyKey} + * @category guards + * @since 2.0.0 + */ +function isSymbol(input) { + return typeof input === "symbol"; +} +/** + * Checks whether a value is a valid `PropertyKey` (string, number, or symbol). + * + * **When to use** + * + * Use when you need a `Predicate` guard for unknown property keys before + * indexing. + * + * **Details** + * + * Uses `isString`, `isNumber`, and `isSymbol`. + * + * **Example** (Guarding property keys) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const key: unknown = "name" + * const obj: Record = { name: "Ada" } + * + * if (Predicate.isPropertyKey(key) && key in obj) { + * obj[key] // => "Ada" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @see {@link isSymbol} + * @category guards + * @since 4.0.0 + */ +function isPropertyKey(u) { + return isString(u) || isNumber(u) || isSymbol(u); +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isFunction(input) { + return typeof input === "function"; +} +/** + * Checks whether a value is `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for values that are exactly + * `undefined`. + * + * **Details** + * + * Uses `input === undefined`. + * + * **Example** (Guarding undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = undefined + * + * Predicate.isUndefined(data) // => true + * ``` + * + * @see {@link isNotUndefined} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isUndefined(input) { + return input === undefined; +} +/** + * Checks whether a value is not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `undefined` + * while preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `undefined`. + * + * **Example** (Filtering undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, undefined, 2] + * const defined = values.filter(Predicate.isNotUndefined) // => [1, 2] + * ``` + * + * @see {@link isUndefined} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotUndefined(input) { + return input !== undefined; +} +/** + * Checks whether a value is `null`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullable values. + * + * **Details** + * + * Uses `input === null`. + * + * **Example** (Guarding null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = null + * + * Predicate.isNull(data) // => true + * ``` + * + * @see {@link isNotNull} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isNull(input) { + return input === null; +} +/** + * Checks whether a value is not `null`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `null` while + * preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `null`. + * + * **Example** (Filtering null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, null, 2] + * const nonNull = values.filter(Predicate.isNotNull) // => [1, 2] + * ``` + * + * @see {@link isNull} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotNull(input) { + return input !== null; +} +/** + * Checks whether a value is `null` or `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullish values. + * + * **Details** + * + * Uses `input === null || input === undefined`. + * + * **Example** (Guarding nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const nullish = values.filter(Predicate.isNullish) // => [null, undefined] + * ``` + * + * @see {@link isNotNullish} + * @see {@link isUndefined} + * @see {@link isNull} + * @category guards + * @since 4.0.0 + */ +function isNullish(input) { + return input === null || input === undefined; +} +/** + * Checks whether a value is not `null` and not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out nullish values + * but keeps other falsy ones. + * + * **Details** + * + * Uses `input != null`. + * + * **Example** (Filtering non-nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const present = values.filter(Predicate.isNotNullish) // => [0, ""] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNull} + * @see {@link isNotUndefined} + * @category guards + * @since 4.0.0 + */ +function isNotNullish(input) { + return input != null; +} +/** + * Type guard that always returns `false`. + * + * **When to use** + * + * Use when you need a `Predicate` that never accepts, e.g. in default branches. + * + * **Example** (Matching no values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isNever("anything") // => false + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isNever(_) { + return false; +} +/** + * Type guard that always returns `true`. + * + * **When to use** + * + * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. + * + * **Example** (Matching every value) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isUnknown(123) // => true + * ``` + * + * @see {@link isNever} + * @category guards + * @since 2.0.0 + */ +function isUnknown(_) { + return true; +} +/** + * Checks whether a value is an object or an array (non-null object). + * + * **When to use** + * + * Use when you need a `Predicate` guard that accepts plain objects and arrays, + * but not `null`. + * + * **Details** + * + * Uses `typeof input === "object" && input !== null` and includes arrays. + * + * **Example** (Checking objects or arrays) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObjectOrArray([]) // => true + * ``` + * + * @see {@link isObject} + * @see {@link isObjectKeyword} + * @category guards + * @since 4.0.0 + */ +function isObjectOrArray(input) { + return typeof input === "object" && input !== null; +} +/** + * Checks whether a value is a non-null object value that is not an array. + * + * **When to use** + * + * Use to narrow unknown input to a non-null, non-array object with a + * `Predicate` guard. + * + * **Details** + * + * This is a structural runtime check using `typeof input === "object"`, so it + * also accepts object instances such as `Date`, `Map`, class instances, and + * typed arrays. It excludes `null` and arrays. + * + * **Example** (Guarding objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObject({ a: 1 }) // => true + * Predicate.isObject([1, 2]) // => false + * ``` + * + * @see {@link isObjectOrArray} + * @see {@link isReadonlyObject} + * @category guards + * @since 2.0.0 + */ +function isObject(input) { + return typeof input === "object" && input !== null && !Array.isArray(input); +} +/** + * Checks whether a value is a non-null, non-array object and narrows it to a + * readonly indexable object type. + * + * **When to use** + * + * Use to narrow unknown input to a readonly view of a non-null, non-array + * object with a `Predicate` guard. + * + * **Details** + * + * Readonly-ness is a TypeScript type-level view; it is not observable at + * runtime. This delegates to `isObject`, so class instances and built-in object + * instances are accepted. + * + * **Example** (Checking readonly objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { a: 1 } + * + * Predicate.isReadonlyObject(data) // => true + * ``` + * + * @see {@link isObject} + * @category guards + * @since 4.0.0 + */ +function isReadonlyObject(input) { + return isObject(input); +} +/** + * 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} + * @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} + * @category guards + * @since 2.0.0 + */ +const hasProperty = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, property) => isObjectKeyword(self) && property in self); +/** + * Checks whether a value has a `_tag` property equal to the given tag. + * + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. + * + * **Details** + * + * Uses `hasProperty` and strict equality on `_tag`. + * + * **Example** (Guarding tagged values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isOk = Predicate.isTagged("Ok") + * + * isOk({ _tag: "Ok", value: 1 }) // => true + * ``` + * + * @see {@link hasProperty} + * @category guards + * @since 2.0.0 + */ +const isTagged = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, tag) => hasProperty(self, "_tag") && self["_tag"] === tag); +/** + * Checks whether a value is an `Error`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for errors caught from unknown sources. + * + * **Details** + * + * Uses `instanceof Error`. + * + * **Example** (Guarding errors) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Error("boom") + * + * Predicate.isError(data) // => true + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isError(input) { + return input instanceof Error; +} +/** + * Checks whether a value is a `Uint8Array`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for binary data. + * + * **Details** + * + * Uses `instanceof Uint8Array`. + * + * **Example** (Guarding Uint8Array values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Uint8Array([1, 2]) + * + * Predicate.isUint8Array(data) // => true + * ``` + * + * @see {@link isIterable} + * @see {@link isSet} + * @category guards + * @since 2.0.0 + */ +function isUint8Array(input) { + return input instanceof Uint8Array; +} +/** + * Checks whether a value is a `Date`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for dates. + * + * **Details** + * + * Uses `instanceof Date`. + * + * **Example** (Guarding Date values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Date() + * + * Predicate.isDate(data) // => true + * ``` + * + * @see {@link isRegExp} + * @category guards + * @since 2.0.0 + */ +function isDate(input) { + return input instanceof Date; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isIterable(input) { + return hasProperty(input, Symbol.iterator) || isString(input); +} +/** + * Checks whether a value is a `Promise`-like object with `then` and `catch`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise instances across realms. + * + * **Details** + * + * Performs a structural check for `then` and `catch` functions. + * + * **Example** (Guarding promises) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Promise.resolve(1) + * + * Predicate.isPromise(data) // => true + * ``` + * + * @see {@link isPromiseLike} + * @category guards + * @since 2.0.0 + */ +function isPromise(input) { + return hasProperty(input, "then") && "catch" in input && isFunction(input.then) && isFunction(input.catch); +} +/** + * Checks whether a value is `PromiseLike` (has a `then` method). + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise-like values with a + * callable `then` method. + * + * **Details** + * + * Performs a structural check for a callable `then`. + * + * **Example** (Guarding promise-like values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { then: () => {} } + * + * Predicate.isPromiseLike(data) // => true + * ``` + * + * @see {@link isPromise} + * @category guards + * @since 2.0.0 + */ +function isPromiseLike(input) { + return hasProperty(input, "then") && isFunction(input.then); +} +/** + * Checks whether a value is a `RegExp`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for regular expressions. + * + * **Details** + * + * Uses `instanceof RegExp`. + * + * **Example** (Guarding RegExp values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = /abc/ + * + * Predicate.isRegExp(data) // => true + * ``` + * + * @see {@link isDate} + * @category guards + * @since 3.9.0 + */ +function isRegExp(input) { + return input instanceof RegExp; +} +/** + * Composes two predicates or refinements into one. + * + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. + * + * **Example** (Composing refinements) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNumber: Predicate.Refinement = (u): u is number => typeof u === "number" + * const isInteger: Predicate.Refinement = (n): n is number => Number.isInteger(n) + * + * const isIntegerNumber = Predicate.compose(isNumber, isInteger) + * + * isIntegerNumber(1) // => true + * ``` + * + * @see {@link and} + * @see {@link Refinement} + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => ab(a) && bc(a)))); +/** + * Creates a predicate for tuples by applying predicates to each element. + * + * **When to use** + * + * Use when you want to validate tuple positions independently by lifting + * element predicates into a tuple predicate. + * + * **Details** + * + * Returns a refinement if any element predicate is a refinement. Evaluation + * stops at the first failing element. + * + * **Example** (Checking tuples) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const tupleCheck = Predicate.Tuple([(n: number) => n > 0, Predicate.isString]) + * + * tupleCheck([1, "ok"]) // => true + * ``` + * + * @see {@link Struct} + * @see {@link isTupleOf} + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return as => { + for (let i = 0; i < elements.length; i++) { + if (elements[i](as[i]) === false) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate for objects by applying predicates to named properties. + * + * **When to use** + * + * Use when you want to validate a record shape at runtime by lifting property + * predicates into an object predicate. + * + * **Details** + * + * Returns a refinement if any field predicate is a refinement. Only the + * specified keys are checked, and extra keys are ignored. + * + * **Example** (Checking structs) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const userCheck = Predicate.Struct({ + * id: Predicate.isNumber, + * name: Predicate.isString + * }) + * + * userCheck({ id: 1, name: "Ada" }) // => true + * ``` + * + * @see {@link Tuple} + * @see {@link hasProperty} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return a => { + for (const key of keys) { + if (!fields[key](a[key])) { + return false; + } + } + return true; + }; +} +/** + * Negates a predicate. + * + * **When to use** + * + * Use when you want the inverse of an existing predicate. + * + * **Details** + * + * Returns a new predicate that flips the boolean result. + * + * **Example** (Negating a predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNotString = Predicate.not(Predicate.isString) + * + * isNotString(1) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +function not(self) { + return a => !self(a); +} +/** + * Creates a predicate that returns `true` if either predicate is `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. + * + * **Example** (Checking either condition) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber) + * + * isStringOrNumber("a") // => true + * ``` + * + * @see {@link and} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) || that(a)))); +/** + * Creates a predicate that returns `true` only if both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. + * + * **Example** (Checking both conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAAndB = Predicate.and( + * Predicate.hasProperty("a"), + * Predicate.hasProperty("b") + * ) + * + * const input: unknown = JSON.parse(`{"a":1,"b":"ok"}`) + * if (hasAAndB(input)) { + * // input has both properties at this point + * const a = input.a + * const b = input.b + * + * const values = [a, b] // => [1, "ok"] + * } + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const and = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) && that(a)))); +/** + * Creates a predicate that returns `true` if exactly one predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with exclusive-or semantics. + * + * **Details** + * + * Returns `true` when results differ. + * + * **Example** (Checking exclusive-or conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const isPositive = (n: number) => n > 0 + * const either = Predicate.xor(isEven, isPositive) + * + * either(-2) // => true + * ``` + * + * @see {@link or} + * @see {@link and} + * @category combinators + * @since 2.0.0 + */ +const xor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) !== that(a)))); +/** + * Creates a predicate that returns `true` when both predicates agree. + * + * **When to use** + * + * Use when you want to check equivalence of two `Predicate`s. + * + * **Details** + * + * Returns `true` when both results are equal. + * + * **Example** (Defining equivalence) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const same = Predicate.eqv(isEven, isEven) + * + * same(3) // => true + * ``` + * + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const eqv = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) === that(a)))); +/** + * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. + * + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. + * + * **Details** + * + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. + * + * **Example** (Checking implication) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isAdult = (age: number) => age >= 18 + * const canVote = (age: number) => age >= 18 + * const implies = Predicate.implies(isAdult, canVote) + * + * implies(16) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @category combinators + * @since 2.0.0 + */ +const implies = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (antecedent, consequent) => a => antecedent(a) ? consequent(a) : true))); +/** + * Creates a predicate that returns `true` when neither predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NOR semantics. + * + * **Details** + * + * Returns the negation of `or`. + * + * **Example** (Checking NOR conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const neither = Predicate.nor(Predicate.isString, Predicate.isNumber) + * + * neither(true) // => true + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) || that(a))))); +/** + * Creates a predicate that returns `true` unless both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NAND semantics. + * + * **Details** + * + * Returns the negation of `and`. + * + * **Example** (Checking NAND conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const notBoth = Predicate.nand(Predicate.isString, Predicate.isNumber) + * + * notBoth("a") // => true + * ``` + * + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nand = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) && that(a))))); +/** + * Creates a predicate that returns `true` if all predicates in the collection return `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates to apply. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking all predicates) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const allChecks = Predicate.every([Predicate.isNumber, (n: number) => n > 0]) + * + * allChecks(2) // => true + * ``` + * + * @see {@link some} + * @see {@link and} + * @category combining + * @since 2.0.0 + */ +function every(collection) { + return a => { + for (const p of collection) { + if (!p(a)) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate that returns `true` if any predicate in the collection returns `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates and only need one to pass. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking any predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const anyCheck = Predicate.some([Predicate.isString, Predicate.isNumber]) + * + * anyCheck("ok") // => true + * ``` + * + * @see {@link every} + * @see {@link or} + * @category combining + * @since 2.0.0 + */ +function some(collection) { + return a => { + for (const p of collection) { + if (p(a)) { + return true; + } + } + return false; + }; +} +//# sourceMappingURL=Predicate.js.map +__webpack_require__.d(__webpack_exports__, { + $P: () => (isDate), + Bm: () => (isSymbol), + Et: () => (isNumber), + Kg: () => (isString), + Lm: () => (isBoolean), + Tn: () => (isFunction), + sI: () => (isBigInt), + xZ: () => (isIterable) +}, { + $J: isTagged, + i5: hasProperty +}); + + +}, +"./node_modules/effect/dist/Pull.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Exit_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/** + * Models one low-level pull step for stream-like consumers. + * + * A `Pull` is an `Effect` that can produce one `A`, fail with an + * ordinary error `E`, or signal end-of-input with `Cause.Done`. The + * separate done signal lets low-level consumers distinguish normal completion + * from failure. This module includes type extractors and helpers for detecting, + * filtering, catching, converting, and matching done signals separately from + * ordinary failures. + * + * @since 4.0.0 + */ + + + + + + +// ----------------------------------------------------------------------------- +// Done +// ----------------------------------------------------------------------------- +/** + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * + * @category error handling + * @since 4.0.0 + */ +const catchDone = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (effect, f) => _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk(effect, filterDoneLeftover, l => f(l))); +/** + * Checks whether a Cause contains any done errors. + * + * **When to use** + * + * Use when you need to test whether a pull failure cause represents normal + * completion and only need a boolean result. + * + * @see {@link isDoneFailure} for checking a single `Cause.Reason` + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * @see {@link filterNoDone} for selecting causes with no done failures + * + * @category predicates + * @since 4.0.0 + */ +const isDoneCause = cause => cause.reasons.some(isDoneFailure); +/** + * Checks whether a `Cause.Reason` is a `Fail` reason whose error is a + * `Cause.Done` signal. + * + * **When to use** + * + * Use when you need to identify done completion reasons while traversing + * `cause.reasons`, before handling ordinary failures. + * + * @see {@link isDoneCause} for checking an entire `Cause` for any done reason + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * + * @category guards + * @since 4.0.0 + */ +const isDoneFailure = failure => failure._tag === "Fail" && _Cause_js__rspack_import_2/* .isDone */.$L(failure.error); +/** + * Finds a `Cause.Done` failure in a `Cause`. + * + * **When to use** + * + * Use to separate `Cause.Done` completion from ordinary causes while preserving + * the typed done value. + * + * **Details** + * + * Returns a successful `Result` with the `Cause.Done` value when the cause + * contains a done signal and no other failures besides interruptions. When the + * done signal was merged with a real failure (for example a failing + * finalizer), the `Result` fails with the remaining cause, stripped of the + * done signal. Without a done signal the `Result` fails with the original + * cause. + * + * @category filtering + * @since 4.0.0 + */ +const filterDone = cause => { + let done; + let hasFailure = false; + for (const reason of cause.reasons) { + if (isDoneFailure(reason)) { + done ??= reason.error; + } else if (reason._tag !== "Interrupt") { + hasFailure = true; + } + } + if (done === undefined) return _Result_js__rspack_import_3/* .fail */.fJ(cause); + return hasFailure ? _Result_js__rspack_import_3/* .fail */.fJ(_Cause_js__rspack_import_2/* .fromReasons */.kO(cause.reasons.filter(reason => !isDoneFailure(reason)))) : _Result_js__rspack_import_3/* .succeed */.Py(done); +}; +/** + * Finds a `Cause.Done` failure in a cause whose done value is not used. + * + * **When to use** + * + * Use to detect `Cause.Done` completion in a `Cause` when the completion value + * is not part of the downstream logic. + * + * **Details** + * + * Returns a successful `Result` with the done marker when it is the only + * failure, otherwise returns a failed `Result` with the non-done cause. + * + * @see {@link filterDone} for preserving the typed `Cause.Done` value when the done payload matters + * @see {@link filterDoneLeftover} for extracting only the done leftover value + * @see {@link filterNoDone} for the inverse filter that succeeds only when no done failure is present + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneVoid = (/* unused pure expression or super */ null && (filterDone)); +/** + * Keeps a `Cause` only when it contains no `Cause.Done` failures. + * + * **When to use** + * + * Use to select ordinary failure causes for handling while leaving `Cause.Done` + * completion causes outside that handler. + * + * **Details** + * + * Returns a successful `Result` with the cause when every failure is non-done; + * otherwise returns a failed `Result` with the original cause. + * + * @see {@link filterDone} for the inverse typed done filter + * @see {@link filterDoneVoid} for done detection when the payload is not needed + * + * @category filtering + * @since 4.0.0 + */ +const filterNoDone = /*#__PURE__*/(/* unused pure expression or super */ null && (Filter.fromPredicate(cause => cause.reasons.every(failure => !isDoneFailure(failure))))); +/** + * Filters a Cause to extract the leftover value from done errors. + * + * **When to use** + * + * Use to extract only the leftover value carried by a `Cause.Done` completion + * signal. + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneLeftover = cause => { + const done = filterDone(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(done) ? done : _Result_js__rspack_import_3/* .succeed */.Py(done.success.value); +}; +/** + * Converts a `Cause` into an `Exit`, treating `Cause.Done` as successful + * completion. + * + * **When to use** + * + * Use to produce an `Exit` for finalizing a low-level pull workflow when a + * `Cause.Done` signal should be treated as success and any remaining cause + * should fail. + * + * **Details** + * + * If the done signal is the only failure in the cause, its leftover becomes + * the successful value. Otherwise the non-done cause becomes the failure + * cause. + * + * @see {@link filterDone} for extracting the done signal without converting the cause to an `Exit` + * @see {@link matchEffect} for handling `Pull` success, failure, and done outcomes directly + * + * @category converting + * @since 4.0.0 + */ +const doneExitFromCause = cause => { + const halt = filterDone(cause); + return !_Result_js__rspack_import_3/* .isFailure */.N6(halt) ? _Exit_js__rspack_import_4/* .succeed */.Py(halt.success.value) : _Exit_js__rspack_import_4/* .failCause */.AT(halt.failure); +}; +/** + * Pattern matches on a Pull, handling success, failure, and done cases. + * + * **When to use** + * + * Use to handle all three `Pull` outcomes with effectful handlers. + * + * **Example** (Matching Pull outcomes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Pull } from "effect" + * + * const pull = Cause.done("stream ended") + * + * const result = Pull.matchEffect(pull, { + * onSuccess: (value) => Effect.succeed(`Got value: ${value}`), + * onFailure: (cause) => Effect.succeed(`Got error: ${cause}`), + * onDone: (leftover) => Effect.succeed(`Stream halted with: ${leftover}`) + * }) + * + * await Effect.runPromise(result) // => "Stream halted with: stream ended" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, options) => _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu(self, { + onSuccess: options.onSuccess, + onFailure: cause => { + const halt = filterDone(cause); + return !_Result_js__rspack_import_3/* .isFailure */.N6(halt) ? options.onDone(halt.success.value) : options.onFailure(halt.failure); + } +})); +//# sourceMappingURL=Pull.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Dc: filterDone, + Og: isDoneCause, + aU: doneExitFromCause, + m8: catchDone, + tv: matchEffect +}); + + +}, +"./node_modules/effect/dist/Queue.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _MutableList_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/MutableList.js"); +/* import */ var _Pull_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Pull.js"); +/** + * Passes values asynchronously between fibers. + * + * A `Queue` accepts values, hands each value to one consumer in offer + * order, and can complete, fail, interrupt, or shut down. Queues can be bounded + * or unbounded, and bounded queues can suspend, drop, or slide values when + * producers are faster than consumers. + * + * @since 3.8.0 + */ + + + + + + + + + +const TypeId = "~effect/Queue"; +const EnqueueTypeId = "~effect/Queue/Enqueue"; +const DequeueTypeId = "~effect/Queue/Dequeue"; +/** + * Type guard to check if a value is a Queue. + * + * **When to use** + * + * Use to narrow an unknown value to a full `Queue` before passing it to APIs + * that need both offering and taking capabilities. + * + * @see {@link isEnqueue} for checking values that only need write access + * @see {@link isDequeue} for checking values that only need read access + * + * @category guards + * @since 2.0.0 + */ +const isQueue = u => hasProperty(u, TypeId); +/** + * Type guard to check if a value is an Enqueue. + * + * **When to use** + * + * Use to narrow an unknown value before calling queue operations that require + * write-side access. + * + * **Gotchas** + * + * A full `Queue` also satisfies this guard because every queue includes the + * enqueue side. + * + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isDequeue} for checking for the read side of a queue + * @see {@link asEnqueue} for narrowing an existing `Queue` to its write-only interface + * + * @category guards + * @since 2.0.0 + */ +const isEnqueue = u => hasProperty(u, EnqueueTypeId); +/** + * Type guard to check if a value is a Dequeue. + * + * **When to use** + * + * Use to narrow an unknown value before passing it to read-side queue + * operations. + * + * @see {@link Dequeue} for the read-side queue handle checked by this guard + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isEnqueue} for checking for the write side of a queue + * @see {@link asDequeue} for narrowing an existing `Queue` to its read-only interface + * + * @category guards + * @since 2.0.0 + */ +const isDequeue = u => hasProperty(u, DequeueTypeId); +/** + * Converts a `Queue` to its write-only `Enqueue` interface. + * + * **When to use** + * + * Use to expose only the producer side of a `Queue` to code that should offer + * values or signal queue lifecycle. + * + * **Gotchas** + * + * This is a type-level capability restriction. It returns the same queue + * object, so it does not hide read operations at runtime. + * + * @see {@link asDequeue} for exposing only the read side of a `Queue` + * @see {@link Enqueue} for the write-only queue handle returned by this conversion + * + * @category converting + * @since 4.0.0 + */ +const asEnqueue = self => self; +/** + * Narrows a `Queue` to a `Dequeue`, exposing the consumer side of the queue. + * + * **When to use** + * + * Use to pass a queue to code that should consume values while keeping + * producer-side operations out of that code's TypeScript type. + * + * **Gotchas** + * + * This is a type-level narrowing operation. It returns the same queue object + * and does not create a runtime wrapper. + * + * @see {@link asEnqueue} for narrowing a queue to its producer side + * @see {@link Dequeue} for the consumer-side queue handle returned by this function + * + * @category converting + * @since 4.0.0 + */ +const asDequeue = (/* unused pure expression or super */ null && (identity)); +const variance = { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_ +}; +const QueueProto = { + [TypeId]: variance, + [EnqueueTypeId]: variance, + [DequeueTypeId]: variance, + ..._internal_core_js__rspack_import_1/* .PipeInspectableProto */.fU, + toJSON() { + return { + _id: "effect/Queue", + state: this.state._tag, + size: sizeUnsafe(this) + }; + } +}; +/** + * Creates a `Queue` with optional capacity and overflow strategy. + * + * **Details** + * + * By default the queue is unbounded and uses the `"suspend"` strategy. Provide + * `capacity` for a bounded queue and choose `"suspend"`, `"dropping"`, or + * `"sliding"` to control what happens when the queue is full. The returned + * queue can be offered to, taken from, failed, ended, interrupted, or shut down. + * + * **Example** (Creating queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.make() + * + * // add messages to the queue + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offerAll(queue, [3, 4, 5]) + * + * // take messages from the queue + * const messages = yield* Queue.takeAll(queue) + * + * // signal that the queue is done + * yield* Queue.end(queue) + * const done = yield* Effect.flip(Queue.take(queue)) + * + * // signal that another queue has failed + * const failedQueue = yield* Queue.make() + * const failed = yield* Queue.fail(failedQueue, "boom") + * return { messages, done, failed } + * }) + * + * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], done: Cause.Done(), failed: true } + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = options => _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => { + const self = Object.create(QueueProto); + self.dispatcher = fiber.currentDispatcher; + self.capacity = options?.capacity ?? Number.POSITIVE_INFINITY; + self.strategy = options?.strategy ?? "suspend"; + self.messages = _MutableList_js__rspack_import_2/* .make */.L8(); + self.scheduleRunning = false; + self.state = { + _tag: "Open", + takers: new Set(), + offers: new Set(), + awaiters: new Set() + }; + return _internal_effect_js__rspack_import_3/* .succeed */.PyW(self); +}); +/** + * Creates a bounded queue with the specified capacity that uses backpressure strategy. + * + * **Details** + * + * When the queue reaches capacity, producers will be suspended until space becomes available. + * This ensures all messages are processed but may slow down producers. + * + * **Example** (Creating bounded queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // This will succeed as queue has capacity + * yield* Queue.offer(queue, "first") + * yield* Queue.offer(queue, "second") + * + * const size = yield* Queue.size(queue) + * return size + * }) + * + * await Effect.runPromise(program) // => 2 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const bounded = capacity => make({ + capacity +}); +/** + * Creates a bounded queue with sliding strategy. When the queue reaches capacity, + * new elements are added and the oldest elements are dropped. + * + * **When to use** + * + * Use when you need producer offers not to block and can accept dropping the + * oldest messages, such as when maintaining a rolling window of recent values. + * + * **Example** (Creating sliding queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.sliding(3) + * + * // Fill the queue to capacity + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * + * // This will succeed, dropping the oldest element (1) + * yield* Queue.offer(queue, 4) + * + * const all = yield* Queue.takeAll(queue) + * return all + * }) + * + * await Effect.runPromise(program) // => [2, 3, 4] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sliding = capacity => make({ + capacity, + strategy: "sliding" +}); +/** + * Creates a bounded queue with dropping strategy. When the queue reaches capacity, + * new elements are dropped and the offer operation returns false. + * + * **When to use** + * + * Use when you need producer offers not to block while preserving existing + * queued messages, even if new messages may be dropped when the queue is full. + * + * **Example** (Creating dropping queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.dropping(2) + * + * // Fill the queue to capacity + * const success1 = yield* Queue.offer(queue, 1) + * const success2 = yield* Queue.offer(queue, 2) + * + * // This will be dropped + * const success3 = yield* Queue.offer(queue, 3) + * + * const all = yield* Queue.takeAll(queue) + * return [success1, success2, success3, all] + * }) + * + * await Effect.runPromise(program) // => [true, true, false, [1, 2]] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const dropping = capacity => make({ + capacity, + strategy: "dropping" +}); +/** + * Creates an unbounded queue that can grow to any size without blocking producers. + * + * **When to use** + * + * Use when you need producers to add messages without backpressure and accept + * unbounded memory growth. + * + * **Example** (Creating unbounded queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.unbounded() + * + * // Producers can always add messages without blocking + * yield* Queue.offer(queue, "message1") + * yield* Queue.offer(queue, "message2") + * yield* Queue.offerAll(queue, ["message3", "message4", "message5"]) + * + * // Check current size + * const size = yield* Queue.size(queue) + * + * // Take all messages + * const messages = yield* Queue.takeAll(queue) + * return { size, messages } + * }) + * + * await Effect.runPromise(program) // => { size: 5, messages: ["message1", "message2", "message3", "message4", "message5"] } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unbounded = () => make(); +/** + * Adds a message to the queue. Returns `false` if the queue is done. + * + * **Details** + * + * For bounded queues, this operation may suspend if the queue is at capacity, + * depending on the backpressure strategy. For dropping/sliding queues, it may + * return false or succeed immediately by dropping/sliding existing messages. + * + * **Example** (Offering a value) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Successfully add messages to queue + * const success1 = yield* Queue.offer(queue, 1) + * const success2 = yield* Queue.offer(queue, 2) + * + * // Queue state + * const size = yield* Queue.size(queue) + * return { offered: [success1, success2], size } + * }) + * + * await Effect.runPromise(program) // => { offered: [true, true], size: 2 } + * ``` + * + * @category offering + * @since 2.0.0 + */ +const offer = (self, message) => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (self.state._tag !== "Open") { + return exitFalse; + } else if (self.messages.length >= self.capacity) { + switch (self.strategy) { + case "dropping": + return exitFalse; + case "suspend": + if (self.capacity <= 0 && self.state.takers.size > 0) { + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + releaseTakers(self); + return exitTrue; + } + return offerRemainingSingle(self, message); + case "sliding": + _MutableList_js__rspack_import_2/* .take */.s(self.messages); + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + return exitTrue; + } + } + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + scheduleReleaseTaker(self); + return exitTrue; +}); +/** + * Adds a message to the queue synchronously. Returns `false` if the queue is done. + * + * **When to use** + * + * Use when you are already in synchronous queue internals or a performance + * boundary where wrapping the mutation in `Effect` is intentionally avoided. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * Use this only when you're certain about the synchronous nature of the operation. + * + * **Example** (Offering a value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * // Create a queue effect and extract the queue for unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Add messages synchronously using unsafe API + * const success1 = Queue.offerUnsafe(queue, 1) + * const success2 = Queue.offerUnsafe(queue, 2) + * + * // Check current size + * const size = Queue.sizeUnsafe(queue) + * return { offered: [success1, success2], size } + * }) + * + * await Effect.runPromise(program) // => { offered: [true, true], size: 2 } + * ``` + * + * @category offering + * @since 4.0.0 + */ +const offerUnsafe = (self, message) => { + if (self.state._tag !== "Open") { + return false; + } else if (self.messages.length >= self.capacity) { + if (self.strategy === "sliding") { + MutableList.take(self.messages); + MutableList.append(self.messages, message); + return true; + } else if (self.capacity <= 0 && self.state.takers.size > 0) { + MutableList.append(self.messages, message); + releaseTakers(self); + return true; + } + return false; + } + MutableList.append(self.messages, message); + scheduleReleaseTaker(self); + return true; +}; +/** + * Adds multiple messages to the queue. Returns the remaining messages that + * were not added. + * + * **When to use** + * + * Use when producers can submit a batch at once and need to know which messages + * did not fit under the queue's capacity strategy. + * + * **Details** + * + * For bounded queues, this operation may suspend if the queue doesn't have + * enough capacity. The operation returns an array of messages that couldn't + * be added (empty array means all messages were successfully added). + * + * **Example** (Offering multiple values) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.dropping(3) + * + * // Try to add more messages than capacity without suspending + * const remaining1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * return remaining1 + * }) + * + * await Effect.runPromise(program) // => [4, 5] + * ``` + * + * @category offering + * @since 2.0.0 + */ +const offerAll = (self, messages) => internalEffect.suspend(() => { + if (self.state._tag !== "Open") { + return internalEffect.succeed(Arr.fromIterable(messages)); + } + const remaining = offerAllUnsafe(self, messages); + if (remaining.length === 0) { + return core.exitSucceed([]); + } else if (self.strategy === "dropping") { + return internalEffect.succeed(remaining); + } + return offerRemainingArray(self, remaining); +}); +/** + * Adds multiple messages to the queue synchronously. Returns the remaining messages that + * were not added. + * + * **When to use** + * + * Use when queue internals or a performance boundary need a synchronous batch + * offer and can handle any messages that do not fit. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Offering multiple values synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * // Create a bounded queue and use unsafe API + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Try to add 5 messages to capacity-3 queue using unsafe API + * const remaining = Queue.offerAllUnsafe(queue, [1, 2, 3, 4, 5]) + * + * // Check what's in the queue + * const size = Queue.sizeUnsafe(queue) + * return { remaining, size } + * }) + * + * await Effect.runPromise(program) // => { remaining: [4, 5], size: 3 } + * ``` + * + * @category offering + * @since 4.0.0 + */ +const offerAllUnsafe = (self, messages) => { + if (self.state._tag !== "Open") { + return Arr.fromIterable(messages); + } else if (self.capacity === Number.POSITIVE_INFINITY || self.strategy === "sliding") { + MutableList.appendAll(self.messages, messages); + if (self.strategy === "sliding") { + MutableList.takeN(self.messages, self.messages.length - self.capacity); + } + scheduleReleaseTaker(self); + return []; + } + const free = self.capacity <= 0 ? self.state.takers.size : self.capacity - self.messages.length; + if (free === 0) { + return Arr.fromIterable(messages); + } + const remaining = []; + let i = 0; + for (const message of messages) { + if (i < free) { + MutableList.append(self.messages, message); + } else { + remaining.push(message); + } + i++; + } + scheduleReleaseTaker(self); + return remaining; +}; +/** + * Fails the queue with an error. If the queue is already done, `false` is + * returned. + * + * **Example** (Failing queues with an error) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Fail the queue with an error + * const failed = yield* Queue.fail(queue, "Something went wrong") + * + * // Taking from the failed queue fails with the error + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Something went wrong")] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const fail = (self, error) => failCause(self, core.causeFail(error)); +/** + * Fails the queue with a cause. If the queue is already done, `false` is + * returned. + * + * **Example** (Failing queues with a cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create a cause and fail the queue + * const cause = Cause.fail("Queue processing failed") + * const failed = yield* Queue.failCause(queue, cause) + * + * // The queue is now done with the specified failure cause + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Queue processing failed"))] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const failCause = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, cause) => _internal_effect_js__rspack_import_3/* .sync */.OH5(() => failCauseUnsafe(self, cause))); +/** + * Fails the queue with a cause synchronously. If the queue is already done, `false` is + * returned. + * + * **When to use** + * + * Use when queue completion must be driven from synchronous internals while + * preserving the full failure `Cause`. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Failing queues with a cause synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create a cause and fail the queue synchronously + * const cause = Cause.fail("Processing error") + * const failed = Queue.failCauseUnsafe(queue, cause) + * + * // The queue is now done with the specified failure cause + * const exit = Queue.takeUnsafe(queue) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Processing error"))] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const failCauseUnsafe = (self, cause) => { + if (self.state._tag !== "Open") { + return false; + } + const exit = _internal_core_js__rspack_import_1/* .exitFailCause */.cb(cause); + const fail = _internal_effect_js__rspack_import_3/* .exitZipRight */.il9(exit, exitFailDone); + if (self.state.offers.size === 0 && self.messages.length === 0) { + finalize(self, fail); + return true; + } + self.state = { + ...self.state, + _tag: "Closing", + exit: fail + }; + return true; +}; +/** + * Signals queue completion. + * + * **When to use** + * + * Use to stop accepting new offers while allowing already queued messages to be + * consumed. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Example** (Ending queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Signal completion - no more messages will be accepted + * const ended = yield* Queue.end(queue) + * + * // Trying to offer more messages will return false + * const offerResult = yield* Queue.offer(queue, 3) + * + * // But we can still take existing messages + * const message = yield* Queue.take(queue) + * return [ended, offerResult, message] + * }) + * + * await Effect.runPromise(program) // => [true, false, 1] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const end = self => failCause(self, core.causeFail(core.Done())); +/** + * Signals queue completion synchronously. + * + * **When to use** + * + * Use when implementing low-level queue integrations that must complete a queue + * without wrapping the operation in `Effect`. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Ending queues synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * // Create a queue and use unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * + * // End the queue synchronously + * const ended = Queue.endUnsafe(queue) + * + * // Existing messages can still be consumed while the queue is closing + * const states = [queue.state._tag] + * + * Queue.takeUnsafe(queue) + * Queue.takeUnsafe(queue) + * + * // After buffered messages are consumed, the queue is done + * states.push(queue.state._tag) + * return { ended, states } + * }) + * + * await Effect.runPromise(program) // => { ended: true, states: ["Closing", "Done"] } + * ``` + * + * @category completion + * @since 4.0.0 + */ +const endUnsafe = self => failCauseUnsafe(self, core.causeFail(core.Done())); +/** + * Interrupts the queue gracefully, transitioning it to a closing state. + * + * **Details** + * + * This operation stops accepting new offers but allows existing messages to be consumed. + * Once all messages are drained, the queue transitions to the Done state with an interrupt cause. + * + * **Example** (Interrupting queues gracefully) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Interrupt gracefully - no more offers accepted, but messages can be consumed + * const interrupted = yield* Queue.interrupt(queue) + * + * // Trying to offer more messages will return false + * const offerResult = yield* Queue.offer(queue, 3) + * + * // But we can still take existing messages + * const message1 = yield* Queue.take(queue) + * + * const message2 = yield* Queue.take(queue) + * + * // After all messages are consumed, queue is done + * const isDone = queue.state._tag === "Done" + * return { interrupted, offerResult, messages: [message1, message2], isDone } + * }) + * + * await Effect.runPromise(program) // => { interrupted: true, offerResult: false, messages: [1, 2], isDone: true } + * ``` + * + * @category completion + * @since 4.0.0 + */ +const interrupt = self => core.withFiber(fiber => failCause(self, internalEffect.causeInterrupt(fiber.id))); +/** + * Shuts down the queue immediately, discarding buffered messages and resuming + * pending operations. + * + * **Details** + * + * The operation is idempotent and returns `true`, including when the queue has + * already been shut down or completed. + * + * **Example** (Shutting down queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(2) + * + * // Add messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Shutdown clears buffered messages and prevents further offers + * const wasShutdown = yield* Queue.shutdown(queue) + * + * // Queue is now done and cleared + * const size = yield* Queue.size(queue) + * return { wasShutdown, size } + * }) + * + * await Effect.runPromise(program) // => { wasShutdown: true, size: 0 } + * ``` + * + * @category completion + * @since 2.0.0 + */ +const shutdown = self => _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag === "Done") { + return true; + } + _MutableList_js__rspack_import_2/* .clear */.IU(self.messages); + const offers = self.state.offers; + finalize(self, self.state._tag === "Open" ? exitInterrupt : self.state.exit); + if (offers.size > 0) { + for (const entry of offers) { + if (entry._tag === "Single") { + entry.resume(exitFalse); + } else { + entry.resume(_internal_core_js__rspack_import_1/* .exitSucceed */.xt(entry.remaining.slice(entry.offset))); + } + } + offers.clear(); + } + return true; +}); +/** + * Takes and returns all currently buffered messages without waiting for more. + * + * **Details** + * + * Returns an empty array when the queue is empty or has completed normally. If + * the queue has failed, the effect fails with the queue's error. + * + * **Example** (Clearing queued values) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Clear all messages from the queue + * const messages = yield* Queue.clear(queue) + * + * // Queue is now empty + * const size = yield* Queue.size(queue) + * + * // Clearing empty queue returns empty array + * const empty = yield* Queue.clear(queue) + * return { messages, size, empty } + * }) + * + * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], size: 0, empty: [] } + * ``` + * + * @category taking + * @since 4.0.0 + */ +const clear = self => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (self.state._tag === "Done") { + if (_Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause)) { + return _internal_effect_js__rspack_import_3/* .succeed */.PyW([]); + } + return self.state.exit; + } + const messages = takeAllUnsafe(self); + releaseCapacity(self); + return _internal_effect_js__rspack_import_3/* .succeed */.PyW(messages); +}); +/** + * Takes all currently available messages, waiting until at least one message + * is available when the queue is empty. + * + * **When to use** + * + * Use when consumers should process the next non-empty batch of buffered + * messages instead of repeatedly taking one message at a time. + * + * **Details** + * + * Returns a non-empty array. If the queue completes or fails before a message + * can be taken, the effect fails with the queue's terminal error. + * + * **Example** (Taking all available values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Take all available messages + * const messages1 = yield* Queue.takeAll(queue) + * return messages1 + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeAll = self => takeBetween(self, 1, Number.POSITIVE_INFINITY); +/** + * Takes all messages from the queue, until the queue has errored or is done. + * + * **Example** (Collecting values until completion) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * yield* Queue.end(queue) + * + * // Collect all available messages + * return yield* Queue.collect(queue) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category taking + * @since 4.0.0 + */ +const collect = self => internalEffect.suspend(() => { + const out = Arr.empty(); + return internalEffect.as(Pull.catchDone(internalEffect.whileLoop({ + while: constTrue, + body: constant(takeAll(self)), + step(items) { + for (let i = 0; i < items.length; i++) { + out.push(items[i]); + } + } + }), () => internalEffect.void), out); +}); +/** + * Takes up to `n` messages from the queue. + * + * **Details** + * + * The operation may wait until enough messages are available to satisfy the + * queue's batching rules. If `n` is less than or equal to zero, it succeeds + * with an empty array. If the queue completes or fails before messages can be + * taken, the effect fails with the queue's terminal error. + * + * **Example** (Taking a fixed number of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7]) + * + * // Take exactly 3 messages + * const first3 = yield* Queue.takeN(queue, 3) + * + * // Take exactly 2 more messages + * const next2 = yield* Queue.takeN(queue, 2) + * + * // Take remaining messages + * const remaining = yield* Queue.takeN(queue, 2) + * return [first3, next2, remaining] + * }) + * + * await Effect.runPromise(program) // => [[1, 2, 3], [4, 5], [6, 7]] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeN = (self, n) => takeBetween(self, n, n); +/** + * Takes between `min` and `max` messages from the queue. + * + * **Details** + * + * The operation waits when fewer than the required minimum messages are + * available. It returns at most `max` messages. If the queue completes or fails + * before the minimum can be satisfied, the effect fails with the queue's + * terminal error. + * + * **Example** (Taking a bounded batch of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7, 8]) + * + * // Take between 2 and 5 messages + * const batch1 = yield* Queue.takeBetween(queue, 2, 5) + * + * // Take between 1 and 10 messages (but only 3 remain) + * const batch2 = yield* Queue.takeBetween(queue, 1, 10) + * + * // No more messages available, will wait or return done + * // const batch3 = yield* Queue.takeBetween(queue, 1, 3) + * return [batch1, batch2] + * }) + * + * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [6, 7, 8]] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeBetween = (self, min, max) => internalEffect.suspend(() => takeBetweenUnsafe(self, min, max) ?? internalEffect.andThen(awaitTake(self), takeBetween(self, 1, max))); +/** + * Takes a single message from the queue, or wait for a message to be + * available. + * + * **Details** + * + * If the queue is done, it will fail with `Done`. If the + * queue fails, the Effect will fail with the error. + * + * **Example** (Taking one value) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Add some messages + * yield* Queue.offer(queue, "first") + * yield* Queue.offer(queue, "second") + * + * // Take messages one by one + * const msg1 = yield* Queue.take(queue) + * const msg2 = yield* Queue.take(queue) + * + * // End the queue + * yield* Queue.end(queue) + * + * // Taking from an ended queue fails with Done + * const result = yield* Effect.exit(Queue.take(queue)) + * return [[msg1, msg2], result] + * }) + * + * await Effect.runPromise(program) // => [["first", "second"], Exit.fail(Cause.Done())] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const take = self => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => takeUnsafe(self) ?? _internal_effect_js__rspack_import_3/* .andThen */.hgn(awaitTake(self), take(self))); +/** + * Attempts to take one item from the queue without waiting. + * + * **Details** + * + * Returns `Option.some` when an item is immediately available. Returns + * `Option.none` when no item is available, when the queue is done, or when the + * immediate take observes a queue failure. + * + * **Example** (Polling without blocking) + * + * ```ts import.meta.vitest + * import { Effect, Option, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Poll returns Option.none if empty + * const maybe1 = yield* Queue.poll(queue) + * + * // Add an item + * yield* Queue.offer(queue, 42) + * + * // Poll returns Option.some with the item + * const maybe2 = yield* Queue.poll(queue) + * return [maybe1, maybe2] + * }) + * + * await Effect.runPromise(program) // => [Option.none(), Option.some(42)] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const poll = self => internalEffect.suspend(() => { + const result = takeUnsafe(self); + if (result === undefined) { + return internalEffect.succeed(Option.none()); + } + if (result._tag === "Success") { + return internalEffect.succeed(Option.some(result.value)); + } + return internalEffect.succeed(Option.none()); +}); +/** + * Peeks at the next item without removing it. + * + * **Details** + * + * Blocks until an item is available. If the queue is done or fails, the error is propagated. + * + * **Example** (Peeking at the next value) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * yield* Queue.offer(queue, 42) + * + * // Peek at the next item without removing it + * const item = yield* Queue.peek(queue) + * return item + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category taking + * @since 4.0.0 + */ +const peek = self => internalEffect.suspend(() => { + if (self.state._tag === "Done") { + return self.state.exit; + } + if (self.messages.length > 0 && self.messages.head) { + return internalEffect.succeed(self.messages.head.array[self.messages.head.offset]); + } + return internalEffect.andThen(awaitTake(self), peek(self)); +}); +/** + * Attempts to take one message from the queue synchronously. + * + * **When to use** + * + * Use when polling queue internals must not suspend or register a waiting taker, + * and `undefined` is an acceptable result for an empty queue. + * + * **Details** + * + * Returns an `Exit` for an immediately available message or for the queue's + * terminal state. Returns `undefined` when no message is immediately available. + * This operation does not wait or register a taker. + * + * **Example** (Taking one value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Queue } from "effect" + * + * // Create a queue and use unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * + * // Take a message synchronously + * const result1 = Queue.takeUnsafe(queue) + * + * const result2 = Queue.takeUnsafe(queue) + * + * // No more messages - returns undefined + * const result3 = Queue.takeUnsafe(queue) + * return [result1, result2, result3] + * }) + * + * await Effect.runPromise(program) // => [Exit.succeed(1), Exit.succeed(2), undefined] + * ``` + * + * @category taking + * @since 4.0.0 + */ +const takeUnsafe = self => { + if (self.state._tag === "Done") { + return self.state.exit; + } + if (self.messages.length > 0) { + const message = _MutableList_js__rspack_import_2/* .take */.s(self.messages); + releaseCapacity(self); + return _internal_core_js__rspack_import_1/* .exitSucceed */.xt(message); + } else if (self.capacity <= 0 && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const message = _MutableList_js__rspack_import_2/* .take */.s(self.messages); + releaseCapacity(self); + return _internal_core_js__rspack_import_1/* .exitSucceed */.xt(message); + } + return undefined; +}; +const await_ = self => internalEffect.callback(resume => { + const awaiter = effect => resume(Pull.catchDone(effect, () => internalEffect.exitVoid)); + if (self.state._tag === "Done") { + return awaiter(self.state.exit); + } + self.state.awaiters.add(awaiter); + return internalEffect.sync(() => { + if (self.state._tag !== "Done") { + self.state.awaiters.delete(awaiter); + } + }); +}); + +/** + * Returns the current number of buffered messages in the queue. + * + * **Details** + * + * After `end`, a queue remains `Closing` while buffered messages are drained, + * and its size continues to include those messages. A `Done` queue reports a + * size of `0`. + * + * **Example** (Checking queue size) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Check size of empty queue + * const size1 = yield* Queue.size(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Check size after adding messages + * const size2 = yield* Queue.size(queue) + * + * // End the queue + * yield* Queue.end(queue) + * + * // Ending retains the buffered size while the queue is Closing + * const size3 = yield* Queue.size(queue) + * return [size1, size2, size3] + * }) + * + * await Effect.runPromise(program) // => [0, 5, 5] + * ``` + * + * @category sizes + * @since 2.0.0 + */ +const size = self => internalEffect.sync(() => sizeUnsafe(self)); +/** + * Checks whether the queue is full. + * + * **Example** (Checking if queues are full) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * const before = yield* Queue.isFull(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3]) + * + * const after = yield* Queue.isFull(queue) + * return [before, after] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFull = self => internalEffect.sync(() => isFullUnsafe(self)); +/** + * Returns the current number of buffered messages in the queue synchronously. + * + * **When to use** + * + * Use when you need an immediate `Queue` size snapshot for diagnostics or + * internals and do not need the read wrapped in `Effect`. + * + * **Details** + * + * After `endUnsafe`, a queue remains `Closing` while buffered messages are + * drained, and its size continues to include those messages. A `Done` queue + * reports a size of `0`. This unsafe operation reads the queue state directly + * without Effect wrapping. + * + * **Example** (Checking queue size synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Check size of empty queue + * const size1 = Queue.sizeUnsafe(queue) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * Queue.offerUnsafe(queue, 3) + * + * // Check size after adding messages + * const size2 = Queue.sizeUnsafe(queue) + * + * // End the queue + * Queue.endUnsafe(queue) + * + * // Ending retains the buffered size while the queue is Closing + * const size3 = Queue.sizeUnsafe(queue) + * return [size1, size2, size3] + * }) + * + * await Effect.runPromise(program) // => [0, 3, 3] + * ``` + * + * @category sizes + * @since 4.0.0 + */ +const sizeUnsafe = self => self.state._tag === "Done" ? 0 : self.messages.length; +/** + * Checks whether the queue is full synchronously. + * + * **When to use** + * + * Use when an immediate `Queue` capacity snapshot is needed outside effectful + * code and racing queue changes are acceptable. + * + * **Example** (Checking fullness synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * const before = Queue.isFullUnsafe(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3]) + * + * const after = Queue.isFullUnsafe(queue) + * return [before, after] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isFullUnsafe = self => sizeUnsafe(self) === self.capacity; +/** + * Runs an `Effect` into a `Queue`, where success ends the queue and failure + * fails the queue. + * + * **Example** (Running effects into queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create an effect that succeeds + * const dataProcessing = Effect.gen(function*() { + * yield* Effect.yieldNow + * return "Processing completed successfully" + * }) + * + * // Pipe the effect into the queue + * // If dataProcessing succeeds, queue ends successfully + * // If dataProcessing fails, queue fails with the error + * const effectIntoQueue = Queue.into(queue)(dataProcessing) + * + * const wasCompleted = yield* effectIntoQueue + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [wasCompleted, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail(Cause.Done())] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const into = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, self) => internalEffect.uninterruptibleMask(restore => internalEffect.matchCauseEffect(restore(effect), { + onFailure: cause => failCause(self, cause), + onSuccess: _ => end(self) +}))))); +// ----------------------------------------------------------------------------- +// internals +// ----------------------------------------------------------------------------- +// +const exitFalse = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitSucceed */.xt(false); +const exitTrue = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitSucceed */.xt(true); +const exitFailDone = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitFail */.Rk(/*#__PURE__*/_internal_core_js__rspack_import_1/* .Done */.RS()); +const exitInterrupt = /*#__PURE__*/_internal_effect_js__rspack_import_3/* .exitInterrupt */._sz(); +const releaseTakers = self => { + self.scheduleRunning = false; + if (self.state._tag === "Done" || self.state.takers.size === 0) { + return; + } + for (const taker of self.state.takers) { + self.state.takers.delete(taker); + taker(_internal_effect_js__rspack_import_3/* .exitVoid */.x5l); + if (self.messages.length === 0) { + break; + } + } +}; +const scheduleReleaseTaker = self => { + if (self.scheduleRunning || self.state._tag === "Done" || self.state.takers.size === 0) { + return; + } + self.scheduleRunning = true; + self.dispatcher.scheduleTask(() => releaseTakers(self), 0); +}; +const takeBetweenUnsafe = (self, min, max) => { + if (self.state._tag === "Done") { + return self.state.exit; + } else if (max <= 0 || min <= 0) { + return core.exitSucceed([]); + } else if (self.capacity <= 0 && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const messages = [MutableList.take(self.messages)]; + releaseCapacity(self); + return core.exitSucceed(messages); + } + min = Math.min(min, self.capacity || 1); + if (min <= self.messages.length) { + const messages = MutableList.takeN(self.messages, max); + releaseCapacity(self); + return core.exitSucceed(messages); + } +}; +const offerRemainingSingle = (self, message) => { + return _internal_effect_js__rspack_import_3/* .callback */.E2r(resume => { + if (self.state._tag !== "Open") { + return resume(exitFalse); + } + const entry = { + _tag: "Single", + message, + resume + }; + self.state.offers.add(entry); + return _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag === "Open") { + self.state.offers.delete(entry); + } + }); + }); +}; +const offerRemainingArray = (self, remaining) => { + return internalEffect.callback(resume => { + if (self.state._tag !== "Open") { + return resume(core.exitSucceed(remaining)); + } + const entry = { + _tag: "Array", + remaining, + offset: 0, + resume + }; + self.state.offers.add(entry); + return internalEffect.sync(() => { + if (self.state._tag === "Open") { + self.state.offers.delete(entry); + } + }); + }); +}; +const releaseCapacity = self => { + if (self.state._tag === "Done") { + return _Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause); + } else if (self.state.offers.size === 0) { + if (self.state._tag === "Closing" && self.messages.length === 0) { + finalize(self, self.state.exit); + return _Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause); + } + return false; + } + let n = self.capacity - self.messages.length; + for (const entry of self.state.offers) { + if (n === 0) break;else if (entry._tag === "Single") { + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, entry.message); + n--; + entry.resume(exitTrue); + self.state.offers.delete(entry); + } else { + for (; entry.offset < entry.remaining.length; entry.offset++) { + if (n === 0) return false; + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, entry.remaining[entry.offset]); + n--; + } + entry.resume(_internal_core_js__rspack_import_1/* .exitSucceed */.xt([])); + self.state.offers.delete(entry); + } + } + return false; +}; +const awaitTake = self => _internal_effect_js__rspack_import_3/* .callback */.E2r(resume => { + if (self.state._tag === "Done") { + return resume(self.state.exit); + } + self.state.takers.add(resume); + return _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag !== "Done") { + self.state.takers.delete(resume); + } + }); +}); +const takeAllUnsafe = self => { + if (self.messages.length > 0) { + const messages = _MutableList_js__rspack_import_2/* .takeAll */.h0(self.messages); + releaseCapacity(self); + return messages; + } else if (self.state._tag !== "Done" && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const messages = [_MutableList_js__rspack_import_2/* .take */.s(self.messages)]; + releaseCapacity(self); + return messages; + } + return []; +}; +const finalize = (self, exit) => { + if (self.state._tag === "Done") { + return; + } + const openState = self.state; + self.state = { + _tag: "Done", + exit + }; + for (const taker of openState.takers) { + taker(exit); + } + openState.takers.clear(); + for (const awaiter of openState.awaiters) { + awaiter(exit); + } + openState.awaiters.clear(); +}; +//# sourceMappingURL=Queue.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + AT: failCause, + IU: clear, + Mm: bounded, + _1: failCauseUnsafe, + n_: shutdown, + s: take, + x: offer +}); + + +}, +"./node_modules/effect/dist/Record.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_record_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/** + * Works with plain JavaScript records as immutable key/value dictionaries. + * + * A record is an object whose keys are strings or symbols. This module includes + * helpers for construction, lookup, updates, mapping, filtering, folding, + * set-like combination, and typed conversions between records and iterable + * entries. Helpers that change values return new records instead of mutating the + * input. + * + * @since 2.0.0 + */ + + + + + + +/** + * Creates a new, empty record. + * + * **Example** (Creating an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * // Create an empty record + * const emptyRecord = Record.empty() + * emptyRecord // => {} + * + * // The type ensures type safety for future operations + * Record.set(emptyRecord, "count", 42) // => { count: 42 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => ({}); +/** + * Determines if a mutable record is empty. + * + * **Example** (Checking for an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyRecord({}) // => true + * Record.isEmptyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyRecord = self => Object.keys(self).length === 0; +/** + * Determines if a readonly record is empty. + * + * **Example** (Checking for an empty readonly record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyReadonlyRecord({}) // => true + * Record.isEmptyReadonlyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyReadonlyRecord = (/* unused pure expression or super */ null && (isEmptyRecord)); +/** + * Takes an iterable and a projection function and returns a record. + * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. + * + * **Example** (Building a record from mapped iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromIterableWith([1, 2, 3, 4], (a) => [String(a), a * 2]) // => { "1": 2, "2": 4, "3": 6, "4": 8 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const a of self) { + const [k, b] = f(a); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Creates a new record from an iterable, utilizing the provided function to determine the key for each element. + * + * **Example** (Building a record keyed by iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const users = [ + * { id: "2", name: "name2" }, + * { id: "1", name: "name1" } + * ] + * + * Record.fromIterableBy( + * users, + * (user) => user.id + * ) // => { "1": { id: "1", name: "name1" }, "2": { id: "2", name: "name2" } } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (items, f) => fromIterableWith(items, a => [f(a), a])))); +/** + * Builds a record from an iterable of key-value pairs. + * + * **Details** + * + * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the + * previous ones. So the resulting record will only have the value of the last occurrence of each key. + * + * **Example** (Building a record from entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromEntries([["a", 1], ["b", 2]]) // => { a: 1, b: 2 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEntries = Object.fromEntries; +/** + * Transforms the values of a record into an `Array` with a custom mapping function. + * + * **Example** (Collecting mapped record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.collect(x, (key, n) => [key, n]) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const collect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + const out = []; + for (const key of keys(self)) { + out.push(f(key, self[key])); + } + return out; +}); +/** + * Takes a record and returns an array of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.toEntries(x) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const toEntries = /*#__PURE__*/collect((key, value) => [key, value]); +/** + * Returns the number of key/value pairs in a record. + * + * **Example** (Getting the record size) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.size({ a: "a", b: 1, c: true }) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => keys(self).length; +/** + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.has({ a: 1, b: 2 }, "a") // => true + * Record.has(Record.empty(), "c") // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const has = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key)))); +/** + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) + * + * ```ts import.meta.vitest + * import { Option, Record as R } from "effect" + * + * const person: Record = { name: "John Doe", age: 35 } + * + * R.get(person, "name") // => Option.some("John Doe") + * R.get(person, "email") // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key) ? Option.some(self[key]) : Option.none()))); +/** + * Applies a function to the element at the specified key safely, creating a new record, + * or return `Option.none()` if the key doesn't exist. + * + * **Example** (Modifying a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const f = (x: number) => x * 2 + * + * const input: Record = { a: 3 } + * + * Record.modify(input, "a", f) // => Option.some({ a: 6 }) + * Record.modify(input, "b", f) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, f) => { + if (!has(self, key)) return Option.none(); + return Option.some({ + ...self, + [key]: f(self[key]) + }); +}))); +/** + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.replace({ a: 1, b: 2, c: 3 }, "a", 10) // => Option.some({ a: 10, b: 2, c: 3 }) + * Record.replace(Record.empty(), "a", 10) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, b) => modify(self, key, () => b)))); +/** + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.remove({ a: 1, b: 2 }, "a") // => { b: 2 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => { + if (!has(self, key)) { + return { + ...self + }; + } + const out = { + ...self + }; + delete out[key]; + return out; +}))); +/** + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` + * of a tuple with the value and the record with the removed property. + * If the key is not present, returns `Option.none()`. + * + * **Example** (Popping a value and removing its key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const input: Record = { a: 1, b: 2 } + * + * Record.pop(input, "a") // => Option.some([1, { b: 2 }]) + * Record.pop(input, "c") // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const pop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => has(self, key) ? Option.some([self[key], remove(self, key)]) : Option.none()))); +/** + * Maps a record into another record by applying a transformation function to each of its values. + * + * **Example** (Mapping record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const f = (n: number) => `-${n}` + * + * Record.map({ a: 3, b: 5 }, f) // => { a: "-3", b: "-5" } + * + * const g = (n: number, key: string) => `${key.toUpperCase()}-${n}` + * + * Record.map({ a: 3, b: 5 }, g) // => { a: "A-3", b: "B-5" } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = { + ...self + }; + for (const key of keys(self)) { + InternalRecord.assignProperty(out, key, f(self[key], key)); + } + return out; +}))); +/** + * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. + * + * **Example** (Mapping record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()) // => { A: 3, B: 5 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapKeys = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const a = self[key]; + InternalRecord.assignProperty(out, f(key, a), a); + } + return out; +}))); +/** + * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. + * + * **Example** (Mapping record entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]) // => { A: 4, B: 6 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapEntries = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const [k, b] = f(self[key], key); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Transforms a record by applying the function `f` to each key and value in the original record. + * If the function succeeds, the key-value pair is included in the output record. + * + * **Example** (Filtering and mapping with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (a: number, key: string) => a > 2 ? Result.succeed(a * 2) : Result.failVoid + * Record.filterMap(x, f) // => { c: 6 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const key of keys(self)) { + const result = f(self[key], key); + if (R.isSuccess(result)) { + InternalRecord.assignProperty(out, key, result.success); + } + } + return out; +}))); +/** + * Selects properties from a record whose values match the given predicate. + * + * **Example** (Filtering record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3, d: 4 } + * Record.filter(x, (n) => n > 2) // => { c: 3, d: 4 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const out = empty(); + for (const key of keys(self)) { + if (predicate(self[key], key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + return out; +}))); +/** + * Returns a new record containing only the `Some` values from a record of + * `Option` values, preserving the original keys. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = empty(); + for (const key of keys(self)) { + const option = self[key]; + if (Option.isSome(option)) { + InternalRecord.assignProperty(out, key, option.value); + } + } + return out; +}; +/** + * Returns a new record containing only the `Err` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result failures) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getFailures({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { b: "err" } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isFailure(value)) { + InternalRecord.assignProperty(out, key, value.failure); + } + } + return out; +}; +/** + * Returns a new record containing only the `Ok` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result successes) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getSuccesses({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isSuccess(value)) { + InternalRecord.assignProperty(out, key, value.success); + } + } + return out; +}; +/** + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (n: number) => (n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) + * Record.partition(x, f) // => [{ a: 1, c: 3 }, { b: 2 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const left = empty(); + const right = empty(); + for (const key of keys(self)) { + const e = f(self[key], key); + if (R.isFailure(e)) { + InternalRecord.assignProperty(left, key, e.failure); + } else { + InternalRecord.assignProperty(right, key, e.success); + } + } + return [left, right]; +}))); +/** + * Partitions a record of `Result` values into two separate records, + * one with the `Err` values and one with the `Ok` values. + * + * **Example** (Separating Result values) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.separate({ a: Result.fail("e"), b: Result.succeed(1) }) // => [{ a: "e" }, { b: 1 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Retrieves the keys of a given record as an array. + * + * **Example** (Getting record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.keys({ a: 1, b: 2, c: 3 }) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const keys = self => Object.keys(self); +/** + * Retrieves the values of a given record as an array. + * + * **Example** (Getting record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const values = self => collect(self, (_, a) => a); +/** + * Adds a new key-value pair or update an existing key's value in a record. + * + * **Example** (Setting a record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.set("a", 5)({ a: 1, b: 2 }) // => { a: 5, b: 2 } + * Record.set("c", 5)({ a: 1, b: 2 }) // => { a: 1, b: 2, c: 5 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const set = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, value) => { + return { + ...self, + [key]: value + }; +}))); +/** + * Mutates a record by assigning a value to a property. + * + * **When to use** + * + * Use when incrementally constructing a new record and copying it for every + * property would be unnecessary. + * + * **Gotchas** + * + * This function mutates `self`. When `key` is `"__proto__"`, it creates an + * own data property instead of changing the object's prototype. + * + * **Example** (Assigning an external key safely) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const key: string = "__proto__" // Assume this comes from external input + * const value = { polluted: true } + * + * const unsafe: Record = {} + * unsafe[key] = value + * Object.getPrototypeOf(unsafe) === value // => true + * + * const safe: Record = {} + * Record.assignProperty(safe, key, value) + * Object.getPrototypeOf(safe) === Object.prototype // => true + * safe[key] === value // => true + * ``` + * + * @see {@link set} for an immutable update + * @category mutations + * @since 4.0.0 + */ +const assignProperty = _internal_record_js__rspack_import_1/* .assignProperty */.x; +/** + * Checks whether all the keys and values in one record are also found in another record. + * Uses the provided equivalence function to compare values. + * + * **Example** (Checking subrecords with a custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Record } from "effect" + * + * const isSubrecord = Record.isSubrecordBy( + * Equivalence.make((self, that) => self.toLowerCase() === that.toLowerCase()) + * ) + * + * const required: Record.ReadonlyRecord = { role: "Admin" } + * const available: Record.ReadonlyRecord = { + * role: "admin", + * status: "active" + * } + * + * isSubrecord(required, available) // => true + * isSubrecord({ role: "Admin", status: "inactive" }, available) // => false + * isSubrecord(required, { role: "editor", status: "active" }) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecordBy = equivalence => dual(2, (self, that) => { + for (const key of keys(self)) { + if (!has(that, key) || !equivalence(self[key], that[key])) { + return false; + } + } + return true; +}); +/** + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isSubrecord({ a: 1 } as Record, { a: 1, b: 2 }) // => true + * Record.isSubrecord({ a: 1, b: 2 }, { a: 1 } as Record) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecord = /*#__PURE__*/(/* unused pure expression or super */ null && (isSubrecordBy(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.reduce({ a: 1, b: 2, c: 3 }, 0, (acc, value) => acc + value) // => 6 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, zero, f) => { + let out = zero; + for (const key of keys(self)) { + out = f(out, self[key], key); + } + return out; +}))); +/** + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.every({ a: 1, b: 2 }, (n) => n > 0) // => true + * Record.every({ a: 1, b: -1 }, (n) => n > 0) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => { + for (const key of keys(self)) { + if (!refinement(self[key], key)) { + return false; + } + } + return true; +}))); +/** + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.some({ a: 1, b: 2 }, (n) => n > 1) // => true + * Record.some({ a: 1, b: 2 }, (n) => n > 2) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + for (const key of keys(self)) { + if (predicate(self[key], key)) { + return true; + } + } + return false; +}))); +/** + * Merges two records, preserving entries that exist in either of the records. + * For keys that exist in both records, the provided combine function is used to merge the values. + * + * **Example** (Merging records with union) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.union({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { a: 1, b: 5, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const union = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = empty(); + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } else { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(out, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Merges two records, retaining only the entries that exist in both records. + * For intersecting keys, the provided combine function is used to merge the values. + * + * **Example** (Merging intersecting keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.intersection({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { b: 5 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + const out = empty(); + if (isEmptyRecord(self) || isEmptyRecord(that)) { + return out; + } + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } + } + return out; +}))); +/** + * Merges two records, preserving only the entries that are unique to each record. + * Keys that exist in both records are excluded from the result. + * + * **Example** (Keeping keys unique to each record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.difference({ a: 1, b: 2 }, { b: 3, c: 4 }) // => { a: 1, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = {}; + for (const key of keys(self)) { + if (!has(that, key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(self, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Create an `Equivalence` for records using the provided `Equivalence` for values. + * Two records are considered equivalent if they have the same keys and their corresponding values are equivalent. + * + * **Example** (Comparing records with a value equivalence) + * + * ```ts import.meta.vitest + * import { Equal, Record } from "effect" + * + * const recordEquivalence = Record.makeEquivalence(Equal.asEquivalence()) + * + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 3 }) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = equivalence => { + const is = isSubrecordBy(equivalence); + return (self, that) => is(self, that) && is(that, self); +}; +/** + * Create a non-empty record from a single element. + * + * **Example** (Creating a singleton record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.singleton("a", 1) // => { a: 1 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const singleton = (key, value) => ({ + [key]: value +}); +/** + * Creates a `Reducer` for combining `Record`s using union, with values for keys that exist in both records combined + * using the provided `Combiner`. + * + * **When to use** + * + * Use to build a reusable reducer for accumulating many records into one + * union-shaped record, preserving keys from every input and combining + * overlapping values with the supplied combiner. + * + * **Details** + * + * The returned reducer uses `Record.union` for combine and an empty record as + * `initialValue`, so the default `combineAll` folds from `{}` and accumulates + * keys from each input record. + * + * @see {@link union} for one-off record merging with the same union semantics + * @see {@link makeReducerIntersection} for a reducer that keeps only keys present on both sides + * + * @category combining + * @since 4.0.0 + */ +function makeReducerUnion(combiner) { + return Reducer.make((self, that) => union(self, that, combiner.combine), {}); +} +/** + * Creates a `Reducer` whose `combine` operation intersects two records and + * combines values for keys present in both records. + * + * **When to use** + * + * Use to build a `Reducer` that combines records by retaining only keys shared + * by both inputs and combining matching values with a `Combiner`. + * + * **Gotchas** + * + * The reducer's `initialValue` is an empty record. Because intersection with + * an empty record is empty, the default `combineAll` folds from `{}` and + * therefore produces `{}` for ordinary non-empty inputs. + * + * @see {@link makeReducerUnion} for a reducer that preserves keys from either input record + * @see {@link intersection} for applying the shared-key merge to one pair of records + * + * @category combining + * @since 4.0.0 + */ +function makeReducerIntersection(combiner) { + return Reducer.make((self, that) => intersection(self, that, combiner.combine), {}); +} +/** + * Returns the first entry that satisfies the specified + * predicate, or `None` if no such entry exists. + * + * **Example** (Finding the first matching entry) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const record = { a: 1, b: 2, c: 3 } + * Record.findFirst( + * record, + * (value, key) => value > 1 && key !== "b" + * ) // => Option.some(["c", 3]) + * ``` + * + * @category searching + * @since 3.14.0 + */ +const findFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const k = keys(self); + for (let i = 0; i < k.length; i++) { + const key = k[i]; + if (f(self[key], key)) { + return Option.some([key, self[key]]); + } + } + return Option.none(); +}))); +//# sourceMappingURL=Record.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Wo: toEntries +}); + + +}, +"./node_modules/effect/dist/Redactable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @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 + * @category guards + * @since 3.10.0 + */ +const isRedactable = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(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 + * @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 + * @category destructors + * @since 4.0.0 + */ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context ?? emptyContext); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/new Map(); +const emptyContext = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +//# sourceMappingURL=Redactable.js.map +__webpack_require__.d(__webpack_exports__, { + E$: () => (redact), + f6: () => (getRedacted) +}, { + fL: currentFiberTypeId, + uC: symbolRedactable +}); + + +}, +"./node_modules/effect/dist/Reducer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Reusable strategies for reducing many values into one value. A `Reducer` + * extends `Combiner.Combiner` with an `initialValue` for empty collections and + * a `combineAll` method for folding an entire iterable. This module provides a + * constructor for reducers and a helper for reversing the order in which values + * are combined. + * + * @since 4.0.0 + */ +/** + * Creates a `Reducer` from a `combine` function and an `initialValue`. + * + * **When to use** + * + * Use when you have a custom reducing operation not covered by a pre-built reducer. + * - You want to provide an optimized `combineAll` (e.g. short-circuiting on + * a known absorbing element like `0` for multiplication). + * + * **Details** + * + * - If `combineAll` is omitted, a default left-to-right fold starting from + * `initialValue` is used. + * - If `combineAll` is provided, it completely replaces the default fold. + * + * **Example** (Multiplying with short-circuit) + * + * ```ts import.meta.vitest + * import { Reducer } from "effect" + * + * const Product = Reducer.make( + * (a, b) => a * b, + * 1, + * (collection) => { + * let acc = 1 + * for (const n of collection) { + * if (n === 0) return 0 + * acc *= n + * } + * return acc + * } + * ) + * + * Product.combineAll([2, 3, 4]) // => 24 + * Product.combineAll([2, 0, 4]) // => 0 + * ``` + * + * @see {@link Reducer} – the interface this creates + * @see {@link flip} – reverse the argument order + * + * @category constructors + * @since 4.0.0 + */ +function make(combine, initialValue, combineAll) { + return { + combine, + initialValue, + combineAll: combineAll ?? (collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + } + return out; + }) + }; +} +/** + * Reverses the argument order of a reducer's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative reducer such as string concatenation. + * + * **Details** + * + * - Returns a new `Reducer` where `combine(self, that)` calls the original + * reducer as `combine(that, self)`. + * - The `initialValue` is preserved from the original reducer. + * - The `combineAll` is re-derived from the flipped `combine` (using the + * default left-to-right fold), not carried over from the original. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Reducer, String } from "effect" + * + * const Prepend = Reducer.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * Prepend.combineAll(["a", "b", "c"]) // => "cba" + * ``` + * + * @see {@link make} + * @see {@link Combiner.flip} – the same operation on a plain `Combiner` + * + * @category combinators + * @since 4.0.0 + */ +function flip(reducer) { + return make((self, that) => reducer.combine(that, self), reducer.initialValue); +} +//# sourceMappingURL=Reducer.js.map +__webpack_require__.d(__webpack_exports__, { + L: () => (make) +}); + + +}, +"./node_modules/effect/dist/Request.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); + + + + + + +const TypeId = "~effect/Request"; +const requestVariance = /*#__PURE__*/_Equal_js__rspack_import_0/* .byReferenceUnsafe */.Xq({ + /* c8 ignore next */ + _E: _ => _, + /* c8 ignore next */ + _A: _ => _, + /* c8 ignore next */ + _R: _ => _ +}); +/** + * Prototype used by Effect's request constructors. + * + * **Details** + * + * This low-level value provides the structural request marker for values + * created by `Request.of`, `Request.tagged`, `Request.Class`, and + * `Request.TaggedClass`. Most users should use those constructors instead of + * interacting with the prototype directly. + * + * @category prototypes + * @since 4.0.0 + */ +const RequestPrototype = { + ..._internal_core_js__rspack_import_1/* .StructuralProto */.In, + [TypeId]: requestVariance +}; +/** + * Checks whether a value is a `Request`. + * + * **Example** (Checking request values) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * const GetUser = Request.tagged("GetUser") + * + * const request = GetUser({ id: "123" }) + * Request.isRequest(request) // => true + * Request.isRequest("not a request") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isRequest = u => hasProperty(u, TypeId); +/** + * Creates a constructor function for a specific Request type. + * + * **Example** (Creating untagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const UserProfile: unique symbol + * declare const ProfileError: unique symbol + * type UserProfile = typeof UserProfile + * type ProfileError = typeof ProfileError + * + * interface GetUserProfile extends Request.Request { + * readonly id: string + * readonly includeSettings: boolean + * } + * + * const GetUserProfile = Request.of() + * + * const request = GetUserProfile({ + * id: "user-123", + * includeSettings: true + * }) + * + * request.id // => "user-123" + * request.includeSettings // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = () => args => Object.setPrototypeOf({ + ...args +}, RequestPrototype); +/** + * Creates a constructor function for a tagged Request type. The tag is automatically + * added to the request, making it useful for discriminated unions. + * + * **Example** (Creating tagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * declare const Post: unique symbol + * declare const PostNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * type Post = typeof Post + * type PostNotFound = typeof PostNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * + * interface GetPost extends Request.Request { + * readonly _tag: "GetPost" + * readonly id: string + * } + * + * const GetUser = Request.tagged("GetUser") + * const GetPost = Request.tagged("GetPost") + * + * const userRequest = GetUser({ id: "user-123" }) + * const postRequest = GetPost({ id: "post-456" }) + * + * // _tag is automatically set + * Array.of(userRequest._tag, postRequest._tag) // => ["GetUser", "GetPost"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const tagged = tag => args => { + return Object.setPrototypeOf({ + ...args, + _tag: tag + }, RequestPrototype); +}; +/** + * Defines request types with TypeScript classes. + * + * **Details** + * + * Subclasses pass their data fields to `super`, and instances are marked as + * `Request` values while retaining the provided readonly fields. + * + * **Example** (Defining request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUser extends Request.Class<{ id: number }, string, Error> { + * constructor(readonly id: number) { + * super({ id }) + * } + * } + * + * const getUserRequest = new GetUser(123) + * getUserRequest.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function Class(args) { + if (args) { + InternalRecord.assignProperties(this, args); + } + } + Class.prototype = RequestPrototype; + return Class; +}())); +/** + * Creates a class constructor for requests with a fixed `_tag` field. + * + * **Details** + * + * Use this when defining class-based request types that should participate in + * tagged unions or tag-based request resolvers. + * + * **Example** (Defining tagged request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUserById + * extends Request.TaggedClass("GetUserById")<{ id: number }, string, Error> + * {} + * + * const request = new GetUserById({ id: 123 }) + * + * request._tag // => "GetUserById" + * request.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const TaggedClass = tag => { + return class TaggedClass extends Class { + _tag = tag; + }; +}; +/** + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, result) => internalEffect.sync(() => self.completeUnsafe(result))))); +/** + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const completeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.matchEffect(effect, { + onFailure: error => complete(self, core.exitFail(error)), + onSuccess: value => complete(self, core.exitSucceed(value)) +})))); +/** + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, error) => complete(self, core.exitFail(error))))); +/** + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => complete(self, core.exitFailCause(cause))))); +/** + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, value) => complete(self, core.exitSucceed(value))))); +/** + * Creates a `Request.Entry` from its component fields. + * + * **Details** + * + * This is a low-level helper for request runtime and resolver infrastructure; + * most application code receives entries from a `RequestResolver` instead of + * constructing them directly. + * + * @category constructors + * @since 2.0.0 + */ +const makeEntry = options => options; +//# sourceMappingURL=Request.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + lq: makeEntry +}); + + +}, +"./node_modules/effect/dist/Result.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/** + * Models a value that has already succeeded or failed. + * + * A `Result` is `Success` when a value is available and + * `Failure` when an error is available. It is plain data, so inspecting + * or transforming it does not run side effects. This module includes helpers + * for creating, checking, mapping, combining, and extracting results, plus + * conversions to and from `Option` and nullable values. + * + * @since 4.0.0 + */ + + + + + + + +const TypeId = "~effect/data/Result"; +/** + * 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` + * + * @category constructors + * @since 4.0.0 + */ +const succeed = _internal_result_js__rspack_import_0/* .succeed */.Py; +/** + * 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 + * + * @category constructors + * @since 4.0.0 + */ +const fail = _internal_result_js__rspack_import_0/* .fail */.fJ; +const void_ = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed(void 0))); + +/** + * Provides a pre-built failed `Result` whose failure value is `undefined`. + * + * **When to use** + * + * Use when you need a failed `Result` value that acts only as a control signal + * without failure data. + * + * **Details** + * + * This is equivalent to `Result.fail(undefined)` with type + * `Result`, but reuses a shared `Failure` wrapper instead of + * allocating one each time. + * + * **Example** (Failing without a payload) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.failVoid // => Result.fail(undefined) + * ``` + * + * @see {@link fail} to create a Failure with a specific value + * + * @category constructors + * @since 4.0.0 + */ +const failVoid = /*#__PURE__*/(/* unused pure expression or super */ null && (fail(void 0))); +/** + * Converts a possibly `null` or `undefined` value into a `Result`. + * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * + * - Non-nullish values become `Success>` + * - `null` or `undefined` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * - The `onNullish` callback receives the original value + * + * **Example** (Handling nullable values) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.fromNullishOr(1, () => "fallback") // => Result.succeed(1) + * + * Result.fromNullishOr(null, () => "fallback") // => Result.fail("fallback") + * ``` + * + * @see {@link fromOption} to convert from an Option + * @see {@link succeed} / {@link fail} for direct construction + * + * @category constructors + * @since 4.0.0 + */ +const fromNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onNullish) => self == null ? fail(onNullish(self)) : succeed(self)))); +/** + * Converts an `Option` into a `Result`. + * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * + * - `Some` becomes `Success` + * - `None` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Converting an Option to a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.fromOption(Option.some(1), () => "missing") // => Result.succeed(1) + * + * Result.fromOption(Option.none(), () => "missing") // => Result.fail("missing") + * ``` + * + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values + * + * @category constructors + * @since 2.0.0 + */ +const fromOption = _internal_result_js__rspack_import_0/* .fromOption */.sV; +const try_ = evaluate => { + if (isFunction(evaluate)) { + try { + return succeed(evaluate()); + } catch (e) { + return fail(e); + } + } else { + try { + return succeed(evaluate.try()); + } catch (e) { + return fail(evaluate.catch(e)); + } + } +}; + +/** + * Checks whether a value is a `Result` (either `Success` or `Failure`). + * + * **When to use** + * + * Use to validate unknown input before operating on it as a `Result`. + * + * **Details** + * + * - Returns `true` for both `Success` and `Failure` variants + * - Acts as a TypeScript type guard, narrowing to `Result` + * + * **Example** (Checking if a value is a Result) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.isResult(Result.succeed(1)) // => true + * + * Result.isResult({ value: 1 }) // => false + * ``` + * + * @see {@link isSuccess} / {@link isFailure} to narrow to a specific variant + * + * @category guards + * @since 4.0.0 + */ +const isResult = _internal_result_js__rspack_import_0/* .isResult */.aI; +/** + * 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 + * + * @category guards + * @since 4.0.0 + */ +const isFailure = _internal_result_js__rspack_import_0/* .isFailure */.N6; +/** + * Checks whether a `Result` is a `Success`. + * + * **When to use** + * + * Use to narrow a known `Result` to the `Success` variant. + * + * **Details** + * + * - Acts as a TypeScript type guard, narrowing to `Success` + * - After narrowing, you can access `.success` to read the value + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * const result = Result.succeed(42) + * + * if (Result.isSuccess(result)) { + * result.success // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link isResult} to check if a value is any Result + * + * @category guards + * @since 4.0.0 + */ +const isSuccess = _internal_result_js__rspack_import_0/* .isSuccess */.oJ; +/** + * Extracts the success value as an `Option`, discarding the failure. + * + * **When to use** + * + * Use when you need to extract the success value from a `Result` as an + * `Option` and discard failure information. + * + * **Details** + * + * - `Success` becomes `Some` + * - `Failure` becomes `None` + * + * **Example** (Extracting the success as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * + * Result.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} to extract the error instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_0/* .getSuccess */.Oz; +/** + * Extracts the failure value as an `Option`, discarding the success. + * + * **When to use** + * + * Use when you need to extract the failure value from a `Result` as an + * `Option` and discard successful values. + * + * **Details** + * + * - `Failure` becomes `Some` + * - `Success` becomes `None` + * + * **Example** (Extracting the failure as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getFailure(Result.succeed("ok")) // => Option.none() + * + * Result.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} to extract the success instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_0/* .getFailure */.L8; +/** + * Creates an `Equivalence` for comparing two `Result` values. + * + * **Details** + * + * - Two `Success` values are equal when the `success` equivalence says so + * - Two `Failure` values are equal when the `failure` equivalence says so + * - A `Success` and a `Failure` are never equal + * + * **Example** (Comparing Results for equality) + * + * ```ts import.meta.vitest + * import { Equivalence, Result } from "effect" + * + * const eq = Result.makeEquivalence( + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ) + * + * eq(Result.succeed(1), Result.succeed(1)) // => true + * + * eq(Result.succeed(1), Result.fail("x")) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = (success, failure) => Equivalence.make((x, y) => isFailure(x) ? isFailure(y) && failure(x.failure, y.failure) : isSuccess(y) && success(x.success, y.success)); +/** + * Transforms both the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(1), + * Result.mapBoth({ + * onSuccess: (n) => n + 1, + * onFailure: (e) => `Error: ${e}` + * }) + * ) // => Result.succeed(2) + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error value + * @see {@link match} to fold into a single value + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? fail(onFailure(self.failure)) : succeed(onSuccess(self.success))))); +/** + * Transforms the failure channel of a `Result`, leaving the success channel unchanged. + * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * + * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` + * - If the result is a `Success`, returns it as-is + * + * **Example** (Adding context to an error) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("not found"), + * Result.mapError((e) => `Error: ${e}`) + * ) // => Result.fail("Error: not found") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapBoth} to transform both channels + * + * @category mapping + * @since 4.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(f(self.failure)) : self))); +/** + * Transforms the success channel of a `Result`, leaving the failure channel unchanged. + * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * + * - If the result is a `Success`, applies `f` to the value and returns a new `Success` + * - If the result is a `Failure`, returns it as-is + * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) + * + * **Example** (Doubling the success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(3), + * Result.map((n) => n * 2) + * ) // => Result.succeed(6) + * ``` + * + * @see {@link mapError} to transform only the error value + * @see {@link mapBoth} to transform both channels + * @see {@link flatMap} when `f` returns a `Result` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isSuccess(self) ? succeed(f(self.success)) : self))); +/** + * Folds a `Result` into a single value by applying one of two functions. + * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * - Both branches must return the same type (or a common supertype) + * + * **Example** (Folding to a string) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const format = Result.match({ + * onSuccess: (n: number) => `Got ${n}`, + * onFailure: (e: string) => `Err: ${e}` + * }) + * + * format(Result.succeed(42)) // => "Got 42" + * + * format(Result.fail("timeout")) // => "Err: timeout" + * ``` + * + * @see {@link merge} to extract `A | E` without mapping + * @see {@link getOrElse} to unwrap only the success with a fallback + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? onFailure(self.failure) : onSuccess(self.success)); +/** + * Lifts a value into a `Result` based on a predicate or refinement. + * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * + * - If the predicate returns `true`, the value becomes `Success` + * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Validating a number) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * 5, + * Result.liftPredicate( + * (n: number) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.succeed(5) + * ``` + * + * @see {@link filterOrFail} to validate a value that is already in a `Result` + * @see {@link fromNullishOr} for nullable-based construction + * + * @category constructors + * @since 3.4.0 + */ +const liftPredicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (a, predicate, orFailWith) => predicate(a) ? succeed(a) : fail(orFailWith(a))))); +/** + * Validates the success value of a `Result` using a predicate, failing with a + * custom error if the predicate returns `false`. + * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * + * - If the result is already a `Failure`, it is returned as-is + * - If the predicate passes, the `Success` is returned unchanged + * - If the predicate fails, `orFailWith` produces the error for a new `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - The error type of the output is the union of both error types + * + * **Example** (Filtering a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(0), + * Result.filterOrFail( + * (n) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.fail("0 is not positive") + * ``` + * + * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate + * @see {@link flatMap} for general conditional chaining + * + * @category filtering + * @since 4.0.0 + */ +const filterOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, orFailWith) => flatMap(self, a => predicate(a) ? succeed(a) : fail(orFailWith(a)))))); +/** + * Unwraps a `Result` into `A | E` by returning the inner value regardless + * of whether it is a success or failure. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `E` + * - Useful when both channels share a compatible type + * + * **Example** (Extracting the inner value) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.merge(Result.succeed(42)) // => 42 + * + * Result.merge(Result.fail("error")) // => "error" + * ``` + * + * @see {@link match} to map each branch to a common type + * @see {@link getOrElse} to provide a fallback for failures + * + * @category getters + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (match({ + onFailure: identity, + onSuccess: identity +}))); +/** + * Extracts the success value, or computes a fallback from the error. + * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * + * - `Success` returns the inner value + * - `Failure` applies `onFailure` to the error and returns the result + * - The return type is `A | A2` (union of both branches) + * + * **Example** (Providing a fallback) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrElse(Result.succeed(1), () => 0) // => 1 + * + * Result.getOrElse(Result.fail("err"), () => 0) // => 0 + * ``` + * + * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks + * @see {@link getOrThrow} to throw on failure + * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => isFailure(self) ? onFailure(self.failure) : self.success))); +/** + * Extracts the success value, or returns `null` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `null`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `null` + * + * **Example** (Unwrapping to nullable) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrNull(Result.succeed(1)) // => 1 + * + * Result.getOrNull(Result.fail("err")) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constNull))); +/** + * Extracts the success value, or returns `undefined` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `undefined`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `undefined` + * + * **Example** (Unwrapping to optional) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrUndefined(Result.succeed(1)) // => 1 + * + * Result.getOrUndefined(Result.fail("err")) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constUndefined))); +/** + * Extracts the success value or throws a custom error derived from the failure. + * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws the value returned by `onFailure(e)` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrowWith(Result.succeed(1), () => new Error("fail")) // => 1 + * + * const failure = Result.try({ + * try: () => Result.getOrThrowWith( + * Result.fail("oops"), + * (error) => new Error(`Unexpected: ${error}`) + * ), + * catch: (error) => (error as Error).message + * }) + * Result.merge(failure) // => "Unexpected: oops" + * ``` + * + * @see {@link getOrThrow} to throw the raw failure value + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => { + if (isSuccess(self)) { + return self.success; + } + throw onFailure(self.failure); +}))); +/** + * Extracts the success value or throws the raw failure value `E`. + * + * **When to use** + * + * Use when unchecked boundaries should turn failures into thrown exceptions. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws `E` directly + * - Use {@link getOrThrowWith} for a custom error object + * + * **Example** (Unwrapping or throwing) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrow(Result.succeed(1)) // => 1 + * + * const failure = Result.try(() => Result.getOrThrow(Result.fail("error"))) + * Result.merge(failure) // => "error" + * ``` + * + * @see {@link getOrThrowWith} for custom error mapping + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrThrowWith(identity))); +/** + * Returns the original `Result` if it is a `Success`, otherwise applies + * `that` to the error and returns the resulting `Result`. + * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * + * - `Success` is returned unchanged + * - `Failure` calls `that(e)` to produce a new `Result` + * + * **Example** (Recovering from a failure) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("primary failed"), + * Result.orElse(() => Result.succeed(99)) + * ) // => Result.succeed(99) + * ``` + * + * @see {@link getOrElse} to unwrap with a fallback value (not a Result) + * @see {@link mapError} to transform the error without recovering + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => isFailure(self) ? that(self.failure) : succeed(self.success)))); +/** + * Chains a function that returns a `Result` onto a successful value. + * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * + * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` + * - If `self` is a `Failure`, short-circuits and returns it unchanged + * - The error types are merged into a union (`E | E2`) + * - This is the monadic `bind` / `>>=` for `Result` + * + * **Example** (Validating sequentially) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(5), + * Result.flatMap((n) => + * n > 0 ? Result.succeed(n * 2) : Result.fail("not positive") + * ) + * ) // => Result.succeed(10) + * ``` + * + * @see {@link andThen} for a more flexible variant that also accepts plain values + * @see {@link map} when `f` does not return a `Result` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(self.failure) : f(self.success)))); +/** + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** + * + * The second argument can be: + * - A function `(a: A) => Result` (same as `flatMap`) + * - A function `(a: A) => A2` (auto-wrapped in `succeed`) + * - A `Result` value (ignores the success of `self`) + * - A plain value `A2` (auto-wrapped in `succeed`, ignores `self`) + * + * If `self` is a `Failure`, the second argument is never evaluated. + * + * **Example** (Chaining Result values with different argument types) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * // With a function returning a Result + * const a = pipe( + * Result.succeed(1), + * Result.andThen((n) => Result.succeed(n + 1)) + * ) // => Result.succeed(2) + * + * // With a plain mapping function + * const b = pipe( + * Result.succeed(1), + * Result.andThen((n) => n + 1) + * ) // => Result.succeed(2) + * + * // With a constant value + * const c = pipe(Result.succeed(1), Result.andThen("done")) // => Result.succeed("done") + * ``` + * + * @see {@link flatMap} for the stricter variant (function returning Result only) + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => { + const out = isFunction(f) ? f(a) : f; + return isResult(out) ? out : succeed(out); +})))); +/** + * Collects a structure of `Result`s into a single `Result` of collected values. + * + * **When to use** + * + * Use to collect independent `Result` values into one `Result` while preserving + * the original structure. + * + * **Details** + * + * Accepts: + * - A tuple/array: returns `Result` with a tuple/array of success values + * - A struct (record): returns `Result` with a struct of success values + * - An iterable: returns `Result` with an array of success values + * + * Short-circuits on the first `Failure` encountered; later elements are not inspected. + * + * **Example** (Collecting a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * // Tuple + * Result.all([Result.succeed(1), Result.succeed("two")]) // => Result.succeed([1, "two"]) + * + * // Struct + * Result.all({ x: Result.succeed(1), y: Result.fail("err") }) // => Result.fail("err") + * ``` + * + * @see {@link flatMap} for chaining two Results sequentially + * @see {@link gen} for generator-based composition of multiple Results + * + * @category sequencing + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const e of input) { + if (isFailure(e)) { + return e; + } + out.push(e.success); + } + return succeed(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const e = input[key]; + if (isFailure(e)) { + return e; + } + InternalRecord.assignProperty(out, key, e.success); + } + return succeed(out); +}; +/** + * Swaps the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to swap channels when failure-focused operations are easier through + * success-oriented combinators. + * + * **Details** + * + * - `Success` becomes `Failure` (i.e., `Result`) + * - `Failure` becomes `Success` (i.e., `Result`) + * - Useful when you want to apply success-oriented operations (like `map`) + * to the error channel, then flip back + * + * **Example** (Swapping channels) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.flip(Result.succeed(42)) // => Result.fail(42) + * + * Result.flip(Result.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link mapError} to transform the error without swapping + * + * @category transforming + * @since 2.0.0 + */ +const flip = self => isFailure(self) ? succeed(self.failure) : fail(self.success); +/** + * Provides generator-based syntax for composing `Result` values sequentially. + * + * **When to use** + * + * Use when you need generator syntax to compose sequential `Result` + * computations instead of nested `flatMap` calls. + * + * **Details** + * + * - Use `yield*` to unwrap a `Result` inside the generator; if any yielded + * `Result` is a `Failure`, the generator short-circuits and returns that failure + * - The return value of the generator is wrapped in `Success` + * - Evaluated eagerly and synchronously (unlike `Effect.gen`) + * + * **Example** (Composing multiple Results) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.gen(function*() { + * const a = yield* Result.succeed(1) + * const b = yield* Result.succeed(2) + * return a + b + * }) // => Result.succeed(3) + * ``` + * + * @see {@link flatMap} for point-free sequential composition + * @see {@link all} to collect multiple independent Results + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isFailure(current)) { + return current; + } + state = iterator.next(current.success); + } + return succeed(state.value); +}; +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do notation" simulation with `Result`. + * + * **When to use** + * + * Use to start a `Result` do-notation pipeline from an empty successful record + * before adding named fields from `Result`-producing computations and pure + * computed values. + * + * **Details** + * + * Creates a `Result<{}>` (success with an empty object). Use with + * {@link bind} to add `Result`-producing fields and {@link let_ let} + * to add pure computed fields. + * + * **Example** (Building an object step by step) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", () => Result.succeed(3)), + * Result.let("sum", ({ x, y }) => x + y) + * ) // => Result.succeed({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add Result-producing fields + * @see {@link let_ let} to add pure computed fields + * @see {@link gen} for an alternative generator-based syntax + * @see {@link bindTo} for starting a do-notation chain from an existing Result + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +/** + * Adds a named field to the do-notation accumulator by running a `Result`-producing + * function that receives the current accumulated object. + * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * + * - Short-circuits on the first `Failure` + * - The field name must not collide with existing keys + * - Use {@link let_ let} for pure (non-Result) computed fields + * + * **Example** (Binding Result values) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", ({ x }) => Result.succeed(x + 3)) + * ) // => Result.succeed({ x: 2, y: 5 }) + * ``` + * + * @see {@link Do} to start the do-notation chain + * @see {@link let_ let} for pure computed fields + * @see {@link bindTo} to wrap an initial Result into a named field + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bind(map, flatMap))); +/** + * Wraps the success value of a `Result` into a named field, producing a + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. + * + * **Example** (Wrapping a value into a named field) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(42), + * Result.bindTo("answer") + * ) // => Result.succeed({ answer: 42 }) + * ``` + * + * @see {@link Do} to start from an empty object + * @see {@link bind} to add more fields + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.let_(map))); + +/** + * Transforms `Option>` into `Result, E>`. + * + * **When to use** + * + * Use when optional absence should be treated as a successful `None`, while an + * inner `Result` failure should still fail the whole result. + * + * **Details** + * + * - `None` becomes `Success(None)` + * - `Some(Success(a))` becomes `Success(Some(a))` + * - `Some(Failure(e))` becomes `Failure(e)` + * + * **Example** (Transposing an Option of a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.transposeOption(Option.some(Result.succeed(42))) // => Result.succeed(Option.some(42)) + * + * Result.transposeOption(Option.none>()) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeMapOption} to map and transpose in one step + * + * @category transposing + * @since 3.14.0 + */ +const transposeOption = self => { + return option_.isNone(self) ? succeedNone : map(self.value, option_.some); +}; +/** + * Maps an `Option` value with a `Result`-producing function, then transposes + * the structure from `Option>` to `Result, E>`. + * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * + * - `None` becomes `Success(None)` (the function is never called) + * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` + * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` + * + * **Example** (Mapping and transposing in one step) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parse = (s: string) => + * isNaN(Number(s)) + * ? Result.fail("not a number" as const) + * : Result.succeed(Number(s)) + * + * Result.transposeMapOption(Option.some("42"), parse) // => Result.succeed(Option.some(42)) + * + * Result.transposeMapOption(Option.none(), parse) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeOption} when the Option already contains a Result + * + * @category transposing + * @since 3.15.0 + */ +const transposeMapOption = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some)))); +/** + * Provides a pre-built `Result>` that succeeds with `None`. + * + * **When to use** + * + * Use when an optional success should be absent, such as the `None` branch of + * `transposeOption` or `transposeMapOption`. + * + * **Details** + * + * This is equivalent to `Result.succeed(Option.none())`, but reuses a shared + * `Success` wrapper instead of allocating one each time. + * + * **Example** (Succeeding with None) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedNone // => Result.succeed(Option.none()) + * ``` + * + * @see {@link succeedSome} for the `Some` counterpart + * @see {@link transposeOption} to transpose an Option that already contains a Result + * @see {@link transposeMapOption} to map and transpose an Option in one step + * + * @category constructors + * @since 4.0.0 + */ +const succeedNone = /*#__PURE__*/succeed(_internal_option_js__rspack_import_2/* .none */.dv); +/** + * Creates a `Result>` that succeeds with `Some(a)`. + * + * **Details** + * + * - Equivalent to `Result.succeed(Option.some(a))` + * - Useful with {@link transposeOption} patterns + * + * **Example** (Wrapping a value in Some inside a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedSome(42) // => Result.succeed(Option.some(42)) + * ``` + * + * @see {@link succeedNone} for the `None` counterpart + * + * @category constructors + * @since 4.0.0 + */ +const succeedSome = a => succeed(option_.some(a)); +/** + * Runs a side-effect on the success value without altering the `Result`. + * + * **Details** + * + * - If the result is a `Success`, calls `f` with the value (return value is ignored) + * - If the result is a `Failure`, `f` is not called + * - Returns the original `Result` unchanged (same reference) + * - Useful for logging, debugging, or performing mutations outside the Result chain + * + * **Example** (Logging a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const values: Array = [] + * const result = pipe( + * Result.succeed(42), + * Result.tap((n) => values.push(n)) + * ) + * + * values // => [42] + * result // => Result.succeed(42) + * ``` + * + * @see {@link map} to transform the success value + * + * @category mapping + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isSuccess(self)) { + f(self.success); + } + return self; +}))); +//# sourceMappingURL=Result.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + N6: isFailure, + Py: succeed, + YW: match, + fJ: fail, + oJ: isSuccess +}); + + +}, +"./node_modules/effect/dist/Schedule.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Pull_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Pull.js"); + + + + + + + + + + + + +const TypeId = "~effect/Schedule"; +const randomNext = /*#__PURE__*/(/* unused pure expression or super */ null && (random.Random.useSync(random => random.nextDoubleUnsafe()))); +/** + * Context reference containing metadata for the currently running schedule step. + * + * **Details** + * + * Repeat, retry, stream, and channel scheduling operations provide this service + * to effects run between schedule steps. The default value contains undefined + * input and output values, zero duration, and zeroed timing fields before any + * schedule step has produced metadata. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Schedule/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + input: undefined, + output: undefined, + duration: _Duration_js__rspack_import_2/* .zero */.v_, + attempt: 0, + start: 0, + now: 0, + elapsed: 0, + elapsedSincePrevious: 0 + }) +}); +const ScheduleProto = { + [TypeId]: { + _Out: _Function_js__rspack_import_1/* .identity */.D_, + _In: _Function_js__rspack_import_1/* .identity */.D_, + _Env: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_3/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * Type guard that checks if a value is a Schedule. + * + * **Example** (Checking for schedules) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.exponential("100 millis") + * const notSchedule = { foo: "bar" } + * + * Schedule.isSchedule(schedule) // => true + * Schedule.isSchedule(notSchedule) // => false + * Schedule.isSchedule(null) // => false + * Schedule.isSchedule(undefined) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isSchedule = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Creates a Schedule from a step function that returns a Pull. + * + * **Example** (Creating a custom schedule from a step function) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.fromStep(Effect.sync(() => { + * let count = 0 + * + * return (_now: number, _input: string) => { + * if (count >= 3) { + * return Cause.done(count) + * } + * return Effect.succeed([count++, Duration.millis(100)] as [number, Duration.Duration]) + * } + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => 0 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStep = step => { + const self = Object.create(ScheduleProto); + self.step = step; + return self; +}; +const metadataFn = () => { + let n = 0; + let previous; + let start; + return (now, input) => { + if (start === undefined) start = now; + const elapsed = now - start; + const elapsedSincePrevious = previous === undefined ? 0 : now - previous; + previous = now; + return { + input, + attempt: ++n, + start, + now, + elapsed, + elapsedSincePrevious + }; + }; +}; +/** + * Creates a Schedule from a step function that receives metadata about the schedule's execution. + * + * **Example** (Creating a metadata-aware schedule) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const firstThreeInputs = Schedule.fromStepWithMetadata(Effect.succeed((metadata: Schedule.InputMetadata) => { + * if (metadata.attempt > 3) { + * return Cause.done("finished") + * } + * + * return Effect.succeed([ + * `attempt ${metadata.attempt}: ${metadata.input}`, + * Duration.millis(250) + * ] as [string, Duration.Duration]) + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(firstThreeInputs) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "attempt 1: input" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStepWithMetadata = step => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(step, f => { + const meta = metadataFn(); + return (now, input) => f(meta(now, input)); +})); +/** + * Extracts the step function from a Schedule. + * + * **Example** (Extracting a schedule step function) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * // Extract step function from an existing schedule + * const schedule = Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * + * const program = Effect.gen(function*() { + * const stepFn = yield* Schedule.toStep(schedule) + * + * // Use the step function directly for custom logic. The timestamp is + * // supplied by the caller, so tests can pass a deterministic value. + * const now = 0 + * return yield* stepFn(now, "input") + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStep = schedule => _internal_effect_js__rspack_import_5/* .catchCause */.Tyx(schedule.step, cause => _internal_effect_js__rspack_import_5/* .succeed */.PyW(() => _internal_effect_js__rspack_import_5/* .failCause */.ATB(cause))); +/** + * Extracts a step function from a `Schedule` that sleeps for each computed + * delay and returns metadata for the completed step. + * + * **When to use** + * + * Use to drive a schedule manually while preserving the computed output, + * delay, input, attempt, and elapsed timing metadata for each step. + * + * **Details** + * + * The returned step reads the current time from `Clock` when invoked, calls the + * schedule step with that timestamp and input, sleeps for the returned + * duration, and then yields `Metadata`. + * + * @see {@link toStep} for manually supplying the timestamp and handling the returned delay yourself + * @see {@link toStepWithSleep} for the same automatic sleeping behavior when only the schedule output is needed + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithMetadata = schedule => _internal_effect_js__rspack_import_5/* .clockWith */.RKA(clock => _internal_effect_js__rspack_import_5/* .map */.TjK(toStep(schedule), step => { + const metaFn = metadataFn(); + return input => _internal_effect_js__rspack_import_5/* .suspend */.DYE(() => { + const now = clock.currentTimeMillisUnsafe(); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), ([output, duration]) => { + const meta = metaFn(now, input); + meta.output = output; + meta.duration = duration; + return _internal_effect_js__rspack_import_5.as(_internal_effect_js__rspack_import_5/* .sleep */.yy4(duration), meta); + }); + }); +})); +/** + * Extracts a step function from a Schedule that automatically handles sleep delays. + * + * **Example** (Extracting a sleeping step function) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const schedule = Schedule.recurs(3) + * + * const program = Effect.gen(function*() { + * const stepWithSleep = yield* Schedule.toStepWithSleep(schedule) + * + * return [yield* stepWithSleep("first"), yield* stepWithSleep("second")] + * }) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [0, 1] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithSleep = schedule => effect.map(toStepWithMetadata(schedule), step => input => effect.map(step(input), meta => meta.output)); +/** + * Returns a new `Schedule` that adds the delay computed by the specified + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.recurs(1).pipe( + * Schedule.addDelay(() => Effect.succeed("25 millis")) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(25) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const addDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => modifyDelay(self, metadata => effect.map(f(metadata), d => Duration.sum(Duration.fromInputUnsafe(d), metadata.duration)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concat(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const concat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => map(concatResult(self, other), ({ + output +}) => effect.succeed(Result.merge(output)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concatResult(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concatResult = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => fromStep(effect.sync(() => { + let currentSide = 0; + let currentStep; + const left = map(self, ({ + output + }) => Result.fail(output)); + const right = map(other, ({ + output + }) => Result.succeed(output)); + return function recur(now, input) { + if (currentStep) return currentStep(now, input); + return toStep(currentSide === 0 ? left : right).pipe(effect.flatMap(step => { + currentSide++; + if (currentSide === 1) { + currentStep = (now, input) => Pull.catchDone(step(now, input), _ => { + currentStep = undefined; + return recur(now, input); + }); + return currentStep(now, input); + } + currentStep = step; + return currentStep(now, input); + })); + }; +}))))); +/** + * Combines schedules by recurring while all schedules want to recur, using the + * maximum delay between recurrences and outputting that maximum delay. + * + * **When to use** + * + * Use when a combined policy should continue only while every schedule still + * recurs, and should wait for the slowest schedule between recurrences. + * + * **Example** (Combining retry schedules by their maximum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.max([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const max = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = maxDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const maxDuration = results => { + let max = results[0]; + for (let i = 1; i < results.length; i++) { + max = results[i] && max && Duration.max(max, results[i]); + if (max === undefined) break; + } + return max; +}; +/** + * Returns a new `Schedule` that recurs on the specified `Cron` schedule and + * outputs the duration between recurrences. + * + * **Example** (Scheduling work with cron expressions) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const everyMinute = Schedule.cron("* * * * *") + * Schedule.isSchedule(everyMinute) // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const cron = (expression, tz) => { + const parsed = Cron.isCron(expression) ? Result.succeed(expression) : Cron.parse(expression, tz); + return fromStep(effect.map(effect.fromResult(parsed), cron => (now, _) => { + if (now === Number.POSITIVE_INFINITY) { + return Cause.done(Duration.zero); + } + return effect.sync(() => { + const next = Cron.next(cron, now).getTime(); + const duration = Duration.millis(next - now); + return [duration, duration]; + }); + })); +}; +/** + * Returns a schedule that recurs once after the specified duration. + * + * **When to use** + * + * Use when you need a schedule that recurs once after a fixed delay. + * + * **Details** + * + * The schedule outputs the configured duration for its first recurrence and + * then completes. + * + * **Example** (Recurring once after a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.duration("1 second")) // => true + * ``` + * + * @see {@link during} for recurring until a duration has elapsed + * + * @category constructors + * @since 2.0.0 + */ +const duration = durationInput => { + const duration = Duration.fromInputUnsafe(durationInput); + return fromStepWithMetadata(effect.succeed(meta => meta.attempt === 1 ? effect.succeed([duration, duration]) : Cause.done(Duration.zero))); +}; +/** + * Returns a new `Schedule` that will always recur, but only during the + * specified `duration` of time. + * + * **When to use** + * + * Use to bound a repeating or retrying schedule by elapsed time. + * + * **Example** (Repeating work during a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.during("5 seconds")) // => true + * ``` + * + * @see {@link duration} for one delayed recurrence + * + * @category constructors + * @since 4.0.0 + */ +const during = duration => { + const durationMillis = Duration.toMillis(duration); + return fromStepWithMetadata(effect.succeed(meta => { + const elapsed = Duration.millis(meta.elapsed); + return meta.elapsed > durationMillis ? Cause.done(elapsed) : effect.succeed([elapsed, Duration.zero]); + })); +}; +/** + * Combines schedules by recurring while at least one schedule wants to recur, + * using the minimum delay between recurrences and outputting that minimum delay. + * + * **When to use** + * + * Use when a combined policy should continue while any schedule still recurs, + * and should wait for the fastest schedule between recurrences. + * + * **Example** (Combining retry schedules by their minimum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.min([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const min = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = minDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const minDuration = results => { + let min = undefined; + for (let i = 0; i < results.length; i++) { + const duration = results[i]; + if (duration !== undefined) { + min = min === undefined ? duration : Duration.min(min, duration); + } + } + return min; +}; +/** + * Schedule that always recurs, but will wait a certain amount between + * repetitions, given by `base * factor.pow(n)`, where `n` is the number of + * repetitions so far. Returns the current duration between recurrences. + * + * **Example** (Retrying with exponential backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.exponential("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const exponential = (base, factor = 2) => { + const baseMillis = Duration.toMillis(Duration.fromInputUnsafe(base)); + return fromStepWithMetadata(effect.succeed(meta => { + const duration = Duration.millis(baseMillis * Math.pow(factor, meta.attempt - 1)); + return effect.succeed([duration, duration]); + })); +}; +/** + * Schedule that always recurs, increasing delays by summing the preceding + * two delays (similar to the Fibonacci sequence). Returns the current + * duration between recurrences. + * + * **Example** (Retrying with Fibonacci backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fibonacci("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fibonacci = one => { + const oneMillis = Duration.toMillis(Duration.fromInputUnsafe(one)); + return fromStep(effect.sync(() => { + let a = 0; + let b = oneMillis; + return constant(effect.sync(() => { + const next = a + b; + a = b; + b = next; + const duration = Duration.millis(next); + return [duration, duration]; + })); + })); +}; +/** + * Returns a `Schedule` that recurs on the specified fixed `interval` and + * outputs the number of repetitions of the schedule so far. + * + * **When to use** + * + * Use when recurrences should stay aligned to a regular cadence. + * + * **Gotchas** + * + * If the action run between recurrences takes longer than the interval, the + * next recurrence happens immediately, but missed intervals are not replayed. + * + * ```text + * |-----interval-----|-----interval-----|-----interval-----| + * |---------action--------||action|-----|action|-----------| + * ``` + * + * **Example** (Repeating on fixed intervals) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fixed("1 second")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(1)] + * ``` + * + * @see {@link spaced} for delaying after each action completes + * + * @category constructors + * @since 2.0.0 + */ +const fixed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.sync(() => { + let start = 0; + let lastRun = 0; + return meta => effect.sync(() => { + if (window === 0) { + return [meta.attempt - 1, Duration.zero]; + } + if (meta.attempt === 1) { + start = meta.now; + lastRun = meta.now + window; + return [0, Duration.millis(window)]; + } + const runningBehind = meta.now > lastRun + window; + const boundary = window - (meta.now - start) % window; + const delay = runningBehind ? 0 : boundary === 0 ? window : boundary; + lastRun = runningBehind ? meta.now : meta.now + delay; + return [meta.attempt - 1, Duration.millis(delay)]; + }); + })); +}; +/** + * Returns a new `Schedule` that maps each schedule decision to a new output + * using the full schedule metadata. + * + * **Details** + * + * The callback receives the schedule input, output, selected delay duration, + * current attempt, and elapsed timing information. Return either a plain value + * or an `Effect` that produces the new output. + * + * **Example** (Mapping schedule outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const countSchedule = Schedule.recurs(5).pipe( + * Schedule.map(({ output: count }) => Effect.succeed(`Execution #${count + 1}`)) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(countSchedule) + * const [output] = yield* step(0, undefined) + * return output + * }) + * + * await Effect.runPromise(program) // => "Execution #1" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => Pull.matchEffect(step(now, input), { + onSuccess: ([output, duration]) => { + const result = f({ + ...meta(now, input), + output, + duration + }); + if (!isEffect(result)) return effect.succeed([result, duration]); + return effect.map(result, output => [output, duration]); + }, + onFailure: effect.failCause, + onDone: output => { + const result = f({ + ...meta(now, input), + output, + duration: Duration.zero + }); + if (!isEffect(result)) return Cause.done(result); + return effect.flatMap(result, Cause.done); + } + }); +}))))); +/** + * Returns a new `Schedule` that modifies the delay of the next recurrence + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule metadata) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.spaced("10 millis").pipe( + * Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.times(duration, 2))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(20) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const modifyDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.flatMap(step(now, input), ([output, duration]) => effect.map(f({ + ...meta(now, input), + output, + duration + }), replacement => [output, Duration.fromInputUnsafe(replacement)])); +}))))); +/** + * Returns a new `Schedule` that randomly adjusts each recurrence delay. + * + * **When to use** + * + * Use to add random variation to an existing schedule's recurrence delays while + * preserving its output and completion behavior. + * + * **Details** + * + * Each recurrence delay is scaled by a random factor between `0.8` and `1.2`. + * + * @see {@link modifyDelay} for replacing recurrence delays with a custom effectful transformation + * + * @category delays & timeouts + * @since 2.0.0 + */ +const jittered = self => modifyDelay(self, ({ + duration +}) => effect.map(randomNext, random => { + const millis = Duration.toMillis(duration); + return Duration.millis(millis * 0.8 * (1 - random) + millis * 1.2 * random); +})); +/** + * Returns a new `Schedule` that outputs the inputs of the specified schedule. + * + * **Example** (Passing inputs through as outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const inputSchedule = Schedule.passthrough( + * Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(inputSchedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "input" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const passthrough = self => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => (now, input) => _Pull_js__rspack_import_6/* .matchEffect */.tv(step(now, input), { + onSuccess: result => _internal_effect_js__rspack_import_5/* .succeed */.PyW([input, result[1]]), + onFailure: _internal_effect_js__rspack_import_5/* .failCause */.ATB, + onDone: () => _Cause_js__rspack_import_7/* .done */.Vw(input) +}))); +/** + * Returns a `Schedule` which can only be stepped the specified number of + * `times` before it terminates. + * + * **When to use** + * + * Use when you need a counter schedule with no additional delay. + * + * **Gotchas** + * + * `recurs(n)` counts schedule recurrences, not the first evaluation of the + * effect being repeated or retried. For retrying, this means one initial + * attempt plus at most `n` retries. + * + * **Example** (Limiting recurrences) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(Schedule.recurs(3)), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3, 4] + * ``` + * + * @see {@link upTo} for limiting an existing schedule + * + * @category constructors + * @since 2.0.0 + */ +const recurs = times => while_(forever, ({ + attempt +}) => _internal_effect_js__rspack_import_5/* .succeed */.PyW(attempt <= times)); +/** + * Returns a schedule that recurs continuously, each repetition spaced the + * specified duration from the last run. + * + * **When to use** + * + * Use when each delay should start after the previous action completes. + * + * **Example** (Repeating with fixed spacing) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.spaced("2 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(2)] + * ``` + * + * @see {@link fixed} for recurrence aligned to a regular cadence + * + * @category constructors + * @since 2.0.0 + */ +const spaced = duration => { + const decoded = _Duration_js__rspack_import_2/* .fromInputUnsafe */.bN(duration); + return fromStepWithMetadata(_internal_effect_js__rspack_import_5/* .succeed */.PyW(meta => _internal_effect_js__rspack_import_5/* .succeed */.PyW([meta.attempt - 1, decoded]))); +}; +/** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const attempts: Array = [] + * const monitoredSchedule = Schedule.recurs(2).pipe( + * Schedule.tap((metadata) => Effect.sync(() => attempts.push(metadata.attempt))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(monitoredSchedule) + * const [output] = yield* step(0, undefined) + * return { attempts, output } + * }) + * + * await Effect.runPromise(program) // => { attempts: [1], output: 0 } + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.tap(step(now, input), ([output, duration]) => f({ + ...meta(now, input), + output, + duration + })); +}))))); +/** + * Returns a new `Schedule` that limits an existing schedule by elapsed + * duration, number of outputs, or both. + * + * **When to use** + * + * Use to bound an existing schedule while preserving its output and delay + * behavior. When both `duration` and `times` are specified, the schedule + * stops as soon as either limit is reached. + * + * **Gotchas** + * + * The `times` option limits schedule outputs. When used with repeat or retry, + * the effect is evaluated once before the schedule is stepped, so the total + * number of evaluations can be one greater than the configured number of + * outputs. + * + * The `duration` option is based on the elapsed time observed by the schedule + * step. Long-running effects can cause the duration limit to be detected on the + * following schedule step. + * + * **Example** (Limiting by duration and recurrence count) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const upTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const duration = options.duration === undefined ? undefined : Duration.fromInputUnsafe(options.duration); + return while_(self, ({ + attempt, + elapsed + }) => effect.succeed((options.times === undefined || attempt <= options.times) && (duration === undefined || Duration.isLessThanOrEqualTo(Duration.millis(elapsed), duration)))); +}))); +const while_ = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), result => { + const [output, duration] = result; + const eff = predicate({ + ...meta(now, input), + output, + duration + }); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB((0,_internal_core_js__rspack_import_8/* .isEffect */.yw)(eff) ? eff : _internal_effect_js__rspack_import_5/* .succeed */.PyW(eff), check => check ? _internal_effect_js__rspack_import_5/* .succeed */.PyW(result) : _Cause_js__rspack_import_7/* .done */.Vw(output)); + }); +}))); + +/** + * Schedule that divides the timeline to `interval`-long windows, and sleeps + * until the nearest window boundary every time it recurs. + * + * **Details** + * + * For example, `Schedule.windowed("10 seconds")` would produce a schedule as + * follows: + * + * ```text + * 10s 10s 10s 10s + * |----------|----------|----------|----------| + * |action------|sleep---|act|-sleep|action----| + * ``` + * + * **Example** (Repeating on aligned windows) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.windowed("5 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(5)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const windowed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.succeed(meta => effect.sync(() => [meta.attempt - 1, window === 0 ? Duration.zero : Duration.millis(window - meta.elapsed % window)]))); +}; +/** + * Returns a new `Schedule` that will recur forever. + * + * **Details** + * + * The output of the schedule is the current count of its repetitions thus far + * (i.e. `0, 1, 2, ...`). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const forever = /*#__PURE__*/spaced(_Duration_js__rspack_import_2/* .zero */.v_); +const constIdentity = /*#__PURE__*/(/* unused pure expression or super */ null && (fromStep(/*#__PURE__*/effect.succeed((_now, input) => effect.succeed([input, Duration.zero]))))); +const identity_ = () => constIdentity; + +/** + * Sets the input type of the provided schedule without altering its behavior. + * + * **When to use** + * + * Use to adapt a schedule that does not depend on its input values. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Setting a schedule input type) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.recurs(3).pipe( + * Schedule.setInputType() + * ) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const setInputType = () => self => self; +//# sourceMappingURL=Schedule.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + E6: while_, + GM: isSchedule, + d3: CurrentMetadata, + i4: forever, + le: passthrough, + t5: recurs, + xn: toStepWithMetadata +}); + + +}, +"./node_modules/effect/dist/Scheduler.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.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. + * + * @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. + * + * @category services + * @since 2.0.0 + */ +const Scheduler = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setImmediate = "setImmediate" in globalThis ? f => { + // @ts-ignore + const timer = globalThis.setImmediate(f); + // @ts-ignore + return () => globalThis.clearImmediate(timer); +} : f => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setMicrotask = f => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +class PriorityBuckets { + 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. + * + * @category models + * @since 2.0.0 + */ +class MixedScheduler { + 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.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); + } +} +class MixedSchedulerDispatcher { + tasks = /*#__PURE__*/new PriorityBuckets(); + running = undefined; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === undefined) { + this.running = this.setImmediate(this.afterScheduled); + } + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = undefined; + 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 !== undefined) { + this.running(); + this.running = undefined; + } + 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 + * + * @category services + * @since 4.0.0 + */ +const MaxOpsBeforeYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("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 + * + * @category services + * @since 4.0.0 + */ +const PreventSchedulerYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +//# sourceMappingURL=Scheduler.js.map +__webpack_require__.d(__webpack_exports__, { + FG: () => (MixedScheduler) +}, { + Zm: MaxOpsBeforeYield, + _F: Scheduler, + hf: PreventSchedulerYield +}); + + +}, +"./node_modules/effect/dist/Scope.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.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. + * + * @since 2.0.0 + */ + +const TypeId = _internal_effect_js__rspack_import_0/* .ScopeTypeId */.kWD; +const CloseableTypeId = _internal_effect_js__rspack_import_0/* .ScopeCloseableTypeId */.obm; +/** + * Service tag for the active resource lifetime. + * + * **When to use** + * + * Use to access the active lifetime when registering finalizers or sharing + * resources with the surrounding scope. + * + * **Example** (Accessing the scope service) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.Scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) + * }) + * + * Effect.runSync(Effect.scoped(program)) + * cleanups // => ["Cleanup"] + * ``` + * + * @category services + * @since 2.0.0 + */ +const Scope = _internal_effect_js__rspack_import_0/* .scopeTag */.DLK; +/** + * Creates a new `Scope` with the specified finalizer strategy. + * + * **Example** (Creating a scope) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 2"))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * cleanups // => ["Cleanup 2", "Cleanup 1"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = _internal_effect_js__rspack_import_0/* .scopeMake */.RWE; +/** + * 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"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = _internal_effect_js__rspack_import_0/* .scopeMakeUnsafe */.d97; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const provide = _internal_effect_js__rspack_import_0/* .provideScope */.AAo; +/** + * Registers an exit-aware finalizer on a scope. + * + * **When to use** + * + * Use when cleanup needs to know whether the scope closed with success, + * failure, or interruption. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes and receives + * the scope's exit value. If the scope is already closed, the finalizer runs + * immediately with the stored exit value. + * + * **Example** (Adding an exit-aware finalizer) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const exits: Array> = [] + * const withResource = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizerExit(scope, (exit) => Effect.sync(() => exits.push(exit))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(withResource) + * exits // => [Exit.void] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizerExit = _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio; +/** + * Registers a finalizer effect on a scope. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes, regardless of + * whether the scope closes successfully or with an error. If the scope is + * already closed, the finalizer runs immediately. + * + * **Example** (Adding finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 2"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 3"))) + * events.push("work") + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * events // => ["work", "cleanup 3", "cleanup 2", "cleanup 1"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_0/* .scopeAddFinalizer */.iLB; +/** + * Creates a closeable child scope registered with a parent scope. + * + * **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) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const nestedScopes = Effect.gen(function*() { + * const parentScope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) + * const childScope = yield* Scope.fork(parentScope, "parallel") + * yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) + * yield* Scope.close(childScope, Exit.void) + * yield* Scope.close(parentScope, Exit.void) + * }) + * + * Effect.runSync(nestedScopes) + * cleanups // => ["child", "parent"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const fork = _internal_effect_js__rspack_import_0/* .scopeFork */.Z$R; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const forkUnsafe = _internal_effect_js__rspack_import_0/* .scopeForkUnsafe */.pSt; +/** + * 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`. + * + * **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"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const close = _internal_effect_js__rspack_import_0/* .scopeClose */.vDJ; +/** + * Closes a scope unsafely with the provided exit value. + * + * **When to use** + * + * Use when implementing lower-level scope machinery that must transition a + * scope to `Closed` immediately and can run the returned finalizer effect when + * one is produced. + * + * **Details** + * + * Returns an effect that runs registered finalizers, or `undefined` when the + * scope was already closed or no finalizers need to run. + * + * **Gotchas** + * + * Ignoring the returned effect skips registered finalizers. + * + * @see {@link close} for the usual effectful close operation that always returns an `Effect` + * + * @category unsafe + * @since 4.0.0 + */ +const closeUnsafe = _internal_effect_js__rspack_import_0/* .scopeCloseUnsafe */.fou; +/** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * + * @category combinators + * @since 2.0.0 + */ +const use = _internal_effect_js__rspack_import_0/* .scopeUse */.mdu; +//# sourceMappingURL=Scope.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Fp: forkUnsafe, + Gt: provide, + LZ: makeUnsafe, + U9: addFinalizer, + VN: close, + a6: addFinalizerExit +}); + + +}, +"./node_modules/effect/dist/Semaphore.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + + +/** + * Creates a `Semaphore` synchronously with the specified total + * number of permits. + * + * **When to use** + * + * Use to construct a semaphore synchronously when an immediate value is + * required outside an Effect workflow. + * + * **Example** (Creating an unsafe semaphore) + * + * ```ts import.meta.vitest + * import { Effect, Semaphore } from "effect" + * + * const semaphore = Semaphore.makeUnsafe(3) + * + * const task = (id: number) => + * semaphore.withPermits(1)( + * Effect.gen(function*() { + * yield* Effect.yieldNow + * return id + * }) + * ) + * + * // Only 3 tasks can run concurrently + * const program = Effect.all([ + * task(1), + * task(2), + * task(3), + * task(4), + * task(5) + * ], { concurrency: "unbounded" }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = permits => new SemaphoreImpl(permits); +const waitForPermits = (self, n, effect) => _internal_effect_js__rspack_import_0/* .callback */.E2r(resume => { + if (self.free >= n) return resume(effect); + const observer = () => { + if (self.free < n) return; + self.waiters.delete(observer); + resume(effect); + }; + self.waiters.add(observer); + return _internal_effect_js__rspack_import_0/* .sync */.OH5(() => { + self.waiters.delete(observer); + }); +}); +class SemaphoreImpl { + waiters = /*#__PURE__*/new Set(); + taken = 0; + permits; + constructor(permits) { + this.permits = permits; + } + get free() { + return this.permits - this.taken; + } + take(n) { + const take = _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) { + return waitForPermits(this, n, take); + } + this.taken += n; + return _internal_effect_js__rspack_import_0/* .succeed */.PyW(n); + }); + return take; + } + takeIfAvailable(n) { + return _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) return _internal_effect_js__rspack_import_0/* .succeed */.PyW(false); + this.taken += n; + return _internal_effect_js__rspack_import_0/* .succeed */.PyW(true); + }); + } + releaseUnsafe(fiber, n) { + this.taken -= n; + if (this.waiters.size > 0) { + fiber.currentDispatcher.scheduleTask(() => { + for (const observer of this.waiters) { + if (this.free <= 0) break; + observer(); + } + }, 0); + } + return this.free; + } + resize(permits) { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => { + this.permits = permits; + if (this.free < 0) return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + this.releaseUnsafe(fiber, 0); + return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + }); + } + release(n) { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => _internal_effect_js__rspack_import_0/* .succeed */.PyW(this.releaseUnsafe(fiber, n))); + } + get releaseAll() { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => _internal_effect_js__rspack_import_0/* .succeed */.PyW(this.releaseUnsafe(fiber, this.taken))); + } + withPermits(n) { + return self => _internal_effect_js__rspack_import_0/* .uninterruptibleMask */.FcF(restore => { + const acquire = _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) { + const wait = waitForPermits(this, n, _internal_effect_js__rspack_import_0/* ["void"] */.rIH); + return _internal_effect_js__rspack_import_0/* .flatMap */.qIB(restore(wait), () => acquire); + } + this.taken += n; + return _internal_effect_js__rspack_import_0/* .onExitPrimitive */.r7h(restore(self), () => { + this.releaseUnsafe(_internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku(), n); + return undefined; + }, true); + }); + return acquire; + }); + } + withPermit = /*#__PURE__*/this.withPermits(1); + withPermitsIfAvailable(n) { + return self => _internal_effect_js__rspack_import_0/* .uninterruptibleMask */.FcF(restore => { + if (this.free < n) return _internal_effect_js__rspack_import_0/* .succeedNone */.lwU; + this.taken += n; + return _internal_effect_js__rspack_import_0/* .onExitPrimitive */.r7h(restore(_internal_effect_js__rspack_import_0/* .asSome */.Xx$(self)), () => { + this.releaseUnsafe(_internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku(), n); + return undefined; + }, true); + }); + } +} +/** + * Creates a `Semaphore` initialized with the specified total number of permits. + * + * **When to use** + * + * Use to create a semaphore inside Effect code for bounding concurrency with + * automatic or manual permit management. + * + * **Example** (Creating a semaphore) + * + * ```ts import.meta.vitest + * import { Effect, Semaphore } from "effect" + * + * const program = Effect.gen(function*() { + * const semaphore = yield* Semaphore.make(2) + * + * const task = (id: number) => + * semaphore.withPermits(1)( + * Effect.gen(function*() { + * yield* Effect.yieldNow + * return id + * }) + * ) + * + * // Run 4 tasks, but only 2 can run concurrently + * return yield* Effect.all([task(1), task(2), task(3), task(4)]) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = permits => internal.sync(() => new SemaphoreImpl(permits)); +/** + * Sets the total number of permits managed by the semaphore. + * + * **When to use** + * + * Use to change the concurrency limit of an existing semaphore while keeping + * current acquisitions in place. + * + * **Details** + * + * Existing acquisitions remain taken after resizing. If the new total is less + * than the currently taken permit count, new acquisitions wait until enough + * permits are released. + * + * @see {@link make} for creating a semaphore with an initial permit count + * @see {@link release} for returning permits without changing semaphore capacity + * + * @category combinators + * @since 4.0.0 + */ +const resize = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.resize(permits)))); +/** + * Runs an effect with the given number of permits and releases the permits when + * the effect completes. + * + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits + * for the duration of that effect. + * + * **Details** + * + * The effect waits until enough permits are available. Acquired permits are + * released when the wrapped effect exits. + * + * @see {@link withPermit} for acquiring exactly one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * + * @category combinators + * @since 4.0.0 + */ +const withPermits = (self, permits, effect) => { + const withPermits = self.withPermits(permits); + return effect ? withPermits(effect) : withPermits; +}; +/** + * Runs an effect with a single permit and releases the permit when the effect + * completes. + * + * **When to use** + * + * Use to guard an effect with exactly one semaphore permit while automatically + * releasing that permit when the effect exits. + * + * @see {@link withPermits} for acquiring more than one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * + * @category combinators + * @since 4.0.0 + */ +const withPermit = (self, effect) => { + if (!effect) return self.withPermit; + return self.withPermit(effect); +}; +/** + * Runs an effect only if the specified number of permits are immediately + * available. + * + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * + * **Details** + * + * When the permits are unavailable, the effect is not run and the result is + * `Option.none`. When permits are available, the effect is run, its result is + * wrapped in `Option.some`, and the acquired permits are released when the + * effect exits. + * + * @see {@link withPermits} for the variant that waits until permits are available + * + * @category combinators + * @since 4.0.0 + */ +const withPermitsIfAvailable = (self, permits, effect) => { + const withPermits = self.withPermitsIfAvailable(permits); + return effect ? withPermits(effect) : withPermits; +}; +/** + * Acquires the specified number of permits and returns the acquired permit + * count. + * + * **When to use** + * + * Use when you need manual permit acquisition for a lower-level protocol with + * explicit acquisition and release control. + * + * **Details** + * + * The effect waits until enough permits are available. + * + * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect + * @see {@link takeIfAvailable} for manually acquiring permits without waiting + * @see {@link release} for returning manually acquired permits + * + * @category combinators + * @since 4.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.take(permits)))); +/** + * Acquires the specified number of permits only if they are immediately + * available. + * + * **When to use** + * + * Use when you need fail-fast manual permit acquisition for a lower-level + * protocol with explicit acquisition and release control. + * + * **Details** + * + * If enough permits are available, they are acquired and the effect returns + * `true`. Otherwise, the effect returns `false` immediately without acquiring + * any permits. + * + * @see {@link take} for the variant that waits until permits are available + * @see {@link release} for returning manually acquired permits + * @see {@link withPermitsIfAvailable} for automatic acquisition and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const takeIfAvailable = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.takeIfAvailable(permits)))); +/** + * Releases the specified number of permits and returns the resulting available + * permits. + * + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. + * + * **Details** + * + * Running the effect releases the requested permits, wakes waiting acquirers + * when permits become available, and returns the current available permit + * count. + * + * **Gotchas** + * + * Manual `take` / `release` usage must keep permit counts balanced. Prefer + * `withPermit` or `withPermits` when the acquisition can be scoped to one + * effect. + * + * @see {@link take} for manually acquiring permits + * @see {@link releaseAll} for returning every currently taken permit + * @see {@link withPermits} for automatic acquire and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const release = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.release(permits)))); +/** + * Releases all permits held by this semaphore and returns the resulting + * available permits. + * + * **When to use** + * + * Use to return every currently taken permit to a semaphore at once, typically + * during cleanup of manual `take` / `release` protocols. + * + * @see {@link release} for releasing a known permit count + * @see {@link withPermits} for automatic acquire and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const releaseAll = self => self.releaseAll; +//# sourceMappingURL=Semaphore.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + LZ: makeUnsafe +}); + + +}, +"./node_modules/effect/dist/Stream.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Cause_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Channel_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Channel.js"); +/* import */ var _Effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var _Function_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_stream_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/stream.js"); +/* import */ var _Option_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Describes effectful sources that emit values over time. + * + * A `Stream` can emit many `A` values, fail with `E`, and require + * services `R` while it is being consumed. Streams are useful for data that is + * pulled in steps, such as values from collections, queues, pubsubs, schedules, + * callbacks, async iterables, or platform streams. The APIs here cover the full + * stream lifecycle: create a stream, transform or combine it, control buffering + * and timing, handle failures, and finally consume it. + * + * @since 2.0.0 + */ +// @effect-diagnostics returnEffectInGen:off + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * Runtime identifier stored on `Stream` values and used by `isStream` to + * recognize them. + * + * **Details** + * + * This marker is part of the runtime representation of `Stream` values. Prefer + * `isStream` when narrowing unknown values. + * + * @see {@link isStream} for the public guard that checks this identifier + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = "~effect/Stream"; +/** + * Checks whether a value is a Stream. + * + * **Example** (Checking whether a value is a Stream) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * Stream.isStream(Stream.make(1, 2, 3)) // => true + * Stream.isStream({ data: [1, 2, 3] }) // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isStream = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +/** + * The default chunk size used by Stream constructors and combinators. + * + * **Example** (Reading the default chunk size) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * Stream.DefaultChunkSize // => 4096 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const DefaultChunkSize = (/* inlined export .DefaultChunkSize */4096); +/** + * Creates a stream from a array-emitting `Channel`. + * + * **Example** (Creating a stream from an array-emitting channel) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Stream } from "effect" + * + * const channel = Channel.succeed([1, 2, 3] as const) + * const stream = Stream.fromChannel(channel) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromChannel = _internal_stream_js__rspack_import_2/* .fromChannel */.E; +/** + * Creates a stream from an effect. + * + * **Example** (Creating a stream from an effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.fromEffect(Effect.succeed(42)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of))); +/** + * Accesses a service from the context and emits it as a single element. + * + * **Example** (Accessing a service as a stream) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.service(Greeter).pipe( + * Stream.map((greeter) => greeter.greet("World")) + * ) + * + * await Effect.runPromise( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}!` + * }), + * Stream.runCollect + * ) + * ) // => ["Hello, World!"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const service = service => fromEffect(Effect.service(service)); +/** + * Optionally accesses a service from the context and emits the result as a + * single element. + * + * **When to use** + * + * Use when you need a stream that emits an optional service from the context + * without requiring that service to be present. + * + * **Example** (Accessing an optional service as a stream) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.serviceOption(Greeter).pipe( + * Stream.map((maybeGreeter) => + * Option.match(maybeGreeter, { + * onNone: () => "No greeter", + * onSome: (greeter) => greeter.greet("World") + * }) + * ) + * ) + * + * await Effect.runPromise( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}!` + * }), + * Stream.runCollect + * ) + * ) // => ["Hello, World!"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const serviceOption = service => fromEffect(Effect.serviceOption(service)); +/** + * Creates a stream that runs the effect and emits no elements. + * + * **Example** (Draining an effect into a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * let drained = false + * await Effect.runPromise( + * Stream.fromEffectDrain(Effect.sync(() => { + * drained = true + * })).pipe(Stream.runDrain) + * ) + * drained // => true + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done()))); +/** + * Creates a stream from an effect producing a value of type `A` which repeats forever. + * + * **Example** (Repeating an effect forever) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * let n = 0 + * const stream = Stream.fromEffectRepeat(Effect.sync(() => ++n)).pipe(Stream.take(5)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(effect, Arr.of))); +/** + * Creates a stream from an effect producing a value of type `A`, which is + * repeated using the specified schedule. + * + * **Example** (Repeating an effect with a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const stream = Stream.fromEffectSchedule(Effect.succeed("ping"), Schedule.recurs(2)) + * await Effect.runPromise(Stream.runCollect(stream)) // => ["ping", "ping", "ping"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(function* () { + const step = yield* Schedule.toStepWithMetadata(schedule); + let s = yield* Effect.provideService(effect, Schedule.CurrentMetadata, Schedule.CurrentMetadata.defaultValue()); + let initial = true; + const pull = Effect.suspend(() => step(s)).pipe(Effect.flatMap(meta => Effect.provideService(effect, Schedule.CurrentMetadata, meta)), Effect.map(next => { + s = next; + return Arr.of(next); + })); + return Effect.suspend(() => { + if (initial) { + initial = false; + return Effect.succeed(Arr.of(s)); + } + return pull; + }); +})); +/** + * Creates a stream that emits `void` immediately once, then emits another + * `void` after each specified interval. + * + * **Example** (Emitting ticks on an interval) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.tick(0).pipe(Stream.take(3), Stream.runCollect)) // => [undefined, undefined, undefined] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const tick = interval => fromPull(Effect.sync(() => { + let first = true; + const effect = Effect.succeed(Arr.of(undefined)); + const delayed = Effect.delay(effect, interval); + return Effect.suspend(() => { + if (first) { + first = false; + return effect; + } + return delayed; + }); +})); +/** + * Creates a stream from a pull effect, such as one produced by `Stream.toPull`. + * + * **Details** + * + * A pull effect yields chunks on demand and completes when the upstream stream ends. + * See `Stream.toPull` for a matching producer. + * + * **Example** (Creating a stream from a pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const source = Stream.make(1, 2, 3) + * const pull = yield* Stream.toPull(source) + * const stream = Stream.fromPull(Effect.succeed(pull)) + * return yield* Stream.runCollect(stream) + * }) + * ) + * + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPull = pull => fromChannel(_Channel_js__rspack_import_1/* .fromPull */.OB(pull)); +/** + * Derives a stream by transforming its pull effect. + * + * **Example** (Transforming a pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const transformed = Stream.transformPull(stream, (pull) => Effect.succeed(pull)) + * + * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPull = (self, f) => fromChannel(_Channel_js__rspack_import_1/* .fromTransform */.Z1((_, scope) => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Channel_js__rspack_import_1/* .toPullScoped */.lB(self.channel, scope), pull => f(pull, scope)))); +/** + * Transforms a stream by effectfully transforming its pull effect. + * + * **Details** + * + * A forked scope is also provided to the transformation function, which is + * closed once the resulting stream has finished processing. + * + * **Example** (Transforming a stream by effectfully transforming its pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Scope, Stream } from "effect" + * + * const finalized: Array = [] + * const stream = Stream.make(1, 2, 3) + * + * const transformed = Stream.transformPullBracket( + * stream, + * (pull, _scope, forkedScope) => + * Effect.gen(function*() { + * yield* Scope.addFinalizer(forkedScope, Effect.sync(() => finalized.push(true))) + * return pull + * }) + * ) + * + * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3] + * finalized // => [true] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPullBracket = (self, f) => fromChannel(Channel.fromTransformBracket((_, scope, forkedScope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope, forkedScope)))); +/** + * Creates a channel from a stream. + * + * **Example** (Converting a stream to a channel) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Stream } from "effect" + * + * const channel = Stream.toChannel(Stream.make(1, 2, 3)) + * const values = await Effect.runPromise(Channel.runCollect(channel)) + * values.flat() // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const toChannel = stream => stream.channel; +/** + * Creates a stream from a callback that can emit values into a queue. + * + * **When to use** + * + * Use when you need callback-based code to emit stream values by offering to a + * `Queue`, or signal stream completion through the `Queue` module APIs. + * + * By default it uses an "unbounded" buffer size. + * You can customize the buffer size and strategy by passing an object as the + * second argument with the `bufferSize` and `strategy` fields. + * + * **Example** (Creating a stream from a callback that can emit values into a queue) + * + * ```ts import.meta.vitest + * import { Effect, Queue, Stream } from "effect" + * + * const stream = Stream.callback((queue) => + * Effect.sync(() => { + * // Emit values to the stream + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * Queue.offerUnsafe(queue, 3) + * // Signal completion + * Queue.endUnsafe(queue) + * }) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = (f, options) => fromChannel(Channel.callbackArray(f, options)); +/** + * Creates an empty stream. + * + * **Example** (Creating an empty stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.runCollect(Stream.empty)) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = /*#__PURE__*/fromChannel(_Channel_js__rspack_import_1/* .empty */.Ie); +/** + * Creates a single-valued pure stream. + * + * **Example** (Creating a single-valued pure stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.runCollect(Stream.succeed(3))) // => [3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeed = value => fromChannel(Channel.succeed(Arr.of(value))); +/** + * Creates a stream from a sequence of values. + * + * **Example** (Creating a stream from a sequence of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = (...values) => fromArray(values); +/** + * Creates a stream that synchronously evaluates a function and emits the result as a single value. + * + * **Details** + * + * The function is evaluated each time the stream is run. + * + * **Example** (Evaluating a value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.sync(() => 2 + 1).pipe(Stream.runCollect)) // => [3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate()))); +/** + * Creates a lazily constructed stream. + * + * **Details** + * + * The stream factory is evaluated each time the stream is run. + * + * **Example** (Creating a lazily constructed stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.suspend(() => Stream.make(1, 2, 3)).pipe(Stream.runCollect)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = stream => fromChannel(Channel.suspend(() => stream().channel)); +/** + * Terminates with the specified error. + * + * **Example** (Failing a stream) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * await Effect.runPromise(Effect.exit(Stream.runCollect(Stream.fail("Uh oh!")))) // => Exit.fail("Uh oh!") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fail = error => fromChannel(Channel.fail(error)); +/** + * Terminates with the specified lazily evaluated error. + * + * **Example** (Failing a stream lazily) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * const stream = Stream.failSync(() => "Uh oh!") + * + * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail("Uh oh!") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = evaluate => fromChannel(Channel.failSync(evaluate)); +/** + * Creates a stream that fails with the specified `Cause`. + * + * **Example** (Failing with a cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const stream = Stream.failCause(Cause.fail("Database connection failed")).pipe( + * Stream.catchCause(() => Stream.succeed("recovered")) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => ["recovered"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = cause => fromChannel(Channel.failCause(cause)); +/** + * The stream that dies with the specified defect. + * + * **Example** (Dying with a defect) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Stream } from "effect" + * + * const defect = new Error("Boom") + * const stream = Stream.die(defect) + * + * await Effect.runPromise(Effect.exit(Stream.runCollect(stream))) // => Exit.failCause(Cause.die(defect)) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const die = defect => fromChannel(Channel.die(defect)); +/** + * The stream that always fails with the specified lazily evaluated `Cause`. + * + * **Example** (Failing with a lazy cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Stream } from "effect" + * + * const stream = Stream.failCauseSync(() => + * Cause.fail("Connection timeout after retries") + * ) + * + * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail("Connection timeout after retries") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evaluate)); +/** + * Creates a stream that consumes values from an iterator. + * + * **Details** + * + * The `maxChunkSize` parameter controls how many values are pulled per chunk. + * + * **Example** (Consuming values from an iterator) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * function* numbers() { + * yield 1 + * yield 2 + * yield 3 + * } + * + * const stream = Stream.fromIteratorSucceed(numbers()) + * + * const program = Effect.gen(function* () { + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize)); +/** + * Creates a new `Stream` from an iterable collection of values. + * + * **Details** + * + * - `chunkSize`: Maximum number of values emitted per chunk. + * + * **Example** (Creating a stream from an iterable) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const numbers = [1, 2, 3] + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromIterable(numbers) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = (iterable, options) => Array.isArray(iterable) && options?.chunkSize === undefined ? fromArray(iterable) : fromChannel(Channel.fromIterableArray(iterable, options?.chunkSize)); +/** + * Creates a stream from an effect producing an iterable of values. + * + * **When to use** + * + * Use when the iterable must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an iterable effect) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class UserRepo extends Context.Service> + * }>()("UserRepo") {} + * + * const listUsers = Effect.service(UserRepo).pipe( + * Effect.andThen((repo) => repo.list) + * ) + * + * const stream = Stream.fromIterableEffect(listUsers) + * + * const program = Effect.gen(function*() { + * const users = yield* stream.pipe( + * Stream.provideService(UserRepo, { + * list: Effect.succeed(["user1", "user2"]) + * }), + * Stream.runCollect + * ) + * users // => ["user1", "user2"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIterable)); +/** + * Creates a stream by repeatedly running an effect that yields an iterable of values. + * + * **Example** (Repeating an iterable effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromIterableEffectRepeat(Effect.succeed([1, 2])).pipe( + * Stream.take(5) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 1, 2, 1] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(iterable), fromIterable); +/** + * Creates a stream from an array of values. + * + * **Example** (Creating a stream from an array of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArray([1, 2, 3]) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArray = array => _Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(array) ? fromChannel(_Channel_js__rspack_import_1/* .succeed */.Py(array)) : empty; +/** + * Creates a stream from an effect that produces an array of values. + * + * **When to use** + * + * Use when the array must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an effect that produces an array of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArrayEffect(Effect.succeed(["Ada", "Grace"])) + * const values = yield* Stream.runCollect(stream) + * values // => ["Ada", "Grace"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray)); +/** + * Creates a stream from an arbitrary number of arrays. + * + * **Example** (Creating a stream from an arbitrary number of arrays) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArrays([1, 2], [3, 4]) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty))); +/** + * Creates a stream that pulls values from a `Queue.Dequeue`. + * + * **Details** + * + * The stream emits non-empty batches of queued values and ends when the queue + * fails with `Cause.Done`; other queue failures are propagated. + * + * **Example** (Creating a stream from a queue of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.unbounded() + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * yield* Queue.end(queue) + * + * const stream = Stream.fromQueue(queue) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue)); +/** + * Creates a stream from a subscription to a `PubSub`. + * + * **Example** (Creating a stream from a subscription to a PubSub) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, PubSub, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 3 }) + * + * const fiber = yield* Stream.fromPubSub(pubsub).pipe( + * Stream.take(3), + * Stream.runCollect, + * Effect.forkChild + * ) + * + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * + * const values = yield* Fiber.join(fiber) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub)); +/** + * Creates a stream from a PubSub of `Take` values. + * + * **Details** + * + * `Take` values include end and failure signals. + * + * **Example** (Creating a stream from PubSub takes) + * + * ```ts import.meta.vitest + * import { Effect, Exit, PubSub, Stream, Take } from "effect" + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded>({ + * replay: 3 + * }) + * + * yield* PubSub.publish(pubsub, [1]) + * yield* PubSub.publish(pubsub, [2]) + * yield* PubSub.publish(pubsub, Exit.succeed(undefined)) + * + * const values = yield* Stream.fromPubSubTake(pubsub).pipe(Stream.runCollect) + * values // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsub)); +/** + * Creates a stream from a lazily supplied Web `ReadableStream`. + * + * **Details** + * + * The stream reads from a `ReadableStreamDefaultReader`, maps read failures + * with `onError`, and closes the reader when the stream finalizes. By default + * the reader is canceled; set `releaseLockOnEnd` to release the lock instead. + * + * **Example** (Creating a stream from a ReadableStream) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} + * + * const readableStream = new ReadableStream({ + * start(controller) { + * controller.enqueue(1) + * controller.enqueue(2) + * controller.enqueue(3) + * controller.close() + * } + * }) + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromReadableStream({ + * evaluate: () => readableStream, + * onError: (cause) => new StreamError({ cause }) + * }) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromReadableStream = options => fromChannel(Channel.fromReadableStream(options)); +/** + * Creates a stream from an AsyncIterable. + * + * **Example** (Creating a stream from an AsyncIterable) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} + * + * const iterable = (async function*() { + * yield 1 + * yield 2 + * yield 3 + * })() + * + * await Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause })) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * })) + * + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.fromAsyncIterableArray(iterable, onError)); +/** + * Creates a stream that emits each output of a schedule that does not require input, + * for as long as the schedule continues. + * + * **Example** (Creating a stream from a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const schedule = Schedule.recurs(3) + * const stream = Stream.fromSchedule(schedule) + * const values = yield* Stream.runCollect(stream) + * values // => [0, 1, 2] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => Pull.catchDone(Effect.map(step(void 0), Arr.of), () => Cause.done()))); +/** + * Creates a stream from a PubSub subscription. + * + * **When to use** + * + * Use when you already have a `PubSub.Subscription` and want to expose its + * messages as a `Stream`, with `Stream.take` or cancellation controlling how + * many values are consumed. + * + * **Example** (Creating a stream from a PubSub subscription) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded() + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * + * const stream = Stream.fromSubscription(subscription) + * const values = yield* stream.pipe(Stream.take(2), Stream.runCollect) + * values // => [1, 2] + * })) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscription = pubsub => fromChannel(Channel.fromSubscriptionArray(pubsub)); +/** + * Creates a stream from an event listener. + * + * **Example** (Creating a stream from an event listener) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * class NumberTarget implements Stream.EventListener { + * addEventListener(event: string, f: (event: number) => void) { + * if (event === "data") { + * f(1) + * f(2) + * f(3) + * } + * } + * removeEventListener(_event: string, _f: (event: number) => void) {} + * } + * + * await Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromEventListener(new NumberTarget(), "data").pipe( + * Stream.take(3) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * })) + * + * ``` + * + * @category constructors + * @since 3.1.0 + */ +const fromEventListener = (target, type, options) => callback(queue => { + function emit(event) { + Queue.offerUnsafe(queue, event); + } + return Effect.acquireRelease(Effect.sync(() => target.addEventListener(type, emit, options)), () => Effect.sync(() => target.removeEventListener(type, emit, options))); +}, { + bufferSize: typeof options === "object" ? options.bufferSize : undefined +}); +/** + * Creates a stream by repeatedly applying an effectful step function to a + * state. + * + * **Details** + * + * Each `readonly [value, nextState]` result emits `value` and continues with + * `nextState`; returning `undefined` ends the stream. + * + * **Example** (Unfolding stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const)) + * const values = yield* Stream.runCollect(stream.pipe(Stream.take(5))) + * values // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (s, f) => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let state = s; + return _Effect_js__rspack_import_3/* .flatMap */.qIB(_Effect_js__rspack_import_3/* .suspend */.DYE(() => f(state)), next => { + if (next === undefined) return _Cause_js__rspack_import_5/* .done */.Vw(); + state = next[1]; + return _Effect_js__rspack_import_3/* .succeed */.PyW(_Array_js__rspack_import_4.of(next[0])); + }); +})); +/** + * Creates a stream by repeatedly evaluating an effectful page function. + * + * **When to use** + * + * Use to consume paginated APIs where each step returns a batch of values + * together with an optional next state. + * + * **Details** + * + * This is similar to {@link unfold}, but each step can emit zero or more values + * and independently decide whether another state should be requested. + * + * **Example** (Paginating stream state) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.paginate(0, (n: number) => + * Effect.succeed( + * [ + * [n], + * n < 3 ? Option.some(n + 1) : Option.none() + * ] as const + * )) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [0, 1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const paginate = (s, f) => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let state = s; + let done = false; + return _Effect_js__rspack_import_3/* .suspend */.DYE(function loop() { + if (done) return _Cause_js__rspack_import_5/* .done */.Vw(); + return _Effect_js__rspack_import_3/* .flatMap */.qIB(f(state), ([a, s]) => { + if (_Option_js__rspack_import_6.isNone(s)) { + done = true; + } else { + state = s.value; + } + if (!_Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(a)) return loop(); + return _Effect_js__rspack_import_3/* .succeed */.PyW(a); + }); + }); +})); +/** + * Creates an infinite stream by repeatedly applying a function to a seed value. + * + * **Example** (Iterating from a seed value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.iterate(1, (n) => n + 1).pipe(Stream.take(3)) + * + * const program = Effect.gen(function* () { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const iterate = (value, next) => unfold(value, a => Effect.succeed([a, next(a)])); +/** + * Constructs a stream from a range of integers, including both endpoints. + * + * **Details** + * + * If the provided `min` is greater than `max`, the stream will not emit any + * values. + * + * **Example** (Creating a numeric range) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.range(1, 5).pipe(Stream.runCollect) + * values // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const range = (min, max, chunkSize = (/* inlined export .DefaultChunkSize */4096)) => min > max ? empty : fromPull(Effect.sync(() => { + const size = Math.max(1, chunkSize); + let start = min; + let done = false; + return Effect.suspend(() => { + if (done) return Cause.done(); + const remaining = max - start + 1; + if (remaining > size) { + const chunk = Arr.range(start, start + size - 1); + start += size; + return Effect.succeed(chunk); + } + const chunk = Arr.range(start, start + remaining - 1); + done = true; + return Effect.succeed(chunk); + }); +})); +/** + * The stream that never produces any value or fails with any error. + * + * **Example** (Creating a never-ending stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.never.pipe( + * Stream.take(0), + * Stream.runCollect + * ) + * + * await Effect.runPromise(program) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = /*#__PURE__*/fromChannel(_Channel_js__rspack_import_1/* .never */.Zm); +/** + * Creates a stream produced from an `Effect`. + * + * **Example** (Unwrapping a stream effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const effect = Effect.succeed(Stream.make(1, 2, 3)) + * + * const stream = Stream.unwrap(effect) + * + * const program = Effect.gen(function*() { + * const chunk = yield* Stream.runCollect(stream) + * chunk // => [ 1, 2, 3 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unwrap = effect => fromChannel(_Channel_js__rspack_import_1/* .unwrap */.oA(_Effect_js__rspack_import_3/* .map */.TjK(effect, toChannel))); +/** + * Runs a stream that requires `Scope` in a managed scope, ensuring its + * finalizers are run when the stream completes. + * + * **Example** (Scoping a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.scoped( + * Stream.fromEffect( + * Effect.acquireRelease( + * Effect.sync(() => { + * events.push("acquire") + * return "resource" + * }), + * () => Effect.sync(() => events.push("release")) + * ) + * ) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => ["resource"] + * events // => ["acquire", "release"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const scoped = self => fromChannel(Channel.scoped(self.channel)); +/** + * Transforms the elements of this stream using the supplied function. + * + * **Example** (Mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.map((n, i) => n + i)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 3, 5] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => suspend(() => { + let i = 0; + return fromChannel(Channel.map(self.channel, Arr.map(o => f(o, i++)))); +})))); +/** + * Maps both the failure and success channels of a stream. + * + * **Example** (Mapping both the failure and success channels of a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const mapper = { + * onFailure: (error: string) => `error: ${error}`, + * onSuccess: (value: number) => value * 2 + * } + * + * const program = Effect.gen(function*() { + * const success = yield* Stream.make(1, 2).pipe( + * Stream.mapBoth(mapper), + * Stream.runCollect + * ) + * success // => [ 2, 4 ] + * + * const failure = yield* Stream.fail("boom").pipe( + * Stream.mapBoth(mapper), + * Stream.catch((error: string) => Stream.succeed(error)), + * Stream.runCollect + * ) + * failure // => [ 'error: boom' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => self.pipe(map(options.onSuccess), mapError(options.onFailure))))); +/** + * Transforms each emitted chunk using the provided function, which receives the chunk and its index. + * + * **Example** (Mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.mapArray((chunk, index) => Array.map(chunk, (n) => n + index)), + * Stream.runCollect + * ) + * result // => [ 1, 2, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.map(self.channel, f))))); +/** + * Maps over elements of the stream with the specified effectful function. + * + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.make(1, 2, 3) + * + * const mappedStream = stream.pipe( + * Stream.mapEffect((n) => + * Effect.sync(() => { + * events.push(`Processing: ${n}`) + * return n * 2 + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(mappedStream) + * result // => [2, 4, 6] + * }) + * + * await Effect.runPromise(program) + * events // => ["Processing: 1", "Processing: 2", "Processing: 3"] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => self.channel.pipe(_Channel_js__rspack_import_1/* .flattenArray */.ed, _Channel_js__rspack_import_1/* .mapEffect */.WK(f, options), _Channel_js__rspack_import_1/* .map */.Tj(_Array_js__rspack_import_4.of), fromChannel)); +/** + * Flattens a stream of `Effect` values into a stream of their results. + * + * **When to use** + * + * Use when stream elements already are effects and their successes should become + * stream elements while their failures enter the stream error channel. + * + * **Example** (Flattening a stream of Effect values into a stream of their results) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(Effect.succeed(1), Effect.succeed(2), Effect.succeed(3)) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream.pipe(Stream.flattenEffect())) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flattenEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => mapEffect(self, identity, options)))); +/** + * Maps over non-empty array chunks emitted by the stream effectfully. + * + * **When to use** + * + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. + * + * **Example** (Effectfully mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3, 4]).pipe( + * Stream.rechunk(2), + * Stream.mapArrayEffect((chunk, index) => + * Effect.succeed(Array.map(chunk, (n) => n + index * 10)) + * ), + * Stream.runCollect + * ) + * result // => [ 1, 2, 13, 14 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.mapEffect(self.channel, f))))); +/** + * Lifts failures and successes into a `Result`, yielding a stream that cannot fail. + * + * **Details** + * + * The stream ends after the first failure, emitting a `Result.fail` value. + * + * **Example** (Converting failures to results) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const results = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.result, + * Stream.map(Result.match({ + * onFailure: (error) => `failure: ${error}`, + * onSuccess: (value) => `success: ${value}` + * })), + * Stream.runCollect + * ) + * results // => [ 'success: 1', 'success: 2', 'failure: boom' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const result = self => self.pipe(map(Result.succeed), catch_(e => succeed(Result.fail(e)))); +/** + * Runs the provided effect for each element while preserving the elements. + * + * **Example** (Tapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.tap((n) => Effect.sync(() => events.push(`before mapping: ${n}`))), + * Stream.map((n) => n * 2), + * Stream.tap((n) => Effect.sync(() => events.push(`after mapping: ${n}`))), + * Stream.runCollect + * ) + * + * result // => [2, 4, 6] + * }) + * + * await Effect.runPromise(program) + * events // => ["before mapping: 1", "after mapping: 2", "before mapping: 2", "after mapping: 4", "before mapping: 3", "after mapping: 6"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => mapEffect(self, a => _Effect_js__rspack_import_3.as(f(a), a), options)); +/** + * Returns a stream that effectfully "peeks" at elements and failures. + * + * **Example** (Tapping values and errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapBoth({ + * onElement: (value) => Effect.sync(() => events.push(`seen: ${value}`)), + * onError: (error) => Effect.sync(() => events.push(`error: ${error}`)) + * }), + * Stream.catch(() => Stream.make(3)) + * ) + * const result = yield* Stream.runCollect(stream) + * result // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["seen: 1", "seen: 2", "error: boom"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => self.pipe(tapError(options.onError), tap(options.onElement, { + concurrency: options.concurrency +}))))); +/** + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Ref, Sink, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const seen = yield* Ref.make>([]) + * const sink = Sink.forEach((value: number) => + * Ref.update(seen, (items) => [...items, value]) + * ) + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.tapSink(sink), + * Stream.runCollect + * ) + * const tapped = yield* Ref.get(seen) + * tapped // => [ 1, 2, 3 ] + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapSink = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => transformPullBracket(self, Effect.fnUntraced(function* (pull, _, scope) { + const upstreamLatch = Latch.makeUnsafe(); + const sinkLatch = Latch.makeUnsafe(); + let chunk = undefined; + let causeSink = undefined; + let sinkDone = false; + let streamDone = false; + const sinkUpstream = upstreamLatch.whenOpen(Effect.suspend(() => { + if (chunk) { + const arr = chunk; + chunk = undefined; + if (!streamDone) upstreamLatch.closeUnsafe(); + return Effect.as(sinkLatch.open, arr); + } + return Cause.done(); + })); + yield* Effect.suspend(() => sink.transform(sinkUpstream, scope)).pipe(eff => Effect.onExitPrimitive(eff, exit => { + sinkDone = true; + if (Exit.isFailure(exit)) { + causeSink = exit.cause; + } + return sinkLatch.open; + }, true), Effect.forkIn(scope)); + const pullAndOffer = pull.pipe(Effect.flatMap(chunk_ => { + chunk = chunk_; + sinkLatch.closeUnsafe(); + upstreamLatch.openUnsafe(); + return Effect.as(sinkLatch.await, chunk_); + }), Pull.catchDone(() => { + streamDone = true; + sinkLatch.closeUnsafe(); + upstreamLatch.openUnsafe(); + return Effect.flatMap(sinkLatch.await, () => Cause.done()); + })); + return Effect.suspend(() => { + if (causeSink) { + return Effect.failCause(causeSink); + } else if (sinkDone) { + return pull; + } + return pullAndOffer; + }); +}))))); +/** + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flat mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.flatMap((n) => Stream.make(n, n * 2)), + * Stream.runCollect + * ) + * values // => [ 1, 2, 2, 4, 3, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => self.channel.pipe(_Channel_js__rspack_import_1/* .flattenArray */.ed, _Channel_js__rspack_import_1/* .flatMap */.qI(a => f(a).channel, options), fromChannel)); +/** + * Switches to the latest stream produced by the mapping function, interrupting + * the previous stream when a new element arrives. + * + * **Example** (Switching to the latest stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make(1, 2, 3).pipe( + * Stream.switchMap((n) => (n === 3 ? Stream.make(n) : Stream.never)), + * Stream.runCollect + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* program + * result // => [ 3 ] + * })) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const switchMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.switchMap(a => f(a).channel, options), fromChannel)))); +/** + * Flattens a stream of streams into a single stream. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * strict order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flattening nested streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const streamOfStreams = Stream.make( + * Stream.make(1, 2), + * Stream.make(3, 4), + * Stream.make(5, 6) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(Stream.flatten(streamOfStreams)) + * values // => [ 1, 2, 3, 4, 5, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, options) => flatMap(self, _Function_js__rspack_import_7/* .identity */.D_, options)); +/** + * Flattens a stream of non-empty arrays into a stream of elements. + * + * **Example** (Flattening a stream of non-empty arrays into a stream of elements) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const stream = Stream.make(Array.make(1, 2), Array.make(3)) + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.runCollect(Stream.flattenArray(stream)) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flattenArray = self => fromChannel(Channel.flattenArray(self.channel)); +/** + * Converts this stream to one that runs its effects but emits no elements. + * + * **Example** (Draining stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 6).pipe(Stream.drain, Stream.runCollect) + * result // => [] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const drain = self => fromChannel(Channel.drain(self.channel)); +/** + * Runs the provided stream in the background while this stream runs, interrupting it + * when this stream completes and failing if the background stream fails or defects. + * + * **Example** (Draining a stream in the background) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const foreground = Stream.make(1, 2) + * const background = Stream.fromEffect(Effect.sync(() => events.push("background task"))) + * + * const program = Effect.gen(function*() { + * const values = yield* foreground.pipe( + * Stream.drainFork(background), + * Stream.runCollect + * ) + * values // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * events // => ["background task"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const drainFork = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => mergeEffect(self, runDrain(that))))); +/** + * Repeats the entire stream according to the provided schedule. + * + * **Example** (Repeating a stream on a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.make(1).pipe( + * Stream.repeat(Schedule.recurs(4)), + * Stream.runCollect + * ) + * + * result // => [ 1, 1, 1, 1, 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => fromChannel(Channel.repeat(self.channel, schedule))))); +/** + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.schedule(Schedule.recurs(3)), + * Stream.runCollect + * ) + * + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => self.channel.pipe(Channel.flattenArray, Channel.schedule(schedule), Channel.map(Arr.of), fromChannel)))); +/** + * Ends the stream if it does not produce a value within the specified duration. + * + * **Example** (Timing out a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1).pipe( + * Stream.concat(Stream.never), + * Stream.timeout("1 second"), + * Stream.runCollect + * ) + * values // => [ 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timeout = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, duration) => timeoutOrElse(self, { + duration, + orElse: () => empty +})))); +/** + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category delays & timeouts + * @since 4.0.0 + */ +const timeoutOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const duration = Duration.fromInputUnsafe(options.duration); + if (!Duration.isFinite(duration)) return self; + if (Duration.isZero(duration)) return suspend(options.orElse); + const timeoutSymbol = Symbol(); + return catchCause(suspend(() => { + const parent = Fiber.getCurrent(); + const clock = parent.getRef(Clock); + const durationMs = Duration.toMillis(duration); + let deadline = undefined; + const latch = Latch.makeUnsafe(false); + return merge(transformPull(self, (pull, _scope) => Effect.suspend(() => { + deadline = clock.currentTimeMillisUnsafe() + durationMs; + latch.openUnsafe(); + return pull; + }).pipe(Effect.map(arr => { + latch.closeUnsafe(); + deadline = undefined; + return arr; + }), Effect.succeed)), fromEffectDrain(Effect.gen(function* () { + while (true) { + yield* latch.await; + if (deadline === undefined) continue; + yield* Effect.sleep(deadline - clock.currentTimeMillisUnsafe()); + if (deadline === undefined) continue; + const remaining = deadline - clock.currentTimeMillisUnsafe(); + if (remaining > 0) continue; + return yield* Effect.die(timeoutSymbol); + } + })), { + haltStrategy: "left" + }); + }), cause => { + const isTimeout = cause.reasons.find(r => r._tag === "Die" && r.defect === timeoutSymbol); + if (isTimeout) return options.orElse(); + return failCause(cause); + }); +}))); +/** + * Repeats each element of the stream according to the provided schedule, + * including the original emission. + * + * **Example** (Repeating stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make("A", "B", "C").pipe( + * Stream.repeatElements(Schedule.recurs(1)), + * Stream.runCollect + * ) + * values // => [ 'A', 'A', 'B', 'B', 'C', 'C' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const repeatElements = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => fromChannel(Channel.fromTransform((upstream, scope) => Effect.map(Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope), pullElement => { + let pullRepeat = undefined; + const pull = Effect.gen(function* () { + const element = yield* pullElement; + const chunk = Arr.of(element); + const step = yield* Schedule.toStepWithSleep(schedule); + pullRepeat = step(element).pipe(Effect.as(chunk), Pull.catchDone(_ => { + pullRepeat = undefined; + return pull; + })); + return chunk; + }); + return Effect.suspend(() => pullRepeat ?? pull); +})))))); +/** + * Repeats this stream forever. + * + * **Example** (Repeating a stream forever) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("A", "B").pipe( + * Stream.forever, + * Stream.take(5) + * ) + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.runCollect(stream) + * output // => [ 'A', 'B', 'A', 'B', 'A' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const forever = self => fromChannel(Channel.forever(self.channel)); +/** + * Flattens the iterables emitted by this stream into the stream's structure. + * + * **Example** (Flattening iterable values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make([1, 2], [3, 4]).pipe(Stream.flattenIterable) + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const flattenIterable = self => flatMap(self, fromIterable); +/** + * Unwraps `Take` values, emitting elements from non-empty arrays and ending or + * failing when the `Exit` signals completion. + * + * **Example** (Flattening Take values) + * + * ```ts import.meta.vitest + * import { Array, Effect, Exit, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const takes = Stream.make( + * Array.make(1, 2), + * Array.make(3), + * Exit.succeed(undefined) + * ) + * + * const values = yield* Stream.flattenTake(takes).pipe(Stream.runCollect) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flattenTake = self => self.channel.pipe(Channel.flattenArray, Channel.flattenTake, fromChannel); +/** + * Concatenates two streams, emitting all elements from the first stream + * followed by all elements from the second stream. + * + * **Example** (Concatenating streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.concat(Stream.make(1, 2, 3), Stream.make(4, 5, 6)) + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3, 4, 5, 6 ] + * })) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const concat = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, that) => flatten(fromArray([self, that]))); +/** + * Prepends the values from the provided iterable before the stream's elements. + * + * **Example** (Prepending values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(3, 4).pipe( + * Stream.prepend([1, 2]), + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, values) => concat(fromIterable(values), self)))); +/** + * Merges two streams, emitting elements from both as they arrive. + * + * **Details** + * + * By default, the merged stream ends when both streams end. Use + * `haltStrategy` to change the termination behavior. + * + * **Example** (Merging stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const fast = Stream.make(1, 2, 3) + * const slow = Stream.fromEffect(Effect.delay(Effect.succeed(4), "50 millis")) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(Stream.merge(fast, slow)) + * result // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel(Channel.merge(toChannel(self), toChannel(that), options))))); +/** + * Merges this stream with a background effect, keeping the stream's elements. + * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * + * The effect runs concurrently, fails the stream if it fails, and is interrupted + * when the stream completes. + * + * **Example** (Merging with a background effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.mergeEffect(Effect.sync(() => events.push("side task"))), + * Stream.runCollect + * ) + * + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["side task"] + * ``` + * + * @category merging + * @since 4.0.0 + */ +const mergeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => self.channel.pipe(Channel.mergeEffect(effect), fromChannel)))); +/** + * Merges this stream and the specified stream together, tagging values from the + * left stream as `Result.succeed` and values from the right stream as `Result.fail`. + * + * **When to use** + * + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. + * + * **Example** (Merging streams into results) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const left = Stream.fromEffect(Effect.succeed("left")) + * const right = Stream.fromEffect(Effect.delay(Effect.succeed("right"), "10 millis")) + * + * const merged = left.pipe( + * Stream.mergeResult(right), + * Stream.map( + * Result.match({ + * onFailure: (value) => `right:${value}`, + * onSuccess: (value) => `left:${value}` + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(merged) + * result // => [ 'left:left', 'right:right' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 4.0.0 + */ +const mergeResult = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => merge(map(self, Result.succeed), map(that, Result.fail))))); +/** + * Merges two streams while emitting only the values from the left stream. + * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * + * The right stream still runs for its effects, and any failures from the right + * stream are propagated. The merged stream completes when the left stream + * completes, interrupting the right stream. + * + * **Example** (Merging streams while keeping left values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const values = yield* left.pipe(Stream.mergeLeft(right), Stream.runCollect) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const mergeLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => mergeEffect(left, runDrain(right))))); +/** + * Merges this stream and the specified stream together, emitting only the + * values from the right stream while the left stream runs for its effects. + * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * + * The merged stream ends when the right stream completes, interrupting the + * left stream. Failures from the left stream still fail the merged stream. + * + * **Example** (Merging streams while keeping right values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const left = Stream.make("left-1", "left-2").pipe( + * Stream.tap(() => Effect.sync(() => undefined)) + * ) + * const right = Stream.make(1, 2) + * + * const merged = Stream.mergeRight(left, right) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(merged) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const mergeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => mergeEffect(right, runDrain(left))))); +/** + * Merges a collection of streams, running up to the specified number concurrently. + * + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const streams = [ + * Stream.fromEffect(Effect.delay(Effect.succeed("A"), "20 millis")), + * Stream.fromEffect(Effect.delay(Effect.succeed("B"), "10 millis")) + * ] + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.mergeAll(streams, { concurrency: 2 }).pipe( + * Stream.runCollect + * ) + * values // => [ 'B', 'A' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 + */ +const mergeAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (streams, options) => flatten(fromIterable(streams), options)))); +/** + * Creates the cartesian product of two streams, running the `right` stream for + * each element in the `left` stream. + * + * **Details** + * + * See also `Stream.zip` for the more common point-wise variant. + * + * **Example** (Computing cartesian products) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const values = yield* Stream.runCollect(Stream.cross(left, right)) + * values // => [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const cross = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => crossWith(left, right, (l, r) => [l, r])))); +/** + * Creates a cartesian product of elements from two streams using a function. + * + * **Details** + * + * The `right` stream is rerun for every element in the `left` stream. + * + * See also `Stream.zipWith` for the more common point-wise variant. + * + * **Example** (Combining cartesian products) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const combined = Stream.crossWith(left, right, (n, s) => `${n}-${s}`) + * const result = yield* Stream.runCollect(combined) + * result // => [ '1-a', '1-b', '2-a', '2-b' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const crossWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => flatMap(left, l => map(right, r => f(l, r)))))); +/** + * Zips two streams point-wise with a combining function, ending when either stream ends. + * + * **Example** (Zipping streams with a function) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3, 4, 5, 6) + * const stream2 = Stream.make("a", "b", "c") + * + * const zipped = Stream.zipWith(stream1, stream2, (n, s) => `${n}-${s}`) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ '1-a', '2-b', '3-c' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => zipWithArray(left, right, zipArrays(f))))); +const zipArrays = f => (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const result = []; + for (let i = 0; i < minLength; i++) { + result.push(f(leftArr[i], rightArr[i])); + } + return [result, leftArr.slice(minLength), rightArr.slice(minLength)]; +}; +/** + * Zips two streams by applying a function to non-empty arrays of elements. + * + * **Details** + * + * The function returns output plus leftover arrays that carry into the next pull. + * + * **Example** (Zipping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const left = Stream.fromArrays([1, 2, 3], [4, 5]) + * const right = Stream.fromArrays(["a", "b"], ["c", "d", "e"]) + * + * const zipped = Stream.zipWithArray(left, right, (leftChunk, rightChunk) => { + * const minLength = Math.min(leftChunk.length, rightChunk.length) + * const output = Array.makeBy(minLength, (i) => [leftChunk[i], rightChunk[i]] as const) + * + * return [output, leftChunk.slice(minLength), rightChunk.slice(minLength)] + * }) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ], [ 4, 'd' ], [ 5, 'e' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 4.0.0 + */ +const zipWithArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_, scope) { + const pullLeft = yield* Channel.toPullScoped(left.channel, scope); + const pullRight = yield* Channel.toPullScoped(right.channel, scope); + const pullBoth = Effect.gen(function* () { + const fiberLeft = yield* Effect.forkIn(pullLeft, scope); + const fiberRight = yield* Effect.forkIn(pullRight, scope); + return yield* Fiber.joinAll([fiberLeft, fiberRight]); + }); + let state = { + _tag: "PullBoth" + }; + const pull = Effect.gen(function* () { + const [left, right] = state._tag === "PullBoth" ? yield* pullBoth : state._tag === "PullLeft" ? [yield* pullLeft, state.rightArray] : [state.leftArray, yield* pullRight]; + const result = f(left, right); + if (Arr.isReadonlyArrayNonEmpty(result[1])) { + state = { + _tag: "PullRight", + leftArray: result[1] + }; + } else if (Arr.isReadonlyArrayNonEmpty(result[2])) { + state = { + _tag: "PullLeft", + rightArray: result[2] + }; + } else { + state = { + _tag: "PullBoth" + }; + } + return result[0]; + }); + return pull; +})))))); +/** + * Zips this stream with another point-wise and emits tuples of elements from + * both streams. The new stream ends when either stream ends. + * + * **Example** (Zipping streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3) + * const stream2 = Stream.make("a", "b", "c") + * + * const zipped = Stream.zip(stream1, stream2) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, (a, a2) => [a, a2])))); +/** + * Zips this stream with another point-wise and keeps only the values from + * the left stream. + * + * **Details** + * + * The resulting stream ends when either side ends. + * + * **Example** (Zipping streams while keeping left values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3, 4) + * const stream2 = Stream.make("a", "b") + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipLeft(stream1, stream2).pipe(Stream.runCollect) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const output = leftArr.slice(0, minLength); + const leftoverLeft = leftArr.slice(minLength); + const leftoverRight = rightArr.slice(minLength); + return [output, leftoverLeft, leftoverRight]; +})))); +/** + * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. + * + * **Example** (Zipping streams while keeping right values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2) + * const stream2 = Stream.make("a", "b", "c", "d") + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipRight(stream1, stream2).pipe(Stream.runCollect) + * result // => [ 'a', 'b' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const output = rightArr.slice(0, minLength); + const leftoverLeft = leftArr.slice(minLength); + const leftoverRight = rightArr.slice(minLength); + return [output, leftoverLeft, leftoverRight]; +})))); +/** + * Zips this stream with another point-wise and emits tuples of elements from + * both streams, flattening the left tuple. + * + * **Details** + * + * The new stream will end when one of the sides ends. + * + * **Example** (Zipping and flattening tuples) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream1 = Stream.make( + * [1, "a"] as const, + * [2, "b"] as const, + * [3, "c"] as const + * ) + * const stream2 = Stream.make("x", "y", "z") + * const result = yield* Stream.zipFlatten(stream1, stream2).pipe(Stream.runCollect) + * + * result // => [ [ 1, 'a', 'x' ], [ 2, 'b', 'y' ], [ 3, 'c', 'z' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipFlatten = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, (a, a2) => [...a, a2])))); +/** + * Zips this stream together with the index of elements. + * + * **Example** (Zipping elements with indices) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const indexed = yield* Stream.make("a", "b", "c", "d").pipe( + * Stream.zipWithIndex, + * Stream.runCollect + * ) + * indexed // => [ [ 'a', 0 ], [ 'b', 1 ], [ 'c', 2 ], [ 'd', 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithIndex = self => map(self, (a, i) => [a, i]); +/** + * Zips each element with the next element, pairing the final element with + * `Option.none()`. + * + * **Example** (Zipping elements with next values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4)) + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [[1, Option.some(2)], [2, Option.some(3)], [3, Option.some(4)], [4, Option.none()]] + * })) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) => { + let i = 0; + if (acc._tag === "None") { + i = 1; + acc = Option.some(arr[0]); + } + const pairs = Arr.empty(); + for (; i < arr.length; i++) { + const value = acc.value; + acc = Option.some(arr[i]); + pairs.push([value, acc]); + } + return [acc, pairs]; +}, { + onHalt(state) { + return state._tag === "Some" ? [[state.value, Option.none()]] : []; + } +}); +/** + * Zips each element with its previous element, starting with `None`. + * + * **Example** (Zipping elements with previous values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4)) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [[Option.none(), 1], [Option.some(1), 2], [Option.some(2), 3], [Option.some(3), 4]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, arr) => { + const pairs = Arr.empty(); + for (let i = 0; i < arr.length; i++) { + const value = arr[i]; + pairs.push([acc, value]); + acc = Option.some(arr[i]); + } + return [acc, pairs]; +}); +/** + * Zips each element with its previous and next values. + * + * **Example** (Zipping elements with neighbors) + * + * ```ts import.meta.vitest + * import { Console, Effect, Option, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.zipWithPreviousAndNext, + * Stream.runCollect + * ) + * values // => [[Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({ + prev: Option.none(), + current: Option.none() +}), (acc, arr) => { + let i = 0; + let current; + if (acc.current._tag === "None") { + i = 1; + current = arr[0]; + acc.current = Option.some(current); + } else { + current = acc.current.value; + } + const pairs = Arr.empty(); + for (; i < arr.length; i++) { + const element = arr[i]; + acc.current = Option.some(element); + pairs.push([acc.prev, current, acc.current]); + acc.prev = Option.some(current); + current = element; + } + return [acc, pairs]; +}, { + onHalt(acc) { + return acc.current._tag === "Some" ? [[acc.prev, acc.current.value, Option.none()]] : []; + } +}); +/** + * Zips multiple streams so that when a value is emitted by any stream, it is + * combined with the latest values from the other streams to produce a result. + * + * **When to use** + * + * Use when each stream should contribute its latest value after all streams have + * emitted at least once. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values from many streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.zipLatestAll( + * Stream.make(1, 2, 3).pipe(Stream.rechunk(1)), + * Stream.make("a", "b", "c").pipe(Stream.rechunk(1)), + * Stream.make(true, false, true).pipe(Stream.rechunk(1)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [[1, "a", true], [2, "a", true], [2, "b", true], [2, "b", false], [3, "b", false], [3, "c", false], [3, "c", true]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 3.3.0 + */ +const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => { + const latest = []; + const emitted = new Set(); + const readyLatch = Latch.makeUnsafe(); + return Channel.mergeAll(Channel.fromArray(streams.map((s, i) => s.channel.pipe(Channel.flattenArray, Channel.mapEffect(a => { + latest[i] = a; + if (!emitted.has(i)) { + emitted.add(i); + if (emitted.size < streams.length) { + return readyLatch.await; + } + return Effect.as(readyLatch.open, Arr.of(latest.slice())); + } + return Effect.succeed(Arr.of(latest.slice())); + }), Channel.filter(isNotUndefined)))), { + concurrency: "unbounded", + bufferSize: 0 + }); +})); +/** + * Combines two streams by emitting each new element with the latest value from the other stream. + * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipLatest( + * Stream.make(1), + * Stream.make("a") + * ).pipe(Stream.runCollect) + * + * result // => [ [ 1, 'a' ] ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLatest = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipLatestAll(left, right)))); +/** + * Combines the latest values from both streams whenever either emits, using + * the provided function. + * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values with a function) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.rechunk(1), + * Stream.zipLatestWith( + * Stream.make(10, 20).pipe(Stream.rechunk(1)), + * (n, m) => n + m + * ), + * Stream.runCollect + * ) + * + * result // => [ 11, 12, 22, 23 ] + * })) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLatestWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => map(zipLatestAll(left, right), ([a, a2]) => f(a, a2))))); +/** + * Runs all streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the rest. + * + * **Details** + * + * Failures or completion from losing streams before a winner is chosen are + * ignored unless every stream fails or completes before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing multiple streams) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.raceAll( + * Stream.empty, + * Stream.make(0, 1, 2) + * ).pipe(Stream.runCollect) + * result // => [ 0, 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category racing + * @since 3.5.0 + */ +const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, scope) => Effect.sync(() => { + let winner; + const race = Effect.raceAll(streams.map(stream => { + const childScope = Scope.forkUnsafe(scope); + return Channel.toPullScoped(stream.channel, childScope).pipe(Effect.flatMap(pull => Effect.zip(Effect.succeed(pull), pull)), Effect.onExit(exit => { + if (exit._tag === "Success") { + if (winner) { + return Scope.close(childScope, exit); + } + winner = exit.value[0]; + return Effect.void; + } + return Scope.close(childScope, exit); + }), Effect.map(([, chunk]) => chunk)); + })); + return Effect.suspend(() => winner ?? race); +}))); +/** + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.race( + * Stream.empty, + * Stream.make(0, 1, 2) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 0, 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category racing + * @since 3.7.0 + */ +const race = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => raceAll(left, right)))); +/** + * Filters a stream to the elements that satisfy a predicate. + * + * **Example** (Filtering stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4).pipe( + * Stream.filter((n) => n % 2 === 0) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [ 2, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromChannel(Channel.filterArray(toChannel(self), predicate))))); +/** + * Filters and maps stream elements in one pass using a `Filter`. + * + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromChannel(Channel.filterMapArray(toChannel(self), filter))))); +/** + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.filterEffect((n) => Effect.succeed(n > 2))) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromChannel(Channel.filterArrayEffect(toChannel(self), predicate))))); +/** + * Filters and maps elements in one pass effectfully using a `FilterEffect`. + * + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 + */ +const filterMapEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter))))); +/** + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** + * + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. + * + * **Example** (Partitioning a stream into queues) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const [passes, fails] = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.partitionQueue((n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) + * ) + * + * const passValues = yield* Stream.fromQueue(passes).pipe(Stream.runCollect) + * const failValues = yield* Stream.fromQueue(fails).pipe(Stream.runCollect) + * + * passValues // => [ 2, 4 ] + * failValues // => [ 1, 3 ] + * }) + * + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const partitionQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, filter, options) { + const scope = yield* Effect.scope; + const pull = yield* Channel.toPullScoped(self.channel, scope); + const capacity = options?.capacity === "unbounded" ? undefined : options?.capacity ?? DefaultChunkSize; + const passes = yield* Queue.make({ + capacity + }); + const fails = yield* Queue.make({ + capacity + }); + yield* Effect.gen(function* () { + while (true) { + const chunk = yield* pull; + const excluded = []; + const satisfying = []; + for (let i = 0; i < chunk.length; i++) { + const result = filter(chunk[i]); + if (Result.isFailure(result)) { + excluded.push(result.failure); + } else { + satisfying.push(result.success); + } + } + let passFiber = undefined; + if (satisfying.length > 0) { + const leftover = Queue.offerAllUnsafe(passes, satisfying); + if (leftover.length > 0) { + passFiber = yield* Effect.forkChild(Queue.offerAll(passes, leftover)); + } + } + if (excluded.length > 0) { + const leftover = Queue.offerAllUnsafe(fails, excluded); + if (leftover.length > 0) { + yield* Queue.offerAll(fails, leftover); + } + } + if (passFiber) yield* Fiber.join(passFiber); + } + }).pipe(Effect.onError(cause => { + Queue.failCauseUnsafe(passes, cause); + Queue.failCauseUnsafe(fails, cause); + return Effect.void; + }), Effect.forkIn(scope)); + return [passes, fails]; +})))); +/** + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering + * @since 4.0.0 + */ +const partitionEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(mapEffect(self, a => filter(a), options), result => result, options), ([passes, fails]) => [fromQueue(passes), fromQueue(fails)])))); +/** + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const [excluded, satisfying] = yield* Stream.partition( + * Stream.make(1, 2, 3, 4), + * (n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n) + * ) + * const left = yield* Stream.runCollect(excluded) + * const right = yield* Stream.runCollect(satisfying) + * left // => [ 1, 3 ] + * right // => [ 2, 4 ] + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(self, filter, { + capacity: options?.bufferSize ?? 16 +}), ([passes, fails]) => [fromQueue(fails), fromQueue(passes)])))); +/** + * Returns the specified stream if the given condition is satisfied, otherwise + * returns an empty stream. + * + * **Example** (Conditionally keeping a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect( + * Stream.when(Stream.make(1, 2, 3), Effect.succeed(false)) + * ) + * result // => [] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const when = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, test) => test.pipe(Effect.map(pass => pass ? self : empty), unwrap)))); +/** + * Runs a sink to peel off enough elements to produce a value and returns that + * value with the remaining stream in a scope. + * + * **Details** + * + * The returned stream is only valid within the scope. + * + * **Example** (Peeling a stream with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const stream = Stream.fromArrays([1, 2, 3], [4, 5, 6]) + * const sink = Sink.take(3) + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [peeled, rest] = yield* Stream.peel(stream, sink) + * const remaining = yield* Stream.runCollect(rest) + * const result = [peeled, remaining] // => [[1, 2, 3], [4, 5, 6]] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const peel = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, sink) { + let cause = undefined; + const originalPull = yield* Channel.toPull(self.channel); + const pull = Effect.catchCause(originalPull, cause_ => { + cause = cause_; + return Effect.failCause(cause_); + }); + let stream = fromPull(Effect.succeed(pull)); + const leftover = yield* run(stream, sink); + if (cause) return [leftover, empty]; + stream = fromPull(Effect.succeed(originalPull)); + return [leftover, stream]; +})))); +/** + * Buffers up to `capacity` elements so a faster producer can progress + * independently of a slower consumer. + * + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.buffer({ capacity: 1 }), + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category buffering + * @since 2.0.0 + */ +const buffer = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromChannel(Channel.bufferArray(self.channel, options))))); +/** + * Allows a faster producer to progress independently of a slower consumer by + * buffering up to `capacity` chunks in a queue. + * + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. + * + * **Example** (Buffering stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArrays([1, 2], [3, 4]).pipe( + * Stream.bufferArray({ capacity: 2 }), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category buffering + * @since 4.0.0 + */ +const bufferArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromChannel(Channel.buffer(self.channel, options))))); +/** + * Switches over to the stream produced by the provided function in case this + * one fails. Allows recovery from all causes of failure, including + * interruption if the stream is uninterruptible. + * + * **Example** (Catching stream causes) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("Oops!")), + * Stream.concat(Stream.make(3, 4)) + * ) + * + * const recovered = stream.pipe( + * Stream.catchCause(() => Stream.make(999)) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(recovered) + * values // => [ 1, 2, 999 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.channel.pipe(Channel.catchCause(cause => f(cause).channel), fromChannel)))); +/** + * Runs an effect when the stream fails without changing its values or error, + * unless the tap effect itself fails. + * + * **Example** (Tapping stream causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const observations: Array = [] + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapCause((cause) => Effect.sync(() => observations.push(Cause.isReason(cause)))), + * Stream.catch(() => Stream.succeed(0)) + * ) + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.runCollect(stream) + * result // => [1, 2, 0] + * }) + * + * await Effect.runPromise(program) + * observations // => [false] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.channel.pipe(Channel.tapCause(f), fromChannel)))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.catch(self.channel, error => f(error).channel))))); + +/** + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const errors: Array = [] + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapError((error) => Effect.sync(() => errors.push(error))), + * Stream.catch(() => Stream.make(999)) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 999] + * }) + * + * await Effect.runPromise(program) + * errors // => ["boom"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => self.channel.pipe(_Channel_js__rspack_import_1/* .tapError */.sF(f), fromChannel)); +/** + * Recovers from errors that match a predicate by switching to a recovery stream. + * + * **Details** + * + * When a failure matches the filter, the stream switches to the recovery + * stream. Non-matching failures propagate downstream, so the error type is + * preserved unless the filter narrows it. + * + * **Example** (Catching matching failures) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail(42)), + * Stream.catchIf( + * (error): error is 42 => error === 42, + * () => Stream.make(999) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 999 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, predicate, f, orElse) => fromChannel(Channel.catchIf(toChannel(self), predicate, e => f(e).channel, orElse && (e => orElse(e).channel)))))); +/** + * Recovers from errors that match a `Filter` by switching to a recovery + * stream. + * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, f, orElse) => fromChannel(Channel.catchFilter(toChannel(self), filter, e => f(e).channel, orElse && (e => orElse(e).channel)))))); +/** + * Recovers from failures whose `_tag` matches the provided value by switching to + * the stream returned by `f`. + * + * **When to use** + * + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. + * + * **Example** (Catching tagged failures) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class HttpError extends Data.TaggedError("HttpError")<{ message: string }> {} + * + * const stream = Stream.fail(new HttpError({ message: "timeout" })) + * + * const recovered = Stream.catchTag(stream, "HttpError", (error) => + * Stream.make(`Recovered: ${error.message}`) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(recovered) + * values // => [ 'Recovered: timeout' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); + return catchIf(self, pred, f, orElse); +}))); +/** + * Switches to a recovery stream based on matching `_tag` handlers. + * + * **Example** (Catching tagged failures with handlers) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * class NotFound { + * readonly _tag = "NotFound" + * constructor(readonly resource: string) {} + * } + * + * class Unauthorized { + * readonly _tag = "Unauthorized" + * constructor(readonly user: string) {} + * } + * + * const stream = Stream.fail(new NotFound("profile")) + * + * const program = Effect.gen(function* () { + * const result = yield* stream.pipe( + * Stream.catchTags({ + * NotFound: () => Stream.succeed("fallback"), + * Unauthorized: () => Stream.succeed("login") + * }), + * Stream.runCollect + * ) + * result // => [ 'fallback' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTags = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, cases, orElse) => { + let keys; + return catchFilter(self, e => { + keys ??= Object.keys(cases); + return hasProperty(e, "_tag") && isString(e["_tag"]) && keys.includes(e["_tag"]) ? Result.succeed(e) : Result.fail(e); + }, e => cases[e["_tag"]](e), orElse); +}))); +/** + * Catches a specific reason within a tagged error. + * + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const stream = Stream.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* stream.pipe( + * Stream.catchReason("AiError", "RateLimitError", (reason) => + * Stream.succeed(`retry: ${reason.retryAfter}`) + * ), + * Stream.runCollect + * ) + * values // => [ 'retry: 60' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, errorTag, reasonTag, f, orElse) => fromChannel(Channel.catchReason(toChannel(self), errorTag, reasonTag, (reason, error) => f(reason, error).channel, orElse && ((reason, error) => orElse(reason, error).channel)))))); +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * **Example** (Catching tagged error reasons) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const stream = Stream.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* stream.pipe( + * Stream.catchReasons("AiError", { + * RateLimitError: (reason) => Stream.succeed(`retry: ${reason.retryAfter}`), + * QuotaExceededError: (reason) => Stream.succeed(`quota: ${reason.limit}`) + * }), + * Stream.runCollect + * ) + * values // => [ 'retry: 60' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, errorTag, cases, orElse) => { + const handlers = Object.create(null); + for (const key of Object.keys(cases)) { + const handler = cases[key]; + handlers[key] = (reason, error) => handler(reason, error).channel; + } + const orElseHandler = orElse && ((reason, error) => orElse(reason, error).channel); + return fromChannel(Channel.catchReasons(self.channel, errorTag, handlers, orElseHandler)); +}))); +/** + * Transforms the errors emitted by this stream using `f`. + * + * **Example** (Mapping stream errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fail("bad").pipe( + * Stream.mapError((error) => `mapped: ${error}`), + * Stream.catch((error) => Stream.make(`recovered from ${error}`)), + * Stream.runCollect + * ) + * result // => [ 'recovered from mapped: bad' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.mapError(self.channel, f))))); +/** + * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. + * Non-matching causes are re-emitted as failures. + * + * **Example** (Catching matching causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const failingStream = Stream.fail("NetworkError") + * const recovered = Stream.catchCauseIf( + * failingStream, + * (cause) => Cause.hasFails(cause), + * (cause) => Stream.make(`Recovered: ${Cause.squash(cause)}`) + * ) + * + * const output = yield* Stream.runCollect(recovered) + * output // => [ 'Recovered: NetworkError' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, f) => fromChannel(Channel.catchCauseIf(self.channel, predicate, cause => f(cause).channel))))); +/** + * Recovers from stream failures by filtering the `Cause` and switching to a + * recovery stream. + * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, filter, f) => fromChannel(Channel.catchCauseFilter(self.channel, filter, (failure, cause) => f(failure, cause).channel))))); +/** + * Switches to a fallback stream if this stream is empty. + * + * **Example** (Switching on empty streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.empty.pipe( + * Stream.orElseIfEmpty(() => Stream.make(1, 2)), + * Stream.runCollect + * ) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseIfEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, orElse) => fromChannel(Channel.orElseIfEmpty(self.channel, _ => toChannel(orElse())))))); +/** + * Returns a stream that emits a fallback value when this stream fails. + * + * **Example** (Recovering with a fallback value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fail("NetworkError").pipe( + * Stream.orElseSucceed((error) => `Recovered: ${error}`) + * ) + * + * const values = yield* Stream.runCollect(stream) + * values // => [ 'Recovered: NetworkError' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSucceed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catch_(self, e => succeed(f(e)))))); +/** + * Turns typed failures into defects, making the stream infallible. + * + * **Example** (Turning failures into defects) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.orDie, + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => fromChannel(Channel.orDie(self.channel)); +/** + * Ignores failures and ends the stream on error. + * + * **When to use** + * + * Use when you want a failing stream to end gracefully rather than propagate + * the error. + * + * **Details** + * + * The `log` option controls whether the failure is logged before the stream + * terminates. + * + * **Example** (Ignoring stream failures) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.ignore, + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * **Example** (Configuring ignore logging) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.fail("boom").pipe( + * Stream.ignore({ log: false }), + * Stream.runCollect + * ) + * values // => [] + * })) + * + * ``` + * + * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures + * + * @category error handling + * @since 4.0.0 + */ +const ignore = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignore(self.channel, options))))); +/** + * Ignores the stream's failure cause, including defects, and ends the stream. + * + * **When to use** + * + * Use when you need to silently suppress a stream's entire failure cause, + * including both typed errors and defects, rather than propagate it downstream. + * + * **Example** (Ignoring stream failure causes) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.die("boom")), + * Stream.ignoreCause({ log: false }), + * Stream.runCollect + * ) + * values // => [1, 2] + * })) + * + * ``` + * + * @see {@link ignore} to ignore only typed failures without suppressing defects + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignoreCause(self.channel, options))))); +/** + * Retries the stream according to the given schedule when it fails. + * + * **Details** + * + * This retries the entire stream, so will re-execute all of the stream's + * acquire operations. + * + * The schedule is reset as soon as the first element passes through the + * stream again. + * + * **Example** (Retrying stream failures) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.retry(Schedule.recurs(1)), + * Stream.take(2), + * Stream.runCollect + * ) + * + * values // => [ 1, 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const retry = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, policy) => fromChannel(Channel.retry(self.channel, policy))))); +const retryWithoutReset = (self, schedule) => unwrap(Effect.map(Schedule.toStepWithMetadata(schedule), step => { + let meta = Schedule.CurrentMetadata.defaultValue(); + const loop = () => catch_(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), error => unwrap(Pull.catchDone(Effect.map(step(error), meta_ => { + meta = meta_; + return unwrap(Effect.as(Effect.yieldNow, loop())); + }), () => Effect.succeed(fail(error))))); + return loop(); +})); +/** + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources + * until it succeeds or the plan is exhausted. + * + * **Details** + * + * By default, a failing step can fallback even after emitting elements; set + * `preventFallbackOnPartialStream` to fail instead of mixing partial output with + * a later fallback. + * + * Attempts can be observed from outside the stream by passing + * `options.onEvent`, which receives an `ExecutionPlan.Event` before each + * attempt and after it settles; see `Effect.withExecutionPlan` for the handler + * semantics. When a downstream consumer stops pulling early (for example + * `Stream.take` outside the plan), the truncated attempt reports + * `AttemptSuccess`: the consumer stopped, not the source. + * + * **Example** (Applying an execution plan) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer, Stream } from "effect" + * + * class Service extends Context.Service()("Service", { + * make: Effect.succeed({ + * stream: Stream.fail("A") as Stream.Stream + * }) + * }) { + * static Bad = Layer.succeed(Service, Service.of({ stream: Stream.fail("A") })) + * static Good = Layer.succeed(Service, Service.of({ stream: Stream.make(1, 2, 3) })) + * } + * + * const plan = ExecutionPlan.make( + * { provide: Service.Bad }, + * { provide: Service.Good } + * ) + * + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) + * + * const program = Effect.gen(function*() { + * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) + * items // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 3.16.0 + */ +const withExecutionPlan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, policy, options) => suspend(() => { + const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false; + let i = 0; + let meta = { + attempt: 0, + stepIndex: 0 + }; + const provideMeta = provideServiceEffect(ExecutionPlan.CurrentMetadata, Effect.sync(() => { + meta = { + attempt: meta.attempt + 1, + stepIndex: i + }; + return meta; + })); + const emitter = options?.onEvent === undefined ? undefined : internalExecutionPlan.makeEventEmitter(options.onEvent, () => meta); + let attemptState; + const instrument = emitter === undefined ? identity : attempt => onExit(onStart(attempt, Effect.map(emitter.begin, state => { + attemptState = state; + })), exit => Effect.suspend(() => { + if (attemptState === undefined) return Effect.void; + const state = attemptState; + attemptState = undefined; + return emitter.end(state, exit); + })); + let lastError = Option.none(); + const loop = suspend(() => { + const step = policy.steps[i]; + if (!step) { + return fail(Option.getOrThrow(lastError)); + } + let nextStream = provideMeta(instrument(provide(self, step.provide))); + let receivedElements = false; + if (Option.isSome(lastError)) { + const error = lastError.value; + let attempted = false; + const wrapped = nextStream; + // ensure the schedule is applied at least once + nextStream = suspend(() => { + if (attempted) return wrapped; + attempted = true; + return fail(error); + }); + nextStream = retryWithoutReset(nextStream, internalExecutionPlan.scheduleFromStep(step, false)); + } else { + const schedule = internalExecutionPlan.scheduleFromStep(step, true); + nextStream = schedule ? retryWithoutReset(nextStream, schedule) : nextStream; + } + return catch_(preventFallbackOnPartialStream ? onFirst(nextStream, _ => { + receivedElements = true; + return Effect.void; + }) : nextStream, error => { + i++; + if (preventFallbackOnPartialStream && receivedElements) { + return fail(error); + } + lastError = Option.some(error); + return loop; + }); + }); + return loop; +})))); +/** + * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. + * + * **Example** (Taking values from the left) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.take(3), + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => n < 1 ? empty : takeUntil(self, (_, i) => i === n - 1)))); +/** + * Emits byte chunks until the configured limit would be exceeded, then drops + * the crossing chunk and switches to a fallback stream. + * + * **Example** (Truncating at a byte limit) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make( + * new Uint8Array([1, 2]), + * new Uint8Array([3, 4, 5]) + * ).pipe( + * Stream.limitBytes(4, () => Stream.empty), + * Stream.runCollect, + * Effect.map((chunks) => chunks.map((chunk) => [...chunk])) + * ) + * + * await Effect.runPromise(program) // => [[1, 2]] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const limitBytes = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, bytes, onLimitReached) => suspend(() => { + const limit = BigInt(bytes); + let size = BigInt(0); + let limitReached = false; + return concat(takeWhile(self, chunk => { + const nextSize = size + BigInt(chunk.length); + if (nextSize > limit) { + limitReached = true; + return false; + } + size = nextSize; + return true; + }), suspend(() => limitReached ? onLimitReached() : empty)); +})))); +/** + * Keeps the last `n` elements from this stream. + * + * **Example** (Taking elements from the right) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.range(1, 6).pipe( + * Stream.takeRight(3), + * Stream.runCollect + * ) + * values // => [ 4, 5, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => mapAccumArray(self, MutableList.make, (list, arr) => { + MutableList.appendAll(list, arr); + if (list.length > n) { + MutableList.takeNVoid(list, list.length - n); + } + return [list, emptyArr]; +}, { + onHalt(list) { + return MutableList.takeAll(list); + } +})))); +/** + * Takes elements until the predicate matches. + * + * **Details** + * + * When `excludeLast` is `true`, the matching element is dropped. + * + * **Example** (Taking until a predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(1, 5) + * + * const program = Effect.gen(function*() { + * const inclusive = yield* stream.pipe( + * Stream.takeUntil((n) => n % 3 === 0), + * Stream.runCollect + * ) + * inclusive // => [ 1, 2, 3 ] + * + * const exclusive = yield* stream.pipe( + * Stream.takeUntil((n) => n % 3 === 0, { excludeLast: true }), + * Stream.runCollect + * ) + * exclusive // => [ 1, 2 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeUntil = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => _Effect_js__rspack_import_3/* .sync */.OH5(() => { + let i = 0; + let done = false; + const pump = _Effect_js__rspack_import_3/* .flatMap */.qIB(_Effect_js__rspack_import_3/* .suspend */.DYE(() => done ? _Cause_js__rspack_import_5/* .done */.Vw() : pull), chunk => { + const index = chunk.findIndex(a => predicate(a, i++)); + if (index >= 0) { + done = true; + const arr = chunk.slice(0, options?.excludeLast ? index : index + 1); + return _Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(arr) ? _Effect_js__rspack_import_3/* .succeed */.PyW(arr) : _Cause_js__rspack_import_5/* .done */.Vw(); + } + return _Effect_js__rspack_import_3/* .succeed */.PyW(chunk); + }); + return pump; +}))); +/** + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.takeUntilEffect((n) => Effect.succeed(n % 3 === 0)), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeUntilEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let i = 0; + let done = false; + return Effect.gen(function* () { + if (done) return yield* Cause.done(); + const chunk = yield* pull; + for (let j = 0; j < chunk.length; j++) { + if (yield* predicate(chunk[j], i++)) { + done = true; + const arr = chunk.slice(0, options?.excludeLast ? j : j + 1); + return Arr.isReadonlyArrayNonEmpty(arr) ? arr : yield* Cause.done(); + } + } + return chunk; + }); +}))))); +/** + * Takes the longest initial prefix of elements that satisfy the predicate. + * + * **Example** (Taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(1, 5).pipe( + * Stream.takeWhile((n) => n % 3 !== 0) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let i = 0; + let done = false; + const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => { + const out = []; + for (let j = 0; j < chunk.length; j++) { + if (!predicate(chunk[j], i++)) { + done = true; + break; + } + out.push(chunk[j]); + } + return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump; + }); + return pump; +}))))); +/** + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. + * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** + * + * The stream stops at the first `Result.fail` returned by the filter. + * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements + * + * @category filtering + * @since 4.0.0 + */ +const takeWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let done = false; + const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => { + const out = []; + for (let j = 0; j < chunk.length; j++) { + const result = filter(chunk[j]); + if (Result.isFailure(result)) { + done = true; + break; + } + out.push(result.success); + } + return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump; + }); + return pump; +}))))); +/** + * Takes elements from the stream while the effectful predicate is `true`. + * + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.takeWhileEffect((n) => Effect.succeed(n % 3 !== 0)), + * Stream.runCollect + * ) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const takeWhileEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => takeUntilEffect(self, (a, n) => Effect.map(predicate(a, n), b => !b), { + excludeLast: true +})))); +/** + * Drops the first `n` elements from this stream. + * + * **Example** (Dropping values from the left) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const result = Stream.drop(stream, 2) + * + * const program = Effect.gen(function*() { + * const items = yield* Stream.runCollect(result) + * items // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropped = 0; + const pump = pull.pipe(Effect.flatMap(chunk => { + if (dropped >= n) return Effect.succeed(chunk); + dropped += chunk.length; + if (dropped <= n) return pump; + return Effect.succeed(chunk.slice(n - dropped)); + })); + return pump; +}))))); +/** + * Drops elements until the specified predicate evaluates to `true`, then drops + * that matching element. + * + * **Example** (Dropping until a predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const result = Stream.dropUntil(stream, (n) => n >= 3) + * + * await Effect.runPromise(Effect.gen(function*() { + * const output = yield* Stream.runCollect(result) + * output // => [ 4, 5 ] + * })) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropUntil = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => drop(dropWhile(self, (a, i) => !predicate(a, i)), 1)))); +/** + * Drops all elements of the stream until the specified effectful predicate + * evaluates to `true`. + * + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.dropUntilEffect((n) => Effect.succeed(n % 3 === 0)), + * Stream.runCollect + * ) + * result // => [ 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropUntilEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => drop(dropWhileEffect(self, (a, i) => Effect.map(predicate(a, i), b => !b)), 1)))); +/** + * Drops elements from the stream while the specified predicate evaluates to `true`. + * + * **Example** (Dropping while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropWhile((n) => n < 3), + * Stream.runCollect + * ) + * values // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + let index = 0; + const filtered = Effect.flatMap(pull, arr => { + const found = arr.findIndex(a => !predicate(a, index++)); + if (found === -1) return filtered; + dropping = false; + return Effect.succeed(arr.slice(found)); + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops elements while the filter succeeds. + * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering + * @since 4.0.0 + */ +const dropWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + const filtered = Effect.flatMap(pull, arr => { + const found = arr.findIndex(a => Result.isFailure(filter(a))); + if (found === -1) return filtered; + dropping = false; + return Effect.succeed(arr.slice(found)); + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops elements while the specified effectful predicate evaluates to `true`. + * + * **Example** (Effectfully dropping while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropWhileEffect((n) => Effect.succeed(n < 3)), + * Stream.runCollect + * ) + * result // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropWhileEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + let index = 0; + const filtered = Effect.gen(function* () { + while (true) { + const arr = yield* pull; + for (let i = 0; i < arr.length; i++) { + const drop = yield* predicate(arr[i], index++); + if (drop) continue; + dropping = false; + return arr.slice(i); + } + } + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops the last specified number of elements from this stream. + * + * **Details** + * + * Keeps the last `n` elements in memory to drop them on completion. + * + * **Example** (Dropping values from the right) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropRight(2), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + if (n <= 0) return self; + return transformPull(self, (pull, _scope) => Effect.sync(() => { + const list = MutableList.make(); + const emit = Effect.flatMap(pull, arr => { + MutableList.appendAllUnsafe(list, arr); + const toTake = list.length - n; + const items = MutableList.takeN(list, toTake); + return Arr.isArrayNonEmpty(items) ? Effect.succeed(items) : emit; + }); + return emit; + })); +}))); +/** + * Exposes the underlying chunks as a stream of non-empty arrays. + * + * **Example** (Exposing stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const chunks = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.chunks, + * Stream.runCollect + * ) + * chunks // => [ [ 1, 2 ], [ 3, 4 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel); +/** + * Groups the stream into arrays of the specified size, preserving element order. + * + * **Details** + * + * The size is clamped to at least 1. + * + * **Example** (Rechunking stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.rechunk(2), + * Stream.chunks, + * Stream.runCollect + * ) + * result // => [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const rechunk = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, target) => { + target = Math.max(1, target); + return transformPull(self, (pull, _scope) => Effect.sync(() => { + let chunk = Arr.empty(); + let index = 0; + let current; + let done = false; + return Effect.suspend(function loop() { + if (done) return Cause.done();else if (current === undefined) { + return Effect.flatMap(pull, arr => { + if (chunk.length === 0 && arr.length === target) { + return Effect.succeed(arr); + } else if (chunk.length + arr.length < target) { + chunk.push(...arr); + return loop(); + } + current = arr; + return loop(); + }); + } + for (; index < current.length;) { + chunk.push(current[index++]); + if (chunk.length === target) { + const result = chunk; + chunk = []; + return Effect.succeed(result); + } + } + index = 0; + current = undefined; + return loop(); + }).pipe(Pull.catchDone(() => { + if (chunk.length === 0) return Cause.done(); + const result = chunk; + done = true; + chunk = []; + return Effect.succeed(result); + })); + })); +}))); +/** + * Emits a sliding window of `n` elements. + * + * **Example** (Emitting sliding windows) + * + * ```ts import.meta.vitest + * import { Effect, pipe, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* pipe( + * Stream.make(1, 2, 3, 4, 5), + * Stream.sliding(2), + * Stream.runCollect + * ) + * result // => [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ] + * })) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const sliding = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, chunkSize) => slidingSize(self, chunkSize, 1)))); +/** + * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. + * + * **Example** (Emitting sliding windows with a step size) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const chunks = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.slidingSize(3, 2), + * Stream.runCollect + * ) + * chunks // => [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const slidingSize = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, chunkSize, stepSize) => transformPull(self, (upstream, _scope) => Effect.sync(() => { + let cause = null; + const list = MutableList.make(); + let emitted = false; + let skip = 0; + const pull = Effect.matchCauseEffect(upstream, { + onSuccess(arr) { + MutableList.appendAllUnsafe(list, arr); + if (skip > 0) { + const length = list.length; + MutableList.takeNVoid(list, skip); + skip = Math.max(0, skip - length); + } + if (list.length < chunkSize) return pull; + emitted = true; + const chunks = []; + while (list.length >= chunkSize) { + if (chunkSize === stepSize) { + chunks.push(MutableList.takeN(list, chunkSize)); + } else { + chunks.push(MutableList.toArrayN(list, chunkSize)); + if (chunkSize === 1 && stepSize <= 0) { + MutableList.take(list); + } else { + const length = list.length; + MutableList.takeNVoid(list, stepSize); + skip = Math.max(0, stepSize - length); + } + } + } + return Effect.succeed(chunks); + }, + onFailure(cause_) { + if (emitted) MutableList.takeNVoid(list, chunkSize - stepSize); + if (list.length === 0) return Effect.failCause(cause_); + cause = cause_; + return Effect.succeed(Arr.of(MutableList.takeAll(list))); + } + }); + return Effect.suspend(() => cause ? Effect.failCause(cause) : pull); +}))))); +/** + * Splits the stream into non-empty groups whenever the predicate matches. + * + * **Details** + * + * Matching elements act as delimiters and are not included in the output. + * + * **Example** (Splitting on matching values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(0, 9).pipe( + * Stream.split((n) => n % 4 === 0), + * Stream.runCollect + * ) + * result // => [ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 9 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const split = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => mapAccumArray(self, Arr.empty, (acc, arr) => { + const out = Arr.empty(); + for (let i = 0; i < arr.length; i++) { + if (predicate(arr[i])) { + if (Arr.isArrayNonEmpty(acc)) { + out.push(acc); + acc = []; + } + } else { + acc.push(arr[i]); + } + } + return [acc, out]; +}, { + onHalt(arr) { + return Arr.isArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +})))); +/** + * Combines elements from this stream and the specified stream by repeatedly + * applying a stateful function that can pull from either side. + * + * **Details** + * + * Where possible, prefer `Stream.combineArray` for a more efficient + * implementation. + * + * **Example** (Combining streams with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.combine( + * Stream.make("A", "B", "C"), + * Stream.make(1, 2, 3), + * () => true, + * (takeLeft, pullLeft, pullRight) => + * takeLeft + * ? Effect.map(pullLeft, (value) => [`L:${value}`, false] as const) + * : Effect.map(pullRight, (value) => [`R:${value}`, true] as const) + * ) + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.runCollect(stream) + * output // => [ 'L:A', 'R:1', 'L:B', 'R:2', 'L:C', 'R:3' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => Channel.combine(Channel.flattenArray(self.channel), Channel.flattenArray(that.channel), s, f).pipe(Channel.map(Arr.of), fromChannel)))); +/** + * Combines two streams chunk-by-chunk with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.combineArray( + * Stream.make(10, 20), + * () => true, + * (useLeft, pullLeft, pullRight) => + * Effect.gen(function*() { + * const array = useLeft ? yield* pullLeft : yield* pullRight + * return [array, !useLeft] as const + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 10, 20 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const combineArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => fromChannel(Channel.combine(self.channel, that.channel, s, f))))); +/** + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const totals = yield* Stream.make(0, 1, 2, 3, 4, 5, 6).pipe( + * Stream.mapAccum(() => 0, (total, n) => { + * const next = total + n + * return [next, [next]] as const + * }), + * Stream.runCollect + * ) + * + * totals // => [0, 1, 3, 6, 10, 15, 21] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { + const acc = Arr.empty(); + for (let index = 0; index < arr.length; index++) { + const [newState, values] = f(state, arr[index]); + state = newState; + acc.push(...values); + } + return [state, Arr.isArrayNonEmpty(acc) ? Arr.of(acc) : emptyArr]; +}, options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined))))); +/** + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** + * + * The mapping function runs once per chunk and the state is threaded across chunks. + * + * **Example** (Statefully mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.rechunk(2), + * Stream.mapAccumArray(() => 0, (sum: number, chunk) => { + * const next = chunk.reduce((acc, n) => acc + n, sum) + * return [next, [next]] + * }), + * Stream.runCollect + * ) + * output // => [ 3, 10, 21 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapAccumArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { + const [newState, values] = f(state, arr); + state = newState; + return [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]; +}, options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined))))); +const emptyArr = /*#__PURE__*/(/* unused pure expression or super */ null && (Arr.empty())); +/** + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 1, 1).pipe( + * Stream.mapAccumEffect(() => 0, (total, n) => + * Effect.succeed([total + n, [total + n]]) + * ), + * Stream.runCollect + * ) + * + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapAccumEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : Arr.empty()]), options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined), fromChannel)))); +/** + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const totals = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.mapAccumArrayEffect(() => 0, (total, chunk) => + * Effect.gen(function*() { + * const next = chunk.reduce((sum, value) => sum + value, total) + * return [next, [next]] as const + * }) + * ), + * Stream.runCollect + * ) + * totals // => [ 3, 10 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapAccumArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]), options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined), fromChannel)))); +/** + * Accumulates state across the stream, emitting the initial state and each updated state. + * + * **Example** (Scanning stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.scan(0, (acc, n) => acc + n), + * Stream.runCollect + * ) + * values // => [ 0, 1, 3, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => suspend(() => { + let isFirst = true; + return fromChannel(Channel.mapAccum(self.channel, constant(initial), (state, arr) => { + const states = Arr.empty(); + if (isFirst) { + isFirst = false; + states.push(state); + } + for (let index = 0; index < arr.length; index++) { + state = f(state, arr[index]); + states.push(state); + } + return [state, Arr.of(states)]; + })); +})))); +/** + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const states = yield* Stream.make(1, 2, 3).pipe( + * Stream.scanEffect(0, (sum, n) => Effect.succeed(sum + n)), + * Stream.runCollect + * ) + * states // => [ 0, 1, 3, 6 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const scanEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => self.channel.pipe(Channel.flattenArray, Channel.scanEffect(initial, f), Channel.map(Arr.of), fromChannel)))); +/** + * Drops earlier elements within the debounce window and emits only the latest element after the pause. + * + * **Example** (Debouncing stream elements) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3).pipe(Stream.debounce(Duration.zero)) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 3 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const debounce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, duration) => transformPull(self, Effect.fnUntraced(function* (pull, scope) { + const clock = yield* Clock; + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + let lastArr; + let cause; + let emitAtMs = Infinity; + const pullLatch = Latch.makeUnsafe(); + const emitLatch = Latch.makeUnsafe(); + const endLatch = Latch.makeUnsafe(); + yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => { + emitLatch.openUnsafe(); + lastArr = arr; + emitAtMs = clock.currentTimeMillisUnsafe() + durationMs; + return Effect.void; + }), Effect.forever({ + disableYield: true + }), Effect.onError(cause_ => { + cause = cause_; + emitAtMs = clock.currentTimeMillisUnsafe(); + emitLatch.openUnsafe(); + endLatch.openUnsafe(); + return Effect.void; + }), Effect.forkIn(scope)); + const sleepLoop = Effect.suspend(function loop() { + const now = clock.currentTimeMillisUnsafe(); + const timeMs = emitAtMs < now ? durationMs : Math.min(durationMs, emitAtMs - now); + return Effect.flatMap(Effect.raceFirst(Effect.sleep(timeMs), endLatch.await), () => { + const now = clock.currentTimeMillisUnsafe(); + if (now < emitAtMs) { + return loop(); + } else if (lastArr) { + emitLatch.closeUnsafe(); + pullLatch.closeUnsafe(); + const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr))); + lastArr = undefined; + return eff; + } else if (cause) { + return Effect.failCause(cause); + } + return loop(); + }); + }); + return Effect.suspend(() => { + if (cause) { + if (lastArr) { + const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr))); + lastArr = undefined; + return eff; + } + return Effect.failCause(cause); + } + pullLatch.openUnsafe(); + return emitLatch.whenOpen(sleepLoop); + }); +}))))); +/** + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. + * + * If using the "enforce" strategy, arrays that do not meet the bandwidth + * constraints are dropped. If using the "shape" strategy, arrays are delayed + * until they can be emitted without exceeding the bandwidth constraints. + * + * Defaults to the "shape" strategy. + * + * **Example** (Throttling stream chunks effectfully) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(0, 5).pipe( + * Stream.rechunk(1), + * Stream.throttleEffect({ + * cost: (arr) => Effect.succeed(arr.length), + * units: 1, + * duration: 0, + * strategy: "shape" + * }) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 0, 1, 2, 3, 4, 5 ] + * })) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const throttleEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const burst = options.burst ?? 0; + if (options.strategy === "enforce") { + return throttleEnforceEffect(self, options.cost, options.units, options.duration, burst); + } + return throttleShapeEffect(self, options.cost, options.units, options.duration, burst); +}))); +const throttleEnforceEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => { + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst; + let tokens = units; + let timestampMs = clock.currentTimeMillisUnsafe(); + return Effect.succeed(Effect.flatMap(pull, function loop(arr) { + return Effect.flatMap(cost(arr), weight => { + const currentMs = clock.currentTimeMillisUnsafe(); + const elapsed = currentMs - timestampMs; + const cycles = elapsed / durationMs; + const sum = tokens + cycles * units; + const available = sum < 0 ? max : Math.min(sum, max); + if (weight <= available) { + tokens = available - weight; + timestampMs = currentMs; + return Effect.succeed(arr); + } + // Drop the array and continue + return Effect.flatMap(pull, loop); + }); + })); +})); +const throttleShapeEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => { + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst; + let tokens = units; + let timestampMs = clock.currentTimeMillisUnsafe(); + return Effect.succeed(Effect.flatMap(pull, arr => Effect.flatMap(cost(arr), weight => { + const currentMs = clock.currentTimeMillisUnsafe(); + const elapsed = currentMs - timestampMs; + const cycles = elapsed / durationMs; + const sum = tokens + cycles * units; + const available = sum < 0 ? max : Math.min(sum, max); + const remaining = available - weight; + if (remaining >= 0) { + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + } + // Calculate delay needed + const waitCycles = -remaining / units; + const delayMs = Math.max(0, waitCycles * durationMs); + if (delayMs > 0) { + return Effect.flatMap(Effect.sleep(delayMs), () => { + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + }); + } + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + }))); +})); +/** + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. + * + * If using the "enforce" strategy, arrays that do not meet the bandwidth + * constraints are dropped. If using the "shape" strategy, arrays are delayed + * until they can be emitted without exceeding the bandwidth constraints. + * + * Defaults to the "shape" strategy. + * + * **Example** (Throttling stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(0, 5).pipe( + * Stream.rechunk(1), + * Stream.throttle({ + * cost: (arr) => arr.length, + * units: 1, + * duration: 0, + * strategy: "shape" + * }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 0, 1, 2, 3, 4, 5 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const throttle = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => throttleEffect(self, { + ...options, + cost: arr => Effect.succeed(options.cost(arr)) +})))); +/** + * Partitions the stream into non-empty arrays of the specified size. + * + * **Details** + * + * The final array may be smaller if there are not enough elements to fill it. + * + * **Example** (Grouping elements by size) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.range(1, 8).pipe( + * Stream.grouped(3), + * Stream.runCollect + * ) + * grouped // => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const grouped = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => chunks(rechunk(self, n))))); +/** + * Partitions the stream into arrays, emitting when the chunk size is reached + * or the duration passes. + * + * **Example** (Grouping elements by size or time) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.groupedWithin(2, "5 seconds"), + * Stream.runCollect + * ) + * values // => [ [ 1, 2 ], [ 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupedWithin = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, chunkSize, duration) => aggregateWithin(self, Sink.take(chunkSize), Schedule.spaced(duration))))); +/** + * Groups elements into keyed substreams using an effectful classifier. + * + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.groupBy((n) => + * Effect.succeed([n % 2 === 0 ? "even" : "odd", n] as const) + * ), + * Stream.mapEffect( + * Effect.fnUntraced(function*([key, stream]) { + * return [key, yield* Stream.runCollect(stream)] as const + * }), + * { concurrency: "unbounded" } + * ), + * Stream.runCollect + * ) + * + * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) { + for (let i = 0; i < arr.length; i++) { + const [key, value] = yield* f(arr[i]); + const oentry = MutableHashMap.get(queueMap, key); + const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key)); + yield* RcMap.touch(queues, key); + yield* Queue.offer(queue, value); + } +}), options)))); +/** + * Groups elements by a key and emits a stream per key. + * + * **Example** (Grouping elements by key) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.groupByKey((n) => n % 2 === 0 ? "even" : "odd"), + * Stream.mapEffect( + * ([key, stream]) => + * Stream.runCollect(stream).pipe( + * Effect.map((values) => [key, values] as const) + * ), + * { concurrency: "unbounded" } + * ), + * Stream.runCollect + * ) + * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupByKey = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => suspend(() => { + const batch = MutableHashMap.empty(); + return groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) { + for (let i = 0; i < arr.length; i++) { + const key = f(arr[i]); + const ovalues = MutableHashMap.get(batch, key); + if (Option.isNone(ovalues)) { + MutableHashMap.set(batch, key, [arr[i]]); + } else { + ovalues.value.push(arr[i]); + } + } + for (const [key, values] of batch) { + const oentry = MutableHashMap.get(queueMap, key); + const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key)); + yield* RcMap.touch(queues, key); + yield* Queue.offerAll(queue, values); + } + MutableHashMap.clear(batch); + }), options); +})))); +const groupByImpl = (self, f, options) => transformPullBracket(self, Effect.fnUntraced(function* (pull, scope, forkedScope) { + const out = yield* Queue.unbounded(); + yield* Scope.addFinalizer(scope, Queue.shutdown(out)); + const queueMap = MutableHashMap.empty(); + const queues = yield* RcMap.make({ + lookup: key => Effect.acquireRelease(Queue.make({ + capacity: options?.bufferSize ?? 4096 + }).pipe(Effect.tap(queue => { + MutableHashMap.set(queueMap, key, queue); + return Queue.offer(out, [key, fromQueue(queue)]); + })), queue => { + MutableHashMap.remove(queueMap, key); + return Queue.end(queue); + }), + idleTimeToLive: options?.idleTimeToLive ?? Duration.infinity + }).pipe(Scope.provide(forkedScope)); + yield* Effect.whileLoop({ + while: constTrue, + body: constant(Effect.flatMap(pull, arr => f(arr, queues, queueMap))), + step: constVoid + }).pipe(Effect.catchCause(cause => Queue.failCause(out, cause)), Effect.forkIn(scope)); + return Queue.takeAll(out); +})); +/** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping + * @since 2.0.0 + */ +const groupAdjacentBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let currentKey = undefined; + let group; + let toEmit = Arr.empty(); + const loop = pull.pipe(Effect.flatMap(chunk => { + for (let i = 0; i < chunk.length; i++) { + const item = chunk[i]; + const key = f(item); + if (group === undefined) { + currentKey = key; + group = [item]; + continue; + } else if (Equal.equals(key, currentKey)) { + group.push(item); + continue; + } + toEmit.push([currentKey, group]); + currentKey = key; + group = [item]; + } + if (Arr.isArrayNonEmpty(toEmit)) { + const out = toEmit; + toEmit = []; + return Effect.succeed(out); + } + return loop; + })); + let done = false; + return Pull.catchDone(Effect.suspend(() => done ? Cause.done() : loop), () => { + done = true; + const out = group; + group = undefined; + return out && Arr.isArrayNonEmpty(out) ? Effect.succeed(Arr.of([currentKey, out])) : Cause.done(); + }); +}))))); +/** + * Applies a sink transducer to the stream and emits each sink result. + * + * **Example** (Transducing with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.transduce(Sink.take(2)), + * Stream.runCollect + * ) + * + * result // => [ [ 1, 2 ], [ 3, 4 ], [] ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const transduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => transformPull(self, (upstream, scope) => Effect.sync(() => { + let done; + let leftover; + const upstreamWithLeftover = Effect.suspend(() => { + if (leftover !== undefined) { + const chunk = leftover; + leftover = undefined; + return Effect.succeed(chunk); + } + return upstream; + }).pipe(Effect.catch(error => { + done = Exit.fail(error); + return Cause.done(); + })); + const pull = Effect.map(Effect.suspend(() => sink.transform(upstreamWithLeftover, scope)), ([value, leftover_]) => { + leftover = leftover_; + return Arr.of(value); + }); + return Effect.suspend(() => done ? done : pull); +}))))); +/** + * Aggregates elements using the provided sink and emits each sink result as a stream element. + * + * **Details** + * + * The stream runs the upstream and downstream in separate fibers, so the sink can keep + * consuming input while downstream is busy processing the previous output. + * + * **Example** (Aggregating with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const aggregated = yield* Stream.runCollect( + * Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.aggregate( + * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)) + * ) + * ) + * ) + * aggregated // => [ 6, 15 ] + * })) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const aggregate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever)))); +/** + * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. + * + * **Details** + * + * The schedule can flush the current aggregation even if the sink has not finished. + * + * **Example** (Aggregating with a sink and schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Sink, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const aggregated = yield* Stream.runCollect( + * Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.aggregateWithin( + * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)), + * Schedule.forever + * ) + * ) + * ) + * aggregated // => [ 6, 15 ] + * })) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const aggregateWithin = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, sink, schedule) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_upstream, _, scope) { + const pull = yield* Channel.toPullScoped(self.channel, _); + const pullLatch = Latch.makeUnsafe(false); + const scheduleStep = Symbol(); + const buffer = yield* Queue.make({ + capacity: 0 + }); + // upstream -> buffer + yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => { + pullLatch.closeUnsafe(); + return Queue.offer(buffer, arr); + }), Effect.forever, + // don't disable autoYield to prevent choking the schedule + Effect.catchCause(cause => Queue.failCause(buffer, cause)), Effect.forkIn(scope)); + // schedule -> buffer + let lastOutput = Option.none(); + let leftover; + let sinkHasInput = false; + const step = yield* Schedule.toStepWithSleep(schedule); + const stepLoop = Effect.suspend(function loop() { + return Effect.flatMap(step(lastOutput), () => !sinkHasInput ? loop() : Queue.offer(buffer, scheduleStep)); + }); + const stepToBuffer = stepLoop.pipe(Effect.flatMap(() => Effect.never), Pull.catchDone(() => Cause.done())); + // buffer -> sink + const pullFromBuffer = Queue.take(buffer).pipe(Effect.flatMap(arr => { + if (arr === scheduleStep) { + return Cause.done(); + } + sinkHasInput = true; + return Effect.succeed(arr); + })); + const sinkUpstream = Effect.suspend(() => { + if (leftover !== undefined) { + const chunk = leftover; + leftover = undefined; + sinkHasInput = true; + return Effect.succeed(chunk); + } + pullLatch.openUnsafe(); + return pullFromBuffer; + }); + const catchSinkHalt = Effect.flatMap(([value, leftover_]) => { + // ignore the last output if the upstream only pulled a halt + if (!sinkHasInput && buffer.state._tag === "Done") return Cause.done(); + lastOutput = Option.some(value); + leftover = leftover_; + return Effect.succeed(Arr.of(value)); + }); + return Effect.suspend(() => { + // if the buffer has exited and there is no more data to process + if (buffer.state._tag === "Done" && leftover === undefined) { + return buffer.state.exit; + } + sinkHasInput = leftover !== undefined; + return Effect.succeed(Effect.suspend(() => sink.transform(sinkUpstream, scope))); + }).pipe(Effect.flatMap(pull => Effect.raceFirst(catchSinkHalt(pull), stepToBuffer))); +})))))); +/** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * values // => [ [ 1, 2, 3 ], [ 1, 2, 3 ] ] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category broadcasting + * @since 4.0.0 + */ +const broadcastN = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + const streams = new Array(options.n); + const parentScope = yield* Scope.Scope; + for (let i = 0; i < options.n; i++) { + const scope = Scope.forkUnsafe(parentScope); + const subscription = yield* PubSub.subscribe(pubsub).pipe(Effect.provideService(Scope.Scope, scope)); + streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe(Channel.onExit(exit => Scope.close(scope, exit)), fromChannel); + } + yield* Channel.runForEach(self.channel, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped); + return streams; +})))); +const makePubSub = options => Effect.acquireRelease(options.capacity === "unbounded" ? PubSub.unbounded(options) : options.strategy === "dropping" ? PubSub.dropping(options) : options.strategy === "sliding" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown); +/** + * Creates a PubSub-backed stream that multicasts the source to all subscribers. + * + * **Details** + * + * The returned stream is scoped and uses the provided PubSub capacity and replay settings. + * + * **Example** (Broadcasting a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function* () { + * const broadcasted = yield* Stream.broadcast(Stream.fromArray([1, 2, 3]), { + * capacity: 8, + * replay: 3 + * }) + * + * const [left, right] = yield* Effect.all([ + * Stream.runCollect(broadcasted), + * Stream.runCollect(broadcasted) + * ], { concurrency: "unbounded" }) + * + * const result = [left, right] // => [[1, 2, 3], [1, 2, 3]] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category broadcasting + * @since 2.0.0 + */ +const broadcast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Effect.map(toPubSubTake(self, options), fromPubSubTake)))); +/** + * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. + * + * **Details** + * + * The upstream continues running while there is at least one consumer and is finalized after the last one exits. + * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from + * the next element instead of restarting. + * + * **Example** (Sharing a stream) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Ref, Stream } from "effect" + * + * const result = await Effect.runPromise( + * Effect.scoped( + * Effect.gen(function*() { + * const firstReady = yield* Deferred.make() + * const secondReady = yield* Deferred.make() + * const acquisitions = yield* Ref.make(0) + * const source = Stream.fromEffect(Ref.update(acquisitions, (n) => n + 1)).pipe( + * Stream.drain, + * Stream.concat(Stream.make(0)), + * Stream.concat( + * Stream.fromEffect(Effect.all([Deferred.await(firstReady), Deferred.await(secondReady)])).pipe(Stream.drain) + * ), + * Stream.concat(Stream.make(1, 2, 3)) + * ) + * const shared = yield* Stream.share(source, { capacity: 16, replay: 1 }) + * const consume = (ready: Deferred.Deferred) => + * shared.pipe( + * Stream.tap((value) => value === 0 ? Deferred.succeed(ready, void 0) : Effect.void), + * Stream.filter((value) => value !== 0), + * Stream.runCollect + * ) + * + * const values = yield* Effect.all([consume(firstReady), consume(secondReady)], { concurrency: "unbounded" }) + * return { values, acquisitions: yield* Ref.get(acquisitions) } + * }) + * ) + * ) + * result // => { values: [[1, 2, 3], [1, 2, 3]], acquisitions: 1 } + * ``` + * + * @category broadcasting + * @since 3.8.0 + */ +const share = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Effect.map(RcRef.make({ + acquire: broadcast(self, options), + idleTimeToLive: options.idleTimeToLive +}), ref => unwrap(RcRef.get(ref)))))); +/** + * Pipes this stream through a channel that consumes and emits chunked elements. + * + * **Details** + * + * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the + * output elements and error type. + * + * **Example** (Piping through a channel) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] + * + * const doubleChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, (n) => n * 2)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.rechunk(2), + * Stream.pipeThroughChannel(doubleChunks), + * Stream.runCollect + * ) + * result // => [ 2, 4, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThroughChannel = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, channel) => fromChannel(Channel.pipeTo(self.channel, channel))))); +/** + * Pipes values through the provided channel while preserving this stream's + * failures alongside any channel failures. + * + * **Details** + * + * Upstream failures are not passed to the channel, so the resulting stream can + * fail with either the original stream error or the channel error. + * + * **Example** (Piping through a channel with failures) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] + * + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), + * Stream.runCollect + * ) + * + * result // => ["1", "2", "3"] + * })) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThroughChannelOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, channel) => fromChannel(Channel.pipeToOrFail(self.channel, channel))))); +/** + * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. + * + * **Details** + * + * If the sink completes mid-chunk, the remaining elements become the output stream. + * + * **Example** (Piping through a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const leftovers = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.pipeThrough(Sink.take(2)), + * Stream.runCollect + * ) + * + * leftovers // => [ 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThrough = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => self.channel.pipe(Channel.pipeToOrFail(Sink.toChannel(sink)), Channel.concatWith(([_, leftover]) => leftover ? Channel.succeed(leftover) : Channel.empty), fromChannel)))); +/** + * Collects all elements into an array and emits it as a single element. + * + * **Example** (Collecting values into a stream element) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.gen(function*() { + * const collected = yield* stream.pipe(Stream.collect, Stream.runCollect) + * collected[0] // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 4.0.0 + */ +const collect = self => fromEffect(runCollect(self)); +/** + * Accumulates elements into a growing array, emitting the cumulative array for each input chunk. + * + * **Example** (Accumulating stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const accumulated = yield* Stream.runCollect( + * Stream.fromArray([1, 2, 3]).pipe( + * Stream.rechunk(1), + * Stream.accumulate + * ) + * ) + * accumulated // => [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => { + const combined = Arr.appendAll(acc, as); + return [combined, [combined]]; +}); +/** + * Emits only elements that differ from the previous one. + * + * **Example** (Emitting changed values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.fromIterable([1, 1, 2, 2, 3]).pipe( + * Stream.changes, + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changes = self => changesWith(self, Equal.equals); +/** + * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. + * + * **Example** (Emitting values that changed by equivalence) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("A", "a", "B", "b", "b").pipe( + * Stream.changesWith((left, right) => left.toLowerCase() === right.toLowerCase()) + * ) + * + * await Effect.runPromise( + * Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 'A', 'B' ] + * }) + * ) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changesWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let first = true; + let last; + return Effect.flatMap(pull, function loop(arr) { + const out = []; + let i = 0; + if (first) { + first = false; + last = arr[0]; + i = 1; + out.push(last); + } + for (; i < arr.length; i++) { + const a = arr[i]; + if (f(a, last)) continue; + last = a; + out.push(a); + } + return Arr.isArrayNonEmpty(out) ? Effect.succeed(out) : Effect.flatMap(pull, loop); + }); +}))))); +/** + * Emits only elements that differ from the previous element, using an effectful equality check. + * + * **Details** + * + * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. + * + * **Example** (Effectfully emitting changed values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 1, 2, 2, 3, 3).pipe( + * Stream.changesWithEffect((a, b) => Effect.succeed(a === b)) + * ) + * const result = yield* Stream.runCollect(stream) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changesWithEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let first = true; + let last; + return Effect.flatMap(pull, Effect.fnUntraced(function* loop(arr) { + const out = []; + let i = 0; + if (first) { + first = false; + last = arr[0]; + i = 1; + out.push(last); + } + for (; i < arr.length; i++) { + const a = arr[i]; + if (yield* f(a, last)) continue; + last = a; + out.push(a); + } + return Arr.isArrayNonEmpty(out) ? out : yield* Effect.flatMap(pull, Effect.fnUntraced(loop)); + })); +}))))); +/** + * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding. + * + * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const encoder = new TextEncoder() + * const stream = Stream.make( + * encoder.encode("Hello"), + * encoder.encode(" World") + * ) + * + * const program = Effect.gen(function*() { + * const decoded = yield* stream.pipe( + * Stream.decodeText, + * Stream.runCollect + * ) + * decoded // => [ 'Hello', ' World' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeText = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => suspend(() => { + const decoder = new TextDecoder(options?.encoding); + return map(self, chunk => decoder.decode(chunk, { + stream: true + })); +})))); +/** + * Encodes a stream of strings into UTF-8 `Uint8Array` chunks. + * + * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("Hello", " ", "World") + * const program = Effect.gen(function*() { + * const encoded = Stream.encodeText(stream) + * const chunks = yield* Stream.runCollect(encoded) + * const bytes = chunks.map((chunk) => [...chunk]) + * bytes // => [ [ 72, 101, 108, 108, 111 ], [ 32 ], [ 87, 111, 114, 108, 100 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category encoding + * @since 2.0.0 + */ +const encodeText = self => suspend(() => { + const encoder = new TextEncoder(); + return map(self, chunk => encoder.encode(chunk)); +}); +/** + * Splits a stream of strings into lines, handling `\n`, `\r`, and `\r\n` delimiters across chunks. + * + * **Example** (Splitting streamed text into lines) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const lines = yield* Stream.runCollect( + * Stream.make("a\nb\r\n", "c\n").pipe(Stream.splitLines) + * ) + * lines // => [ 'a', 'b', 'c' ] + * })) + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.splitLines()), fromChannel); +/** + * Inserts the provided element between emitted elements. + * + * **Example** (Interspersing stream elements) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.intersperse(0)) + * const result = yield* Stream.runCollect(stream) + * result // => [1, 0, 2, 0, 3, 0, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, element) => mapArray(self, (arr, i) => { + const out = i === 0 ? [] : [element]; + const lastIndex = arr.length - 1; + for (let j = 0; j < arr.length; j++) { + if (j === lastIndex) { + out.push(arr[j]); + } else { + out.push(arr[j], element); + } + } + return out; +})))); +/** + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** + * + * The start and end values are always emitted, even when the stream is empty. + * + * **Example** (Interspersing stream affixes) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const stream = Stream.make("a", "b", "c").pipe( + * Stream.intersperseAffixes({ start: "[", middle: ",", end: "]" }) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => ["[", "a", ",", "b", ",", "c", "]"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const intersperseAffixes = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => succeed(options.start).pipe(concat(intersperse(self, options.middle)), concat(succeed(options.end)))))); +/** + * Interleaves this stream with the specified stream by alternating pulls from + * each stream; when one ends, the remaining values from the other stream are + * emitted. + * + * **Example** (Interleaving streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.interleave( + * Stream.make(2, 3), + * Stream.make(5, 6, 7) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [ 2, 5, 3, 6, 7 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const interleave = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => interleaveWith(self, that, fromIterable(Iterable.forever([true, false])))))); +/** + * Interleaves two streams deterministically by following a boolean decider stream. + * + * **Details** + * + * The decider controls how many elements are pulled; if one side ends, pulls for + * that side are ignored. + * + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 3, 5) + * const right = Stream.make(2, 4, 6) + * const decider = Stream.make(true, false, false, true, true) + * + * const values = yield* Stream.runCollect( + * Stream.interleaveWith(left, right, decider) + * ) + * + * values // => [ 1, 2, 4, 3, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const interleaveWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, decider) => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pullDecider = yield* Channel.toTransform(Channel.flattenArray(decider.channel))(upstream, scope); + const retry = Symbol(); + let leftDone = false; + let rightDone = false; + const pullLeft = (yield* Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope)).pipe(Pull.catchDone(() => { + leftDone = true; + return Effect.succeed(retry); + })); + const pullRight = (yield* Channel.toTransform(Channel.flattenArray(that.channel))(upstream, scope)).pipe(Pull.catchDone(() => { + rightDone = true; + return Effect.succeed(retry); + })); + return Effect.gen(function* () { + while (true) { + if (leftDone && rightDone) { + return yield* Cause.done(); + } + const side = yield* pullDecider; + if (side && leftDone) continue; + if (!side && rightDone) continue; + const elem = yield* side ? pullLeft : pullRight; + if (elem === retry) continue; + return Arr.of(elem); + } + }); +})))))); +/** + * Interrupts the evaluation of this stream when the provided effect + * completes. The given effect will be forked as part of this stream, and its + * success will be discarded. This combinator will also interrupt any + * in-progress element being pulled from upstream. + * + * **Details** + * + * If the effect completes with a failure before the stream completes, the + * returned stream will emit that failure. + * + * **Example** (Interrupting when an effect completes) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const interrupt = yield* Deferred.make() + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.tap((value) => + * value === 2 + * ? Deferred.succeed(interrupt, void 0) + * : Effect.void + * ), + * Stream.interruptWhen(Deferred.await(interrupt)) + * ) + * + * const result = yield* Stream.runCollect(stream) + * result // => [ 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptWhen = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, effect) => fromChannel(_Channel_js__rspack_import_1/* .interruptWhen */.S6(self.channel, effect))); +/** + * Stops a stream after the current pull when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt or truncate an in-progress pull. A pull may emit + * multiple elements in a single chunk, in which case the entire chunk is + * emitted. Use {@link interruptWhen} when the stream should be interrupted + * immediately. + * + * **Example** (Halting a stream after an effect completes) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const halt = yield* Deferred.make() + * const values = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.tap((value) => value === 2 ? Deferred.succeed(halt, void 0) : Effect.void), + * Stream.haltWhen(Deferred.await(halt)), + * Stream.runCollect + * ) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const haltWhen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => fromChannel(Channel.haltWhen(self.channel, effect))))); +/** + * Runs the provided finalizer when the stream exits, passing the exit value. + * + * **Example** (Running a finalizer on exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * const exits: Array = [] + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.onExit((exit) => + * Exit.isSuccess(exit) + * ? Effect.sync(() => exits.push("success")) + * : Effect.sync(() => exits.push("failure")) + * ) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * yield* Stream.runCollect(stream) + * })) + * exits // => ["success"] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, finalizer) => fromChannel(_Channel_js__rspack_import_1/* .onExit */.cf(self.channel, finalizer))); +/** + * Runs the provided effect when the stream fails, passing the failure cause. + * + * **Gotchas** + * + * Note: Unlike `Effect.onError` there is no guarantee that the provided + * effect will not be interrupted. + * + * **Example** (Running an effect on errors) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const errors: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.onError((cause) => Effect.sync(() => errors.push(String(Cause.squash(cause))))) + * ) + * + * yield* Stream.runCollect(stream) + * }) + * + * await Effect.runPromise(Effect.exit(program)) + * errors // => ["boom"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const onError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cleanup) => fromChannel(Channel.onError(self.channel, cleanup))))); +/** + * Runs the provided effect before this stream starts. + * + * **Example** (Running an effect on start) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.fromArray([1, 2, 3]).pipe( + * Stream.onStart(Effect.sync(() => events.push("started"))) + * ) + * + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["started"] + * ``` + * + * @category sequencing + * @since 3.6.0 + */ +const onStart = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onStart) => fromChannel(Channel.onStart(self.channel, onStart))))); +/** + * Runs the provided effect with the first element emitted by the stream. + * + * **Example** (Running an effect on the first value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const first: Array = [] + * await Effect.runPromise(Effect.gen(function* () { + * yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.onFirst((value) => Effect.sync(() => first.push(value))), + * Stream.runDrain + * ) + * })) + * first // => [1] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const onFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFirst) => fromChannel(Channel.onFirst(self.channel, arr => onFirst(arr[0])))))); +/** + * Runs the provided effect when the stream ends successfully. + * + * **Example** (Running an effect on end) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.onEnd(Effect.sync(() => events.push("ended"))), + * Stream.runCollect + * ) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["ended"] + * ``` + * + * @category sequencing + * @since 3.6.0 + */ +const onEnd = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onEnd) => fromChannel(Channel.onEnd(self.channel, onEnd))))); +/** + * Executes the provided finalizer after this stream's finalizers run. + * + * **Example** (Ensuring finalization) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.fromArray([1, 2]).pipe( + * Stream.ensuring(Effect.sync(() => events.push("cleanup"))) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * events // => ["cleanup"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => fromChannel(Channel.ensuring(self.channel, finalizer))))); +/** + * Provides a layer or context to the stream, removing the corresponding + * service requirements. Use `options.local` to build the layer every time; by + * default, layers are shared between provide calls. + * + * **Example** (Providing stream requirements) + * + * ```ts import.meta.vitest + * import { Console, Context, Effect, Layer, Stream } from "effect" + * + * class Env extends Context.Service()("Env") {} + * + * const layer = Layer.succeed(Env)({ name: "Ada" }) + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const env = yield* Effect.service(Env) + * return `Hello, ${env.name}` + * }) + * ) + * + * const withEnv = stream.pipe(Stream.provide(layer)) + * + * await Effect.runPromise(Stream.runCollect(withEnv)) // => ["Hello, Ada"] + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, layer, options) => fromChannel(Channel.provide(self.channel, layer, options))))); +/** + * Provides multiple services to the stream using a context. + * + * **Example** (Providing multiple services to the stream using a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Config extends Context.Service()("Config") {} + * class Greeter extends Context.Service string }>()("Greeter") {} + * + * const context = Context.make(Config, { prefix: "Hello" }).pipe( + * Context.add(Greeter, { greet: (name: string) => `${name}!` }) + * ) + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * const greeter = yield* Effect.service(Greeter) + * return greeter.greet(config.prefix) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(Stream.provideContext(stream, context)) + * result // => [ 'Hello!' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => fromChannel(Channel.provideContext(self.channel, context))))); +/** + * Provides the stream with a single required service, eliminating that + * requirement from its environment. + * + * **Example** (Providing a stream service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.fromEffect( + * Effect.service(Greeter).pipe( + * Effect.map((greeter) => greeter.greet("Ada")) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}` + * }) + * ) + * ) + * collected // => [ 'Hello, Ada' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideService = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(3, (self, key, service) => fromChannel(_Channel_js__rspack_import_1/* .provideService */.Pf(self.channel, key, service))); +/** + * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. + * + * **Example** (Providing a stream service effectfully) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class ApiConfig extends Context.Service()("ApiConfig") {} + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const config = yield* Effect.service(ApiConfig) + * return config.baseUrl + * }) + * ) + * + * const events: Array = [] + * const withConfig = stream.pipe( + * Stream.provideServiceEffect( + * ApiConfig, + * Effect.succeed({ baseUrl: "https://example.com" }).pipe( + * Effect.tap(() => Effect.sync(() => events.push("loading"))) + * ) + * ) + * ) + * + * await Effect.runPromise(Stream.runCollect(withConfig)) // => ["https://example.com"] + * events // => ["loading"] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideServiceEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => fromChannel(Channel.provideServiceEffect(self.channel, key, service))))); +/** + * Transforms the stream's required services by mapping the current context + * to a new one. + * + * **Example** (Updating the stream context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Logger extends Context.Service()("Logger") {} + * class Config extends Context.Service()("Config") {} + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * const config = yield* Effect.service(Config) + * return `${logger.prefix}${config.name}` + * }) + * ) + * + * const updated = stream.pipe( + * Stream.updateContext((context: Context.Context) => + * Context.add(context, Config, { name: "World" }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(updated) + * values // => [ 'Hello World' ] + * }) + * + * await Effect.runPromise( + * Effect.provideService(program, Logger, { prefix: "Hello " }) + * ) + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.updateContext(self.channel, f))))); +/** + * Updates a single service in the stream environment by applying a function. + * + * **Example** (Updating a stream service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Counter extends Context.Service()("Counter") {} + * + * const stream = Stream.fromEffect(Effect.service(Counter)).pipe( + * Stream.updateService(Counter, (counter) => ({ count: counter.count + 1 })) + * ) + * + * const program = Effect.gen(function*() { + * const counters = yield* Stream.runCollect(stream) + * const message = `Updated count: ${counters[0].count}` // => "Updated count: 1" + * }) + * + * await Effect.runPromise(Effect.provideService(program, Counter, { count: 0 })) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service))))))); +/** + * Wraps the stream with a new span for tracing. + * + * **Example** (Wrapping a stream in a span) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.withSpan("numbers")) + * + * await Effect.runPromise( + * Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3 ] + * }) + * ) + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = isStream(arguments[0]); + const name = dataFirst ? arguments[1] : arguments[0]; + const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return fromChannel(Channel.withSpan(self.channel, name, options)); + } + return self => fromChannel(Channel.withSpan(self.channel, name, options)); +}; +/** + * Provides the entry point for do-notation style stream composition. + * + * **Example** (Starting stream do notation) + * + * ```ts import.meta.vitest + * import { Effect, pipe, Stream } from "effect" + * + * const program = pipe( + * Stream.Do, + * Stream.bind("value", () => Stream.fromArray([1, 2])), + * Stream.let("next", ({ value }) => value + 1) + * ) + * + * const effect = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(program) + * collected // => [ { value: 1, next: 2 }, { value: 2, next: 3 } ] + * }) + * + * await Effect.runPromise(effect) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, name, f) => map(self, a => ({ + ...a, + [name]: f(a) +}))))); + +/** + * Binds the result of a stream to a field in the do-notation record. + * + * **Example** (Binding a stream value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.Do.pipe( + * Stream.bind("a", () => Stream.make(1, 2)), + * Stream.bind("b", ({ a }) => Stream.succeed(a + 1)) + * ) + * + * const result = Stream.runCollect(program) + * + * await Effect.runPromise(result) // => [{ a: 1, b: 2 }, { a: 2, b: 3 }] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, tag, f, options) => flatMap(self, a => map(f(a), b => ({ + ...a, + [tag]: b +})), options)))); +/** + * Binds an Effect-produced value into the do-notation record for each stream element. + * + * **Example** (Binding an effect value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.Do.pipe( + * Stream.bind("value", () => Stream.make(1, 2)), + * Stream.bindEffect("double", ({ value }) => Effect.succeed(value * 2)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ { value: 1, double: 2 }, { value: 2, double: 4 } ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const bindEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, tag, f, options) => mapEffect(self, a => Effect.map(f(a), b => ({ + ...a, + [tag]: b +})), options)))); +/** + * Maps each element into a record keyed by the provided name. + * + * **Example** (Binding values to a record key) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3).pipe(Stream.bindTo("value")) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [{ value: 1 }, { value: 2 }, { value: 3 }] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, name) => map(self, a => ({ + [name]: a +}))))); +/** + * Runs a stream with a sink and returns the sink result. + * + * **Example** (Running a stream with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Stream.run(Stream.make(1, 2, 3), Sink.sum) + * + * await Effect.runPromise(program) // => 6 + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const run = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => Effect.scopedWith(scope => Channel.toPullScoped(self.channel, scope).pipe(Effect.flatMap(upstream => sink.transform(upstream, scope)), Effect.map(([a]) => a)))))); +/** + * Runs the stream and collects all elements into an array. + * + * **Example** (Collecting stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runCollect = self => Channel.runFold(self.channel, () => [], (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc.push(chunk[i]); + } + return acc; +}); +/** + * Runs the stream and returns the number of elements emitted. + * + * **Example** (Counting stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const program = Effect.gen(function* () { + * const count = yield* Stream.runCount(stream) + * count // => 5 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length); +/** + * Runs the stream and returns the numeric sum of its elements. + * + * **Example** (Summing stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runSum(Stream.make(1, 2, 3)) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc += chunk[i]; + } + return acc; +}); +/** + * Runs the stream and folds elements using a pure reducer. + * + * **Example** (Folding stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runFold( + * Stream.make(1, 2, 3), + * () => 0, + * (acc, n) => acc + n + * ) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runFold = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Channel.runFold(self.channel, initial, (acc, arr) => { + for (let i = 0; i < arr.length; i++) { + acc = f(acc, arr[i]); + } + return acc; +})))); +/** + * Runs the stream and folds elements using an effectful reducer. + * + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runFoldEffect( + * Stream.make(1, 2, 3), + * () => 0, + * (acc, n) => Effect.succeed(acc + n) + * ) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runFoldEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Channel.runFoldEffect(self.channel, initial, (acc, arr) => { + let i = 0; + let s = acc; + return Effect.map(Effect.whileLoop({ + while: () => i < arr.length, + body: () => f(s, arr[i]), + step(z) { + s = z; + i++; + } + }), () => s); +})))); +/** + * Runs the stream and returns the first element as an `Option`. + * + * **Example** (Getting the first stream value) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const head = yield* Stream.runHead(Stream.make(1, 2, 3)) + * Option.getOrThrow(head) // => 1 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runHead = self => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0))); +/** + * Runs the stream and returns the last element as an `Option`. + * + * **When to use** + * + * Use to consume a finite stream when only the final emitted element matters. + * + * **Details** + * + * `Option.some` contains the last emitted element. `Option.none` means the + * stream completed without emitting. + * + * **Gotchas** + * + * The returned effect waits for the stream to complete before it can produce a + * value. + * + * @see {@link runHead} for consuming only the first emitted element + * @see {@link runCollect} for collecting every emitted element + * @see {@link runDrain} for consuming the stream while discarding emitted elements + * + * @category destructors + * @since 2.0.0 + */ +const runLast = self => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty)); +/** + * Runs the provided effectful callback for each element of the stream. + * + * **Example** (Running an effect for each value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * const values: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Stream.runForEach(stream, (n) => Effect.sync(() => values.push(`Processing: ${n}`))) + * }) + * + * await Effect.runPromise(program) + * values // => ["Processing: 1", "Processing: 2", "Processing: 3"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runForEach = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => _Channel_js__rspack_import_1/* .runForEach */.o1(self.channel, arr => { + let i = 0; + return _Effect_js__rspack_import_3/* .whileLoop */.iMI({ + while: () => i < arr.length, + body: () => f(arr[i++]), + step: _Function_js__rspack_import_7/* .constVoid */.Yi + }); +})); +/** + * Runs the stream, applying the effectful predicate to each element and + * stopping when it returns `false`. + * + * **Example** (Running effects while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const values: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * yield* Stream.runForEachWhile(stream, (n) => + * Effect.gen(function*() { + * yield* Effect.sync(() => values.push(n)) + * return n < 3 + * }) + * ) + * }) + * + * await Effect.runPromise(program) + * values // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runForEachWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => Channel.runForEachWhile(self.channel, arr => { + let done = false; + let i = 0; + return Effect.map(Effect.whileLoop({ + while: () => !done && i < arr.length, + body: () => f(arr[i]), + step(b) { + i++; + if (!b) done = true; + } + }), () => !done); +})))); +/** + * Consumes the stream in chunks, passing each non-empty array to the callback. + * + * **Example** (Consuming stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const chunks: Array = [] + * const program = Effect.gen(function*() { + * yield* Stream.runForEachArray( + * stream, + * (chunk) => Effect.sync(() => chunks.push(chunk.join(", "))) + * ) + * }) + * + * await Effect.runPromise(program) + * chunks // => ["1, 2, 3, 4, 5"] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const runForEachArray = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => _Channel_js__rspack_import_1/* .runForEach */.o1(self.channel, f)); +/** + * Runs the stream for its effects, discarding emitted elements. + * + * **Example** (Draining a stream run) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const values: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.mapEffect((n) => Effect.sync(() => values.push(n))) + * ) + * + * yield* Stream.runDrain(stream) + * }) + * + * await Effect.runPromise(program) + * values // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runDrain = self => Channel.runDrain(self.channel); +/** + * Returns a scoped pull for manually consuming the stream's output chunks. + * + * **Details** + * + * The pull fails with `Cause.Done` when the stream ends and with the stream + * error on failure. + * + * **Example** (Creating a scoped pull) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const pull = yield* Stream.toPull(stream) + * const chunk = yield* pull + * chunk // => [ 1, 2, 3 ] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPull = self => Channel.toPull(self.channel); +/** + * Concatenates all emitted strings into a single string. + * + * **Example** (Joining strings from a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("Hello", " ", "World", "!") + * const program = Effect.gen(function*() { + * const text = yield* Stream.mkString(stream) + * text // => "Hello World!" + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const mkString = self => Channel.runFold(self.channel, () => "", (acc, chunk) => acc + chunk.join("")); +/** + * Concatenates the stream's `Uint8Array` chunks into a single `ArrayBuffer`. + * + * **Example** (Joining byte chunks into an ArrayBuffer) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make( + * new Uint8Array([1, 2]), + * new Uint8Array([3, 4]) + * ).pipe( + * Stream.mkArrayBuffer, + * Effect.map((buffer) => [...new Uint8Array(buffer)]) + * ) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4] + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source stream must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category destructors + * @since 4.0.0 + */ +const mkArrayBuffer = self => Effect.map(Channel.mkUint8Array(self.channel), bytes => bytes.buffer); +/** + * Concatenates the stream's `Uint8Array` chunks into a single `Uint8Array`. + * + * **Example** (Joining Uint8Array chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(new Uint8Array([1, 2]), new Uint8Array([3, 4])) + * const program = Effect.gen(function*() { + * const bytes = yield* Stream.mkUint8Array(stream) + * const values = Array.from(bytes) // => [1, 2, 3, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source stream must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category destructors + * @since 4.0.0 + */ +const mkUint8Array = self => Channel.mkUint8Array(self.channel); +/** + * Converts the stream to a `ReadableStream` using the provided services. + * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Converting to a ReadableStream with services) + * + * ```ts import.meta.vitest + * import { Context, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) + * const values = await Array.fromAsync(readableStream) + * values // => [ 1, 2, 3, 4, 5 ] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toReadableStreamWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, context, options) => { + let currentResolve = undefined; + let fiber = undefined; + const latch = Latch.makeUnsafe(false); + return new ReadableStream({ + start(controller) { + fiber = Effect.runFork(Effect.provideContext(runForEachArray(self, chunk => latch.whenOpen(Effect.sync(() => { + latch.closeUnsafe(); + for (let i = 0; i < chunk.length; i++) { + controller.enqueue(chunk[i]); + } + currentResolve(); + currentResolve = undefined; + }))), context)); + fiber.addObserver(exit => { + if (exit._tag === "Failure") { + controller.error(Cause.squash(exit.cause)); + } else { + controller.close(); + } + }); + }, + pull() { + return new Promise(resolve => { + currentResolve = resolve; + latch.openUnsafe(); + }); + }, + cancel() { + if (!fiber) return; + return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber))); + } + }, options?.strategy); +}))); +/** + * Converts a stream to a `ReadableStream`. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Converting a stream to a ReadableStream) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * const readableStream = Stream.toReadableStream(Stream.make(1, 2, 3)) + * const values = await Array.fromAsync(readableStream) + * values // => [ 1, 2, 3 ] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toReadableStream = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => toReadableStreamWith(self, Context.empty(), options)))); +/** + * Creates an Effect that builds a ReadableStream from the stream. + * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Creating a ReadableStream effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const effect = Effect.gen(function*() { + * const readableStream = yield* Stream.toReadableStreamEffect(stream) + * readableStream instanceof ReadableStream // => true + * }) + * + * await Effect.runPromise(effect) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toReadableStreamEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => Effect.map(Effect.context(), context => toReadableStreamWith(self, context, options))))); +/** + * Converts the stream to an `AsyncIterable` using the provided services. + * + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * + * ```ts import.meta.vitest + * import { Context, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * const iterable = Stream.toAsyncIterableWith(stream, Context.empty()) + * + * await Array.fromAsync(iterable) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toAsyncIterableWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => ({ + [Symbol.asyncIterator]() { + const runPromise = Effect.runPromiseWith(context); + const runFork = Effect.runForkWith(context); + const scope = Scope.makeUnsafe(); + let pull; + let currentIter; + let currentFiber; + let closePromise; + const close = exit => { + if (closePromise) return closePromise; + const fiber = currentFiber; + closePromise = runPromise(Effect.as(Effect.andThen(fiber ? Fiber.interrupt(fiber) : Effect.void, Scope.close(scope, exit)), { + done: true, + value: undefined + })); + return closePromise; + }; + const closeAndReportError = async exit => { + try { + await close(exit); + } catch (error) { + await runPromise(Effect.logError("Suppressed error while closing Stream async iterator", error)); + } + }; + return { + async next() { + if (closePromise) return closePromise; + if (currentIter) { + const next = currentIter.next(); + if (!next.done) return next; + currentIter = undefined; + } + const fiber = runFork(pull ?? Effect.flatMap(Channel.toPullScoped(self.channel, scope), nextPull => { + pull = nextPull; + return nextPull; + })); + currentFiber = fiber; + const exit = await runPromise(Fiber.await(fiber)); + if (currentFiber === fiber) { + currentFiber = undefined; + } + if (Exit.isSuccess(exit)) { + currentIter = exit.value[Symbol.iterator](); + return currentIter.next(); + } else if (Pull.isDoneCause(exit.cause)) { + return close(Exit.void); + } + if (closePromise && Cause.hasInterruptsOnly(exit.cause)) { + return closePromise; + } + await closeAndReportError(exit); + throw Cause.squash(exit.cause); + }, + return() { + return close(Exit.void); + }, + async throw(error) { + await closeAndReportError(Exit.die(error)); + throw error; + } + }; + } +})))); +/** + * Creates an effect that yields an `AsyncIterable` using the current services. + * + * **When to use** + * + * Use when the `AsyncIterable` should be created inside Effect with the current + * context supplying the stream's services. + * + * **Example** (Creating an AsyncIterable effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.gen(function*() { + * const iterable = yield* Stream.toAsyncIterableEffect(stream) + * return yield* Effect.promise(() => Array.fromAsync(iterable)) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 3.15.0 + */ +const toAsyncIterableEffect = self => Effect.map(Effect.context(), context => toAsyncIterableWith(self, context)); +/** + * Converts a stream to an `AsyncIterable` for `for await...of` consumption. + * + * **Example** (Converting to an async iterable) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * await Array.fromAsync(Stream.toAsyncIterable(stream)) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 3.15.0 + */ +const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty()); +/** + * Runs the stream, publishing elements into the provided PubSub. + * + * **Details** + * + * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. + * It only shuts down when set to `true`. + * + * **Example** (Running a stream into a PubSub) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function* () { + * const pubsub = yield* PubSub.unbounded() + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* Stream.runIntoPubSub(Stream.fromIterable([1, 2]), pubsub) + * + * const first = yield* PubSub.take(subscription) + * const second = yield* PubSub.take(subscription) + * + * first // => 1 + * second // => 2 + * })) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runIntoPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, pubsub, options) => Channel.runIntoPubSubArray(self.channel, pubsub, options)))); +/** + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** + * + * `shutdownOnEnd` indicates whether the PubSub should be shut down when the + * stream ends. By default this is `true`. + * + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function* () { + * const pubsub = yield* Stream.fromArray([1, 2]).pipe( + * Stream.toPubSub({ capacity: 8 }) + * ) + * const subscription = yield* PubSub.subscribe(pubsub) + * const first = yield* PubSub.take(subscription) + * + * first // => 1 + * })) + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toPubSubArray(self.channel, options)))); +/** + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** + * + * `Take` values include the stream's end and failure signals. + * + * **Example** (Converting to a PubSub of takes) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const pubsub = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.toPubSubTake({ capacity: 8 }) + * ) + * const subscription = yield* PubSub.subscribe(pubsub) + * const take = yield* PubSub.take(subscription) + * + * if (Array.isArray(take)) { + * take // => [ 1, 2, 3 ] + * } + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubTake = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toPubSubTake(self.channel, options)))); +/** + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) + * + * ```ts import.meta.vitest + * import { Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const queue = yield* Stream.toQueue(Stream.fromIterable([1, 2, 3]), { capacity: 8 }) + * const chunk = yield* Queue.takeBetween(queue, 1, 3) + * chunk // => [ 1, 2, 3 ] + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toQueueArray(self.channel, options)))); +/** + * Runs the stream, offering each element to the provided queue and ending it + * with `Cause.Done` when the stream completes. + * + * **Example** (Running a stream into a queue) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(4) + * + * yield* Effect.forkChild( + * Stream.runIntoQueue(Stream.fromIterable([1, 2, 3]), queue) + * ) + * + * const values = [ + * yield* Queue.take(queue), + * yield* Queue.take(queue), + * yield* Queue.take(queue) + * ] + * const done = yield* Effect.flip(Queue.take(queue)) + * + * values // => [ 1, 2, 3 ] + * done._tag === "Done" // => true + * }) + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runIntoQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, queue) => Channel.runIntoQueueArray(self.channel, queue)))); +//# sourceMappingURL=Stream.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + EnV: paginate, + Mim: tap, + PfK: provideService, + QKh: takeUntil, + S67: interruptWhen, + WK$: mapEffect, + cfM: onExit, + ciY: fromArray, + hM$: runForEachArray, + o1d: runForEach, + oAg: unwrap, + sFT: tapError, + t8s: unfold, + xWs: concat +}); + + +}, +"./node_modules/effect/dist/Tracer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Encoding_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Encoding.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/** + * Defines the low-level tracing model used by Effect. + * + * A span records the lifetime of an operation, including its name, parent, + * attributes, links, annotations, sampling decision, kind, and completion + * status. The module also defines the tracer service, parent-span context, + * external span support, trace propagation settings, and the default in-memory + * span implementation. + * + * @since 2.0.0 + */ + + + + +const evaluate = "~effect/Effect/evaluate"; +/** + * 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" + * ``` + * + * @category constants + * @since 4.0.0 + */ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** + * Context service containing the `Span` or `ExternalSpan` to use as the parent + * of newly-created child spans. + * + * **Example** (Accessing the parent span) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the parent span from the context + * const program = Effect.gen(function*() { + * const parentSpan = yield* Effect.service(Tracer.ParentSpan) + * return parentSpan.spanId + * }) + * + * const parent = Tracer.externalSpan({ spanId: "span-123", traceId: "trace-456" }) + * await Effect.runPromise(Effect.provideService(program, Tracer.ParentSpan, parent)) // => "span-123" + * ``` + * + * @category services + * @since 2.0.0 + */ +class ParentSpan extends /*#__PURE__*/_Context_js__rspack_import_0/* .Service */.kl()(ParentSpanKey, { + fiberCached: true +}) {} +/** + * Creates a `Tracer` value from a tracer implementation object. + * + * **When to use** + * + * Use to create a custom tracing backend value that Effect can use when + * creating spans. + * + * **Details** + * + * `make` returns the supplied implementation object unchanged. The object must + * satisfy the `Tracer` contract, including a `span` method that returns a + * `Span`. + * + * @see {@link Span} for the span values returned by tracer implementations + * + * @category constructors + * @since 2.0.0 + */ +const make = options => options; +/** + * Creates an `ExternalSpan` from trace and span identifiers, defaulting + * `sampled` to `true` and annotations to an empty context when they are not + * provided. + * + * **Example** (Creating an external span) + * + * ```ts import.meta.vitest + * import { Effect, Option, Tracer } from "effect" + * + * // Create an external span from another tracing system + * const span = Tracer.externalSpan({ + * spanId: "span-abc-123", + * traceId: "trace-xyz-789", + * sampled: true + * }) + * + * // Use the external span as a parent + * const program = Effect.succeed("Hello").pipe( + * Effect.withSpan("child-operation", { parent: span }) + * ) + * + * const spans: Array = [] + * const tracer = Tracer.make({ + * span(options) { + * const span = new Tracer.NativeSpan(options) + * spans.push(span) + * return span + * } + * }) + * const value = await Effect.runPromise(Effect.provideService(program, Tracer.Tracer, tracer)) + * + * value // => "Hello" + * spans.map((span) => Option.getOrUndefined(span.parent)?.spanId) // => ["span-abc-123"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const externalSpan = options => ({ + _tag: "ExternalSpan", + spanId: options.spanId, + traceId: options.traceId, + sampled: options.sampled ?? true, + annotations: options.annotations ?? Context.empty() +}); +/** + * Context reference for disabling trace propagation. + * + * **When to use** + * + * Use to prevent spans in a scope from propagating tracing context. + * + * **Details** + * + * When enabled on fiber or span annotations, new spans are created as + * non-propagating no-op spans and disabled spans are skipped when deriving a + * parent span. + * + * **Example** (Disabling span propagation) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Disable span propagation for a specific effect + * const program = Tracer.DisablePropagation.pipe( + * Effect.provideService(Tracer.DisablePropagation, true) + * ) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 3.12.0 + */ +const DisablePropagation = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/DisablePropagation", { + defaultValue: _Function_js__rspack_import_1/* .constFalse */.f4 +}); +/** + * Context reference for controlling the current trace level for dynamic filtering. + * + * **When to use** + * + * Use to set the default trace level for spans in a scope when span options do + * not provide `level`. + * + * **Details** + * + * The default value is `"Info"`. Span creation uses `options.level ?? + * CurrentTraceLevel` before applying `MinimumTraceLevel`. + * + * @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled + * + * @category services + * @since 4.0.0 + */ +const CurrentTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/CurrentTraceLevel", { + defaultValue: () => "Info" +}); +/** + * Context reference for setting the minimum trace level threshold. Spans and their + * descendants below this level will have their sampling decision forced to + * false, preventing them from being exported. + * + * **When to use** + * + * Use to set the trace-level threshold that controls whether spans are sampled + * by default. + * + * **Details** + * + * The default value is `"All"`. Span creation compares the span level from + * `options.level ?? CurrentTraceLevel` against this threshold. + * + * **Gotchas** + * + * Explicit `options.sampled` bypasses threshold computation. + * + * @see {@link CurrentTraceLevel} for the default span level used when options do not specify one + * + * @category services + * @since 4.0.0 + */ +const MinimumTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/MinimumTraceLevel", { + defaultValue: () => "All" +}); +/** + * 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. + * + * @category constants + * @since 4.0.0 + */ +const TracerKey = "effect/Tracer"; +/** + * Context reference for the active tracer service. By default it uses the + * native tracer, which creates `NativeSpan` instances. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the current tracer from the context + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.service(Tracer.Tracer) + * // Or use the built-in tracer effect + * const tracerFromAccessor = yield* Effect.tracer + * return tracer === tracerFromAccessor + * }) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 2.0.0 + */ +const Tracer = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or(TracerKey, { + fiberCached: true, + defaultValue: () => make({ + span: options => new NativeSpan(options) + }) +}); +/** + * Default in-memory `Span` implementation used by the native tracer. It + * generates span and trace identifiers, stores attributes, events, and links, + * and records `Started` or `Ended` status. + * + * **Details** + * + * The constructor initializes the span with `Started` status, inherits the + * parent trace id or generates a new one, and always generates a new span id. + * Attributes, events, links, and status are then mutated through `Span` methods. + * + * @see {@link Span} for the interface implemented by native spans + * + * @category models + * @since 4.0.0 + */ +class NativeSpan { + _tag = "Span"; + spanId; + traceId = "native"; + sampled; + name; + parent; + annotations; + links; + startTime; + kind; + status; + attributes; + events = []; + constructor(options) { + this.name = options.name; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = options.links; + this.startTime = options.startTime; + this.kind = options.kind; + this.sampled = options.sampled; + this.status = { + _tag: "Started", + startTime: options.startTime + }; + this.attributes = new Map(); + this.traceId = _Option_js__rspack_import_2.getOrUndefined(options.parent)?.traceId ?? _Encoding_js__rspack_import_3/* .randomHex */.nw(32); + this.spanId = _Encoding_js__rspack_import_3/* .randomHex */.nw(16); + } + end(endTime, exit) { + this.status = { + _tag: "Ended", + endTime, + exit, + startTime: this.status.startTime + }; + } + attribute(key, value) { + this.attributes.set(key, value); + } + event(name, startTime, attributes) { + this.events.push([name, startTime, attributes ?? {}]); + } + addLinks(links) { + // oxlint-disable-next-line no-restricted-syntax + this.links.push(...links); + } +} +//# sourceMappingURL=Tracer.js.map +__webpack_require__.d(__webpack_exports__, { + Tv: () => (ParentSpan) +}, { + DW: DisablePropagation, + EW: MinimumTraceLevel, + RL: TracerKey, + WG: ParentSpanKey, + pX: CurrentTraceLevel, + sh: Tracer +}); + + +}, +"./node_modules/effect/dist/Utils.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Yields its wrapped value exactly once through an `IterableIterator`. + * + * **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 `{ value: self, done: false }`. Every + * subsequent call returns `{ value: a, done: true }` where `a` is the argument + * passed to `next()`. `[Symbol.iterator]()` returns a **new** `SingleShotGen` + * wrapping the same value, so the outer type can be iterated multiple times. + * + * **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", done: false } + * + * gen.next(42) // => { value: 42, done: true } + * ``` + * + * @see {@link Gen} for the type-level signature that relies on `SingleShotGen` + * @category constructors + * @since 2.0.0 + */ +class SingleShotGen { + called = false; + self; + constructor(self) { + this.self = self; + } + /** + * 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) { + return this.called ? { + value: a, + done: true + } : (this.called = true, { + value: this.self, + done: false + }); + } + /** + * Creates a fresh single-shot iterator over the stored value. + * + * **When to use** + * + * Use to iterate the wrapped value again without reusing the consumed + * iterator state. + * + * @since 2.0.0 + */ + [Symbol.iterator]() { + return new SingleShotGen(this.self); + } +} +// the probe is wrapped in a single function call (rather than module-level +// statements) so the whole selection is pure-annotated by the build and +// tree-shakable when `internalCall` is unused. +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { + [InternalTypeId]: body => { + return body(); + } + }; + const forced = { + [InternalTypeId]: body => { + try { + return body(); + } finally { + // + } + } + }; + const isNotOptimizedAway = standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true; + return isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/pickInternalCall(); +//# sourceMappingURL=Utils.js.map +__webpack_require__.d(__webpack_exports__, { + B: () => (SingleShotGen) +}, { + s: internalCall +}); + + +}, +"./node_modules/effect/dist/internal/array.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * @since 2.0.0 + */ +/** @internal */ +const isArrayNonEmpty = self => self.length > 0; +//# sourceMappingURL=array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + C: isArrayNonEmpty +}); + + +}, +"./node_modules/effect/dist/internal/core.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Utils_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _record_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); + + + + + + + + + +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_, + _R: _Function_js__rspack_import_0/* .identity */.D_ +}; +/** @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 (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + }, + toJSON() { + return { + ...this + }; + }, + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } +}; +/** @internal */ +const StructuralProto = { + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .structureKeys */.uN(this, Object.keys(this)); + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + const selfKeys = Object.keys(this); + const thatKeys = Object.keys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (let i = 0; i < selfKeys.length; i++) { + if (selfKeys[i] !== thatKeys[i] || !_Equal_js__rspack_import_5/* .equals */.aI(this[selfKeys[i]], that[selfKeys[i]])) { + return false; + } + } + return true; + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new _Utils_js__rspack_import_6/* .SingleShotGen */.B(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ...(args in this ? { + args: this[args] + } : undefined) + }; + } +}; +/** @internal */ +const isEffect = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, EffectTypeId); +/** @internal */ +const isExit = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, ExitTypeId); +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseTypeId); +/** @internal */ +const isCauseReason = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseReasonTypeId); +/** @internal */ +class CauseImpl { + [CauseTypeId]; + reasons; + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toJSON() { + return { + _id: "Cause", + failures: this.reasons.map(f => f.toJSON()) + }; + } + toString() { + return `Cause(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.reasons)})`; + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => _Equal_js__rspack_import_5/* .equals */.aI(e, that.reasons[i])); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .array */.YO(this.reasons); + } +} +const annotationsMap = /*#__PURE__*/new WeakMap(); +/** @internal */ +class ReasonBase { + [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); + }); + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this); + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toString(); + } +} +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/new Map(); +/** @internal */ +class Fail extends ReasonBase { + error; + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isFailReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.error, that.error) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.error))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeFromReasons = reasons => new CauseImpl(reasons); +/** @internal */ +const causeEmpty = /*#__PURE__*/new CauseImpl([]); +/** @internal */ +const causeFail = error => new CauseImpl([new Fail(error)]); +/** @internal */ +class Die extends ReasonBase { + defect; + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isDieReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.defect, that.defect) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.defect))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeDie = defect => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(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[evaluate] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = options => { + const Proto = makePrimitiveProto(options); + return function () { + const self = Object.create(Proto); + self[args] = options.single === false ? arguments : arguments[0]; + return self; + }; +}; +/** @internal */ +const makeExit = options => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isExit(that) && that._tag === this._tag && _Equal_js__rspack_import_5/* .equals */.aI(this[args], that[args]); + }, + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(options.op), _Hash_js__rspack_import_4/* .hash */.tW(this[args])); + } + }; + return function (value) { + const self = Object.create(Proto); + self[args] = value; + return self; + }; +}; +/** @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.currentStackFrame) { + cause = causeAnnotate(cause, { + mapUnsafe: new Map([[StackTraceKey.key, fiber.currentStackFrame]]) + }); + annotated = true; + } + let cont = fiber.getCont(contE); + while (fiber.interruptible && fiber._interruptedCause && cont) { + cont = fiber.getCont(contE); + } + return cont ? cont[contE](cause, fiber, annotated ? undefined : 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 = /*#__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 + } : undefined); + if (args) { + _record_js__rspack_import_8/* .assignProperties */.z(this, args); + // @effect-diagnostics-next-line floatingEffect:off + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = tag => { + class Base extends Error { + _tag = tag; + } + ; + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const NoSuchElementErrorTypeId = "~effect/Cause/NoSuchElementError"; +/** @internal */ +const isNoSuchElementError = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, NoSuchElementErrorTypeId); +/** @internal */ +class NoSuchElementError extends /*#__PURE__*/TaggedError("NoSuchElementError") { + [NoSuchElementErrorTypeId] = NoSuchElementErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, DoneTypeId); +const DoneVoid = { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value: undefined +}; +/** @internal */ +const Done = value => { + if (value === undefined) return DoneVoid; + return { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value + }; +}; +const doneVoid = /*#__PURE__*/exitFail(DoneVoid); +/** @internal */ +const done = value => { + if (value === undefined) return doneVoid; + return exitFail(Done(value)); +}; +//# sourceMappingURL=core.js.map +__webpack_require__.d(__webpack_exports__, { + ET: () => (ReasonBase), + Xm: () => (NoSuchElementError), + dM: () => (Fail), + s0: () => (CauseImpl) +}, { + $L: isDone, + $n: EffectTypeId, + Aj: isCause, + B4: CauseReasonTypeId, + DH: causeEmpty, + Eh: causeAnnotate, + GN: Yield, + IH: ExitTypeId, + In: StructuralProto, + Iu: causeDie, + OE: causeFail, + PW: isNoSuchElementError, + PX: CauseTypeId, + QJ: InterruptorStackTrace, + R6: withFiber, + RS: Done, + Rk: exitFail, + Sc: contE, + Uf: makePrimitive, + V2: exitDie, + Vw: done, + Wg: isCauseReason, + Xb: isDieReason, + _3: evaluate, + a2: args, + b5: causeFromReasons, + b9: isExit, + cb: exitFailCause, + dO: constEmptyAnnotations, + ee: contA, + fU: PipeInspectableProto, + ik: isInterruptReason, + lC: isFailReason, + qB: NoSuchElementErrorTypeId, + q_: DoneTypeId, + rN: TaggedError, + u4: contAll, + xt: exitSucceed, + yj: makePrimitiveProto, + yw: isEffect, + z8: StackTraceKey +}); + + +}, +"./node_modules/effect/dist/internal/doNotation.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); + +/** @internal */ +const let_ = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => map(self, a => ({ + ...a, + [name]: f(a) +}))); +/** @internal */ +const bindTo = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, name) => map(self, a => ({ + [name]: a +}))); +/** @internal */ +const bind = (map, flatMap) => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => flatMap(self, a => map(f(a), b => ({ + ...a, + [name]: b +})))); +//# sourceMappingURL=doNotation.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Jr: bindTo, + oI: bind, + zM: let_ +}); + + +}, +"./node_modules/effect/dist/internal/effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_20 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Equal_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Filter_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Filter.js"); +/* import */ var _Formatter_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_25 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Iterable_js__rspack_import_23 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Option_js__rspack_import_17 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Order_js__rspack_import_24 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Pipeable_js__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/* import */ var _Scheduler_js__rspack_import_13 = __webpack_require__("./node_modules/effect/dist/Scheduler.js"); +/* import */ var _Tracer_js__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Tracer.js"); +/* import */ var _Utils_js__rspack_import_18 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _doNotation_js__rspack_import_22 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _metric_js__rspack_import_16 = __webpack_require__("./node_modules/effect/dist/internal/metric.js"); +/* import */ var _record_js__rspack_import_21 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _references_js__rspack_import_15 = __webpack_require__("./node_modules/effect/dist/internal/references.js"); +/* import */ var _stackTraceLimit_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/stackTraceLimit.js"); +/* import */ var _tracer_js__rspack_import_19 = __webpack_require__("./node_modules/effect/dist/internal/tracer.js"); + + + + + + + + + + + + + + + + + + + + + + + + + + +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +class Interrupt extends _core_js__rspack_import_0/* .ReasonBase */.ET { + fiberId; + constructor(fiberId, annotations = _core_js__rspack_import_0/* .constEmptyAnnotations */.dO) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [_Equal_js__rspack_import_1/* .symbol */.HR](that) { + return (0,_core_js__rspack_import_0/* .isInterruptReason */.ik)(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [_Hash_js__rspack_import_2/* .symbol */.HR]() { + return _Hash_js__rspack_import_2/* .combine */.kg(_Hash_js__rspack_import_2/* .string */.Yj(`${this._tag}:${this.fiberId}`))(_Hash_js__rspack_import_2/* .random */.yT(this.annotations)); + } +} +/** @internal */ +const makeInterruptReason = fiberId => new Interrupt(fiberId); +/** @internal */ +const causeInterrupt = fiberId => new _core_js__rspack_import_0/* .CauseImpl */.s0([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = self => self.reasons.some(_core_js__rspack_import_0/* .isFailReason */.lC); +/** @internal */ +const findFail = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findError = self => { + for (let i = 0; i < self.reasons.length; i++) { + const reason = self.reasons[i]; + if (reason._tag === "Fail") { + return _Result_js__rspack_import_3/* .succeed */.Py(reason.error); + } + } + return _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findErrorOption = /*#__PURE__*/_Filter_js__rspack_import_4/* .toOption */.zL(findError); +/** @internal */ +const hasDies = self => self.reasons.some(_core_js__rspack_import_0/* .isDieReason */.Xb); +/** @internal */ +const findDie = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findDefect = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason.defect) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const hasInterrupts = self => self.reasons.some(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const findInterrupt = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isInterruptReason */.ik); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeFilterInterruptors = self => { + let interruptors; + for (let i = 0; i < self.reasons.length; i++) { + const f = self.reasons[i]; + if (f._tag !== "Interrupt") continue; + interruptors ??= new Set(); + if (f.fiberId !== undefined) { + interruptors.add(f.fiberId); + } + } + return interruptors ? _Result_js__rspack_import_3/* .succeed */.Py(interruptors) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeInterruptors = self => { + const result = causeFilterInterruptors(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? emptySet : result.success; +}; +const emptySet = /*#__PURE__*/new Set(); +/** @internal */ +const hasInterruptsOnly = self => self.reasons.length > 0 && self.reasons.every(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const reasonAnnotations = self => _Context_js__rspack_import_5/* .makeUnsafe */.LZ(self.annotations); +/** @internal */ +const causeAnnotations = self => { + const map = new Map(); + for (const f of self.reasons) { + if (f.annotations.size > 0) { + for (const [key, value] of f.annotations) { + map.set(key, value); + } + } + } + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(map); +}; +/** @internal */ +const causeCombine = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, that) => { + if (self.reasons.length === 0) { + return that; + } else if (that.reasons.length === 0) { + return self; + } + const newCause = new _core_js__rspack_import_0/* .CauseImpl */.s0(_Array_js__rspack_import_7/* .union */.KC(self.reasons, that.reasons)); + return _Equal_js__rspack_import_1/* .equals */.aI(self, newCause) ? self : newCause; +}); +/** @internal */ +const causeMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + let hasFail = false; + const failures = self.reasons.map(failure => { + if ((0,_core_js__rspack_import_0/* .isFailReason */.lC)(failure)) { + hasFail = true; + return new _core_js__rspack_import_0/* .Fail */.dM(f(failure.error), failure.annotations); + } + return failure; + }); + return hasFail ? (0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures) : self; +}); +/** @internal */ +const causePartition = self => { + const obj = { + Fail: [], + Die: [], + Interrupt: [] + }; + for (let i = 0; i < self.reasons.length; i++) { + obj[self.reasons[i]._tag].push(self.reasons[i]); + } + return obj; +}; +/** @internal */ +const causeSquash = self => { + const partitioned = causePartition(self); + if (partitioned.Fail.length > 0) { + return partitioned.Fail[0].error; + } else if (partitioned.Die.length > 0) { + return partitioned.Die[0].defect; + } else if (partitioned.Interrupt.length > 0) { + return new globalThis.Error("All fibers interrupted without error"); + } + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const causePrettyErrors = (self, options) => { + const errors = []; + const interrupts = []; + if (self.reasons.length === 0) return errors; + const prevStackLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(1); + for (const failure of self.reasons) { + if (failure._tag === "Interrupt") { + interrupts.push(failure); + continue; + } + errors.push(causePrettyError(failure._tag === "Die" ? failure.defect : failure.error, failure.annotations, options)); + } + if (errors.length === 0) { + const cause = new Error("The fiber was interrupted by:"); + cause.name = "InterruptCause"; + cause.stack = interruptCauseStack(cause, interrupts); + const error = new globalThis.Error("All fibers interrupted without error", { + cause + }); + error.name = "InterruptError"; + error.stack = `${error.name}: ${error.message}`; + errors.push(causePrettyError(error, interrupts[0].annotations, options)); + } + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevStackLimit); + return errors; +}; +/** @internal */ +const causePrettyError = (original, annotations, options) => { + const kind = typeof original; + let error; + if (original && kind === "object") { + error = new globalThis.Error(causePrettyMessage(original), { + cause: original.cause ? causePrettyError(original.cause) : undefined + }); + if (typeof original.name === "string") { + error.name = original.name; + } + if (typeof original.stack === "string") { + error.stack = cleanErrorStack(original.stack, error, annotations); + } else { + const stack = `${error.name}: ${error.message}`; + error.stack = annotations ? addStackAnnotations(stack, annotations) : stack; + } + if (options?.includeCauseInStack) { + error.stack = renderPrettyError(error); + } + for (const key of Object.keys(original)) { + if (!(key in error)) { + ; + error[key] = original[key]; + } + } + } else { + error = new globalThis.Error(!original ? `Unknown error: ${original}` : kind === "string" ? original : (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(original)); + } + return error; +}; +const causePrettyMessage = u => { + if (typeof u.message === "string") { + return u.message; + } else if (typeof u.toString === "function" && u.toString !== Object.prototype.toString && u.toString !== Array.prototype.toString) { + try { + return u.toString(); + } catch { + // something's off, rollback to json + } + } + return (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(u); +}; +const locationRegExp = /\((.*)\)/g; +const cleanErrorStack = (stack, error, annotations) => { + const message = `${error.name}: ${error.message}`; + const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split("\n"); + const out = [message]; + for (let i = 1; i < lines.length; i++) { + if (/(?:Generator\.next|~effect\/Effect)/.test(lines[i])) { + break; + } + out.push(lines[i]); + } + return annotations ? addStackAnnotations(out.join("\n"), annotations) : out.join("\n"); +}; +const addStackAnnotations = (stack, annotations) => { + const frame = annotations?.get(_core_js__rspack_import_0/* .StackTraceKey.key */.z8.key); + if (frame) { + stack = `${stack}\n${currentStackTrace(frame)}`; + } + return stack; +}; +const interruptCauseStack = (error, interrupts) => { + const out = [`${error.name}: ${error.message}`]; + for (const current of interrupts) { + const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : "unknown"; + const frame = current.annotations.get(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key); + out.push(` at fiber (${fiberId})`); + if (frame) out.push(currentStackTrace(frame)); + } + return out.join("\n"); +}; +const currentStackTrace = frame => { + const out = []; + let current = frame; + let i = 0; + while (current && i < 10) { + const stack = current.stack(); + if (stack) { + const locationMatchAll = stack.matchAll(locationRegExp); + let match = false; + for (const [, location] of locationMatchAll) { + match = true; + out.push(` at ${current.name} (${location})`); + } + if (!match) { + out.push(` at ${current.name} (${stack.replace(/^at /, "")})`); + } + } else { + out.push(` at ${current.name}`); + } + current = current.parent; + i++; + } + return out.join("\n"); +}; +/** @internal */ +const causePretty = cause => causePrettyErrors(cause).map(renderPrettyError).join("\n"); +const renderPrettyError = e => e.cause ? `${e.stack} {\n${renderErrorCause(e.cause, " ")}\n}` : e.stack; +const renderErrorCause = (cause, prefix) => { + const lines = cause.stack.split("\n"); + let stack = `${prefix}[cause]: ${lines[0]}`; + for (let i = 1, len = lines.length; i < len; i++) { + stack += `\n${prefix}${lines[i]}`; + } + if (cause.cause) { + stack += ` {\n${renderErrorCause(cause.cause, `${prefix} `)}\n${prefix}}`; + } + return stack; +}; +// ---------------------------------------------------------------------------- +// Fiber +// ---------------------------------------------------------------------------- +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: _Function_js__rspack_import_6/* .identity */.D_, + _E: _Function_js__rspack_import_6/* .identity */.D_ +}; +const fiberIdStore = { + id: 0 +}; +/** @internal */ +const getCurrentFiber = () => globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; +/** @internal */ +class FiberImpl { + constructor(context, interruptible = true) { + this[FiberTypeId] = fiberVariance; + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = []; + this._exit = undefined; + this._children = undefined; + this._interruptedCause = undefined; + this._yielded = undefined; + this._running = false; + this._deferredInterrupt = false; + this.runtimeMetrics?.recordFiberStart(this.context); + } + [FiberTypeId]; + id; + interruptible; + currentOpCount; + _stack; + _observers; + _exit; + _children; + _interruptedCause; + _yielded; + _running; + _deferredInterrupt; + // set in setContext + context; + currentScheduler; + currentTracerContext; + currentSpan; + currentLogLevel; + minimumLogLevel; + currentStackFrame; + runtimeMetrics; + maxOpsBeforeYield; + currentPreventYield; + _dispatcher = undefined; + get currentDispatcher() { + return this._dispatcher ??= this.currentScheduler.makeDispatcher(); + } + getRef(ref) { + return _Context_js__rspack_import_5/* .get */.Jt(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return _Function_js__rspack_import_6/* .constVoid */.Yi; + } + this._observers.push(cb); + return () => { + if (this._exit) 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.currentStackFrame) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, _Context_js__rspack_import_5/* .make */.L8(_core_js__rspack_import_0/* .StackTraceKey */.z8, this.currentStackFrame)); + } + if (annotations) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, annotations); + } + this._interruptedCause = this._interruptedCause ? causeCombine(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._yielded !== undefined) { + const yielded = this._yielded; + this._yielded = undefined; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === _core_js__rspack_import_0/* .Yield */.GN) { + return; + } + // the interruptChildren middleware is added in Effect.forkChild, so it can be + // tree-shaken if not used + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== undefined) { + return this.evaluate(flatMap(interruptChildren, () => exit)); + } + this._exit = exit; + this.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + for (let i = 0; i < this._observers.length; i++) { + this._observers[i](exit); + } + this._observers.length = 0; + this._stack.length = 0; + this._children = undefined; + this.context = _Context_js__rspack_import_5/* .empty */.Ie(); + } + runLoop(effect) { + const prevFiber = globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + if (!yielding && !this.currentPreventYield && this.currentScheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = this.currentTracerContext ? this.currentTracerContext(current, this) : current[_core_js__rspack_import_0/* .evaluate */._3](this); + if (current === _core_js__rspack_import_0/* .Yield */.GN) { + const yielded = this._yielded; + if (_core_js__rspack_import_0/* .ExitTypeId */.IH in yielded) { + this._deferredInterrupt = false; + this._yielded = undefined; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = undefined; + yielded(); + continue; + } + return _core_js__rspack_import_0/* .Yield */.GN; + } + } + } catch (error) { + if (!(0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(current, _core_js__rspack_import_0/* .evaluate */._3)) { + return (0,_core_js__rspack_import_0/* .exitDie */.V2)(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + } + return this.runLoop((0,_core_js__rspack_import_0/* .exitDie */.V2)(error)); + } finally { + this._running = prevRunning; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return undefined; + const cont = op[_core_js__rspack_import_0/* .contAll */.u4] && op[_core_js__rspack_import_0/* .contAll */.u4](this); + if (cont) { + ; + cont[symbol] = cont; + return cont; + } + if (op[symbol]) return op; + } + } + yieldWith(value) { + this._yielded = value; + return _core_js__rspack_import_0/* .Yield */.GN; + } + children() { + return this._children ??= new Set(); + } + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + // Every key cached below opts in to Context caching, so contexts related + // only by non-caching adds cannot have changed any of them + if (previous !== undefined && _Context_js__rspack_import_5/* .hasSameCache */.Pf(previous, context)) return; + const scheduler = this.getRef(_Scheduler_js__rspack_import_13/* .Scheduler */._F); + if (scheduler !== this.currentScheduler) { + this.currentScheduler = scheduler; + this._dispatcher = undefined; + } + // The string-keyed lookups keep the Tracer key values (and the native + // tracer behind Tracer.Tracer's default) out of every bundle + this.currentSpan = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .ParentSpanKey */.WG); + this.currentLogLevel = this.getRef(_references_js__rspack_import_15/* .CurrentLogLevel */.Gl); + this.minimumLogLevel = this.getRef(_references_js__rspack_import_15/* .MinimumLogLevel */.zQ); + this.currentStackFrame = this.getRef(_references_js__rspack_import_15/* .CurrentStackFrame */.vA); + this.maxOpsBeforeYield = this.getRef(_Scheduler_js__rspack_import_13/* .MaxOpsBeforeYield */.Zm); + this.currentPreventYield = this.getRef(_Scheduler_js__rspack_import_13/* .PreventSchedulerYield */.hf); + this.runtimeMetrics = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _metric_js__rspack_import_16/* .FiberRuntimeMetricsKey */.F); + const currentTracer = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .TracerKey */.RL); + this.currentTracerContext = currentTracer ? currentTracer["context"] : undefined; + } + get currentSpanLocal() { + return this.currentSpan?._tag === "Span" ? this.currentSpan : undefined; + } +} +const deferredInterruptCont = { + [_core_js__rspack_import_0/* .contA */.ee](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [_core_js__rspack_import_0/* .contE */.Sc](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const fiberMiddleware = { + interruptChildren: undefined +}; +const fiberStackAnnotations = fiber => { + if (!fiber.currentStackFrame) return undefined; + const annotations = new Map(); + annotations.set(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key, fiber.currentStackFrame); + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(annotations); +}; +const fiberInterruptChildren = fiber => { + if (fiber._children === undefined || fiber._children.size === 0) { + return undefined; + } + return fiberInterruptAll(fiber._children); +}; +/** @internal */ +const fiberAwait = self => { + const impl = self; + if (impl._exit) return succeed(impl._exit); + return callback(resume => { + if (impl._exit) return resume(succeed(impl._exit)); + return sync(self.addObserver(exit => resume(succeed(exit)))); + }); +}; +/** @internal */ +const fiberAwaitAll = self => callback(resume => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = undefined; + 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 fiberJoinAll = self => callback(resume => { + const fibers = Array.from(self); + if (fibers.length === 0) return resume(succeed(_Array_js__rspack_import_7/* .empty */.Ie())); + const out = new Array(fibers.length); + const cancels = _Array_js__rspack_import_7/* .empty */.Ie(); + let done = 0; + let failed = false; + for (let i = 0; i < fibers.length; i++) { + if (failed) break; + cancels.push(fibers[i].addObserver(exit => { + done++; + if (exit._tag === "Failure") { + failed = true; + cancels.forEach(cancel => cancel()); + return resume(exit); + } + out[i] = exit.value; + if (done === fibers.length) { + resume(succeed(out)); + } + })); + } + return sync(() => { + failed = true; + cancels.forEach(cancel => cancel()); + }); +}); +/** @internal */ +const fiberInterrupt = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fiberInterruptAs(self, fiber.id)); +/** @internal */ +const fiberInterruptAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(args[0], FiberTypeId), (self, fiberId, annotations) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + let ann = fiberStackAnnotations(parent); + ann = ann && annotations ? _Context_js__rspack_import_5/* .merge */.h1(ann, annotations) : ann ?? annotations; + self.interruptUnsafe(fiberId, ann); + return asVoid(fiberAwait(self)); +})); +/** @internal */ +const fiberInterruptAll = fibers => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const fiberInterruptAllAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (fibers, fiberId) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + const fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(fiberId, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +})); +/** @internal */ +const succeed = _core_js__rspack_import_0/* .exitSucceed */.xt; +/** @internal */ +const failCause = _core_js__rspack_import_0/* .exitFailCause */.cb; +/** @internal */ +const fail = _core_js__rspack_import_0/* .exitFail */.Rk; +/** @internal */ +const sync = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Sync", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const value = this[_core_js__rspack_import_0/* .args */.a2](); + const cont = fiber.getCont(_core_js__rspack_import_0/* .contA */.ee); + return cont ? cont[_core_js__rspack_import_0/* .contA */.ee](value, fiber) : fiber.yieldWith((0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Suspend", + [_core_js__rspack_import_0/* .evaluate */._3](_fiber) { + return this[_core_js__rspack_import_0/* .args */.a2](); + } +}); +/** @internal */ +const fromOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => args.length >= 2 || _Option_js__rspack_import_17.isOption(args[0]), (option, onNone) => _Option_js__rspack_import_17.isNone(option) ? fail(onNone ? onNone() : new _core_js__rspack_import_0/* .NoSuchElementError */.Xm("Effect.fromOption: Option.none")) : succeed(option.value)); +/** @internal */ +const fromResult = /*#__PURE__*/_Result_js__rspack_import_3/* .match */.YW({ + onFailure: fail, + onSuccess: succeed +}); +/** @internal */ +const fromNullishOr = value => value == null ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(value); +/** @internal */ +const yieldNowWith = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Yield", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this[_core_js__rspack_import_0/* .args */.a2] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/yieldNowWith(0); +/** @internal */ +const succeedSome = a => succeed(_Option_js__rspack_import_17.some(a)); +/** @internal */ +const succeedNone = /*#__PURE__*/succeed(/*#__PURE__*/_Option_js__rspack_import_17.none()); +/** @internal */ +const transposeOption = self => _Option_js__rspack_import_17.isNone(self) ? succeedNone : map(self.value, _Option_js__rspack_import_17.some); +/** @internal */ +const failCauseSync = evaluate => suspend(() => failCause((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate))); +/** @internal */ +const die = defect => (0,_core_js__rspack_import_0/* .exitDie */.V2)(defect); +/** @internal */ +const failSync = error => suspend(() => fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(error))); +/** @internal */ +const void_ = /*#__PURE__*/succeed(void 0); +/** @internal */ + +/** @internal */ +const try_ = options => { + const evaluate = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.try") : options.catch; + return suspend(() => { + try { + return succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate)); + } catch (err) { + return fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(err))); + } + }); +}; +/** @internal */ + +/** @internal */ +const promise = evaluate => callbackOptions(function (resume, signal) { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(signal)).then(a => resume(succeed(a)), e => resume(die(e))); +}, evaluate.length !== 0); +/** @internal */ +const tryPromise = options => { + const f = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.tryPromise") : options.catch; + return callbackOptions(function (resume, signal) { + const failWithCatch = cause => { + try { + resume(fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(cause)))); + } catch (err) { + resume(die(err)); + } + }; + try { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(signal)).then(a => resume(succeed(a)), failWithCatch); + } catch (err) { + failWithCatch(err); + } + }, f.length !== 0); +}; +/** @internal */ +const withFiberId = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.id)); +/** @internal */ +const fiber = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(succeed); +/** @internal */ +const fiberId = /*#__PURE__*/withFiberId(succeed); +const callbackOptions = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Async", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const register = (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => this[_core_js__rspack_import_0/* .args */.a2][0].bind(fiber.currentScheduler)); + let resumed = false; + let yielded = false; + const controller = this[_core_js__rspack_import_0/* .args */.a2][1] ? new AbortController() : undefined; + const onCancel = register(effect => { + if (resumed) return; + resumed = true; + if (yielded) { + fiber.evaluate(effect); + } else { + yielded = effect; + } + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber._yielded = () => { + resumed = true; + }; + if (controller === undefined && onCancel === undefined) { + return _core_js__rspack_import_0/* .Yield */.GN; + } + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return _core_js__rspack_import_0/* .Yield */.GN; + } +}); +const asyncFinalizer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "AsyncFinalizer", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(this[_core_js__rspack_import_0/* .args */.a2](), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = register => callbackOptions(register, register.length >= 2); +/** @internal */ +const never = /*#__PURE__*/callback(_Function_js__rspack_import_6/* .constVoid */.Yi); +/** @internal */ +const gen = (...args) => suspend(() => fromIteratorUnsafe(args.length === 1 ? args[0]() : args[1].call(args[0].self))); +/** @internal */ +const fnUntraced = (body, ...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 fnStackCleaner = /*#__PURE__*/(0,_tracer_js__rspack_import_19/* .makeStackCleaner */.R)(2); +/** @internal */ +const fn = function () { + const nameFirst = typeof arguments[0] === "string"; + const name = nameFirst ? arguments[0] : "Effect.fn"; + const spanOptions = nameFirst ? arguments[1] : undefined; + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const defError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + if (nameFirst) { + return (body, ...pipeables) => makeFn(name, body, defError, pipeables, nameFirst, spanOptions); + } + return makeFn(name, arguments[0], defError, Array.prototype.slice.call(arguments, 1), nameFirst, spanOptions); +}; +const makeFn = (name, bodyOrOptions, defError, pipeables, addSpan, spanOptions) => { + const body = typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); + return defineFunctionLength(body.length, function (...args) { + let result = suspend(() => { + const iter = body.apply(this, arguments); + return (0,_core_js__rspack_import_0/* .isEffect */.yw)(iter) ? iter : fromIteratorUnsafe(iter); + }); + for (let i = 0; i < pipeables.length; i++) { + result = pipeables[i](result, ...args); + } + if (!(0,_core_js__rspack_import_0/* .isEffect */.yw)(result)) { + return result; + } + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const callError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + return updateService(addSpan ? useSpan(name, spanOptions, span => provideParentSpan(result, span)) : result, _references_js__rspack_import_15/* .CurrentStackFrame */.vA, prev => ({ + name, + stack: fnStackCleaner(() => callError.stack), + parent: { + name: `${name} (definition)`, + stack: fnStackCleaner(() => defError.stack), + parent: prev + } + })); + }); +}; +/** @internal */ +const fnUntracedEager = (body, ...pipeables) => defineFunctionLength(body.length, pipeables.length === 0 ? function () { + return fromIteratorEagerUnsafe(() => body.apply(this, arguments)); +} : function () { + let effect = fromIteratorEagerUnsafe(() => body.apply(this, arguments)); + for (const pipeable of pipeables) { + effect = pipeable(effect); + } + return effect; +}); +const fromIteratorEagerUnsafe = evaluate => { + try { + const iterator = evaluate(); + let value = undefined; + // Try to resolve synchronously in a loop + while (true) { + const state = iterator.next(value); + if (state.done) { + return succeed(state.value); + } + const primitive = state.value; + if (primitive && primitive._tag === "Success") { + value = primitive.value; + continue; + } else if (primitive && primitive._tag === "Failure") { + return state.value; + } else { + let isFirstExecution = true; + return suspend(() => { + if (isFirstExecution) { + isFirstExecution = false; + return flatMap(state.value, value => fromIteratorUnsafe(iterator, value)); + } else { + return suspend(() => fromIteratorUnsafe(evaluate())); + } + }); + } + } + } catch (error) { + return die(error); + } +}; +const fromIteratorUnsafe = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Iterator", + single: false, + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + const iter = this[_core_js__rspack_import_0/* .args */.a2][0]; + 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; + } + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + return this[_core_js__rspack_import_0/* .contA */.ee](this[_core_js__rspack_import_0/* .args */.a2][1], fiber); + } +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, value) => { + const b = succeed(value); + return flatMap(self, _ => b); +}); +/** @internal */ +const asSome = self => map(self, _Option_js__rspack_import_17.some); +/** @internal */ +const flip = self => matchEffect(self, { + onFailure: succeed, + onSuccess: fail +}); +/** @internal */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => (0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)))); +/** @internal */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => as((0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)), a))); +/** @internal */ +const asVoid = self => flatMap(self, _ => exitVoid); +/** @internal */ +const sandbox = self => catchCause(self, fail); +/** @internal */ +const raceAll = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + const effects = _Array_js__rspack_import_7/* .fromIterable */.Ts(all); + const len = effects.length; + let doneCount = 0; + let done = false; + const fibers = new Set(); + const failures = []; + const onExit = (exit, fiber, i) => { + doneCount++; + if (exit._tag === "Failure") { + failures.push(...exit.cause.reasons); + if (doneCount >= len) { + resume(failCause((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures))); + } + return; + } + const isWinner = !done; + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index: i, + parentFiber: parent + }); + } + }; + for (let i = 0; i < len; i++) { + const fiber = forkUnsafe(parent, effects[i], true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + onExit(exit, fiber, i); + }); + if (done) break; + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const raceAllFirst = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + let done = false; + const fibers = new Set(); + const onExit = exit => { + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + }; + let i = 0; + for (const effect of all) { + if (done) break; + const index = i++; + const fiber = forkUnsafe(parent, effect, true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + const isWinner = !done; + onExit(exit); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index, + parentFiber: parent + }); + } + }); + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const race = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAll([self, that], options)); +/** @internal */ +const raceFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAllFirst([self, that], options)); +/** @internal */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onSuccess = Object.create(OnSuccessProto); + onSuccess[_core_js__rspack_import_0/* .args */.a2] = self; + onSuccess[_core_js__rspack_import_0/* .contA */.ee] = f.length !== 1 ? a => f(a) : f; + return onSuccess; +}); +const OnSuccessProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccess", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCauseEffectEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? options.onSuccess(self.value) : options.onFailure(self.cause); + } + return matchCauseEffect(self, options); +}); +/** @internal */ +const effectIsExit = effect => _core_js__rspack_import_0/* .ExitTypeId */.IH in effect; +/** @internal */ +const flatMapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? f(self.value) : self; + } + return flatMap(self, f); +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const flatten = self => flatMap(self, _Function_js__rspack_import_6/* .identity */.D_); +/** @internal */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a))))); +/** @internal */ +const mapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMap(self, f) : map(self, f)); +/** @internal */ +const mapErrorEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMapError(self, f) : mapError(self, f)); +/** @internal */ +const mapBothEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => effectIsExit(self) ? exitMapBoth(self, options) : mapBoth(self, options)); +/** @internal */ +const catchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return f(error.success); + } + return catch_(self, f); +}); +// ---------------------------------------------------------------------------- +// Exit +// ---------------------------------------------------------------------------- +/** @internal */ +const exitInterrupt = fiberId => (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(causeInterrupt(fiberId)); +/** @internal */ +const exitIsSuccess = self => self._tag === "Success"; +/** @internal */ +const exitFilterSuccess = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterValue = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self.value) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitIsFailure = self => self._tag === "Failure"; +/** @internal */ +const exitFilterFailure = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterCause = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self.cause) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFindError = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findError); +/** @internal */ +const exitFindDefect = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findDefect); +/** @internal */ +const exitHasInterrupts = self => self._tag === "Failure" && hasInterrupts(self.cause); +/** @internal */ +const exitHasDies = self => self._tag === "Failure" && hasDies(self.cause); +/** @internal */ +const exitHasFails = self => self._tag === "Failure" && hasFails(self.cause); +/** @internal */ +const exitVoid = /*#__PURE__*/(0,_core_js__rspack_import_0/* .exitSucceed */.xt)(void 0); +/** @internal */ +const exitMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => self._tag === "Success" ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(f(self.value)) : self); +/** @internal */ +const exitMapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(f(error.success)); +}); +/** @internal */ +const exitMapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(options.onFailure(error.success)); +}); +/** @internal */ +const exitAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, b) => exitIsSuccess(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(b) : self); +/** @internal */ +const exitZipRight = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, that) => exitIsSuccess(self) ? that : self); +/** @internal */ +const exitMatch = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => exitIsSuccess(self) ? options.onSuccess(self.value) : options.onFailure(self.cause)); +/** @internal */ +const exitAsVoid = /*#__PURE__*/exitAs(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 : (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures)); +}; +/** @internal */ +const exitGetSuccess = self => exitIsSuccess(self) ? _Option_js__rspack_import_17.some(self.value) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitGetCause = self => exitIsFailure(self) ? _Option_js__rspack_import_17.some(self.cause) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitFindErrorOption = self => { + const error = exitFindError(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(error) ? _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(error.success); +}; +// ---------------------------------------------------------------------------- +// environment +// ---------------------------------------------------------------------------- +/** @internal */ +const service = service => service; +/** @internal */ +const serviceOption = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const serviceOptional = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fromOption(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const updateContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + return onExitPrimitive(self, () => { + fiber.setContext(prevContext); + return undefined; + }); +})); +/** @internal */ +const updateService = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, f) => updateContext(self, s => { + const prev = _Context_js__rspack_import_5/* .getUnsafe */.fp(s, service); + const next = f(prev); + if (prev === next) return s; + return _Context_js__rspack_import_5/* .add */.WQ(s, service, next); +})); +/** @internal */ +const updateServiceScoped = (service, update, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const original = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + const updated = update(original); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, updated)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + let next; + if (options?.reset === undefined) { + if (current !== updated) return void_; + next = original; + } else { + next = options.reset(original, updated, current); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, next)); + return void_; + }); +})); +/** @internal */ +const context = () => getContext; +const getContext = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.context)); +/** @internal */ +const contextWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.context)); +/** @internal */ +const setContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => updateContext(self, (0,_Function_js__rspack_import_6/* .constant */.dY)(context))); +/** @internal */ +const provideContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, _Context_js__rspack_import_5/* .merge */.h1(context)); +}); +/** @internal */ +const provideService = function () { + if (arguments.length === 1) { + return (0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + } + return (0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, _Context_js__rspack_import_5/* .add */.WQ(service, implementation)); +/** @internal */ +const provideServiceEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, acquire) => flatMap(acquire, implementation => provideService(self, service, implementation))); +// ---------------------------------------------------------------------------- +// zipping +// ---------------------------------------------------------------------------- +/** @internal */ +const zip = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => zipWith(self, that, (a, a2) => [a, a2], options)); +/** @internal */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, f, options) => options?.concurrent +// Use `all` exclusively for concurrent cases, as it introduces additional overhead due to the management of concurrency +? map(all([self, that], { + concurrency: 2 +}), ([a, a2]) => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))) : flatMap(self, a => map(that, a2 => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))))); +// ---------------------------------------------------------------------------- +// filtering & conditionals +// ---------------------------------------------------------------------------- +/* @internal */ +const filterOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, orFailWith) => filterOrElse(self, predicate, orFailWith ? a => fail(orFailWith(a)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const when = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, condition) => flatMap(condition, pass => pass ? asSome(self) : succeedNone)); +// ---------------------------------------------------------------------------- +// repetition +// ---------------------------------------------------------------------------- +/** @internal */ +const replicate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, n) => Array.from({ + length: n +}, () => self)); +/** @internal */ +const replicateEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, n, options) => all(replicate(self, n), options)); +/** @internal */ +const forever = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => whileLoop({ + while: _Function_js__rspack_import_6/* .constTrue */.ue, + body: (0,_Function_js__rspack_import_6/* .constant */.dY)(options?.disableYield ? self : flatMap(self, _ => yieldNow)), + step: _Function_js__rspack_import_6/* .constVoid */.Yi +})); +// ---------------------------------------------------------------------------- +// error handling +// ---------------------------------------------------------------------------- +/** @internal */ +const catchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onFailure = Object.create(OnFailureProto); + onFailure[_core_js__rspack_import_0/* .args */.a2] = self; + onFailure[_core_js__rspack_import_0/* .contE */.Sc] = f.length !== 1 ? cause => f(cause) : f; + return onFailure; +}); +const OnFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const catchCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCause(self, cause => { + if (!predicate(cause)) { + return failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)); +})); +/** @internal */ +const catchCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const eb = filter(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(eb) ? failCause(eb.failure) : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(eb.success, cause)); +})); +/** @internal */ +const catch_ = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findError, e => f(e))); +/** @internal */ +const catchNoSuchElement = self => matchEffect(self, { + onFailure: error => (0,_core_js__rspack_import_0/* .isNoSuchElementError */.PW)(error) ? succeedNone : fail(error), + onSuccess: succeedSome +}); +/** @internal */ +const catchDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findDefect, f)); +/** @internal */ +const tapCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCause(self, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCauseIf(self, predicate, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const result = filter(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return failCause(cause); + } + return andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success, cause)), failCause(cause)); +})); +/** @internal */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findError, e => f(e))); +/** @internal */ +const tapErrorTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, k, f) => { + const predicate = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return tapError(self, error => predicate(error) ? f(error) : void_); +}); +/** @internal */ +const tapDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findDefect, _ => f(_))); +/** @internal */ +const catchIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + if (!predicate(error.success)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(error.success)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(error.success)); +})); +/** @internal */ +const catchFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + const result = filter(error.success); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(result.failure)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success)); +})); +/** @internal */ +const catchTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return catchIf(self, pred, f, orElse); +}); +/** @internal */ +const catchTags = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, cases, orElse) => { + let keys; + return catchFilter(self, e => { + keys ??= Object.keys(cases); + return (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e["_tag"]) && keys.includes(e["_tag"]) ? _Result_js__rspack_import_3/* .succeed */.Py(e) : _Result_js__rspack_import_3/* .fail */.fJ(e); + }, e => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[e["_tag"]](e)), orElse); +}); +/** @internal */ +const catchReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, reasonTag, f, orElse) => catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason"), e => { + const reason = e.reason; + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(reason, reasonTag)) return f(reason, e); + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); +})); +/** @internal */ +const catchReasons = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, cases, orElse) => { + let keys; + return catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason") && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e.reason, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e.reason._tag), e => { + const reason = e.reason; + keys ??= Object.keys(cases); + if (keys.includes(reason._tag)) { + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[reason._tag](reason, e)); + } + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); + }); +}); +/** @internal */ +const unwrapReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, errorTag) => catchFilter(self, e => { + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason")) { + return _Result_js__rspack_import_3/* .succeed */.Py(e.reason); + } + return _Result_js__rspack_import_3/* .fail */.fJ(e); +}, fail)); +/** @internal */ +const mapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, error => failSync(() => f(error)))); +/* @internal */ +const mapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: e => failSync(() => options.onFailure(e)), + onSuccess: a => sync(() => options.onSuccess(a)) +})); +/** @internal */ +const orDie = self => catch_(self, die); +/** @internal */ +const orElseSucceed = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, _ => sync(f))); +/** @internal */ +const firstSuccessOf = effects => suspend(() => { + const iterator = effects[Symbol.iterator](); + let state = iterator.next(); + if (state.done) { + return die(new Error("Received an empty collection of effects")); + } + function loop(current) { + const next = iterator.next(); + if (next.done) return current.value; + return catch_(current.value, _ => loop(next)); + } + return loop(state); +}); +/** @internal */ +const eventually = self => catch_(self, _ => flatMap(yieldNow, () => eventually(self))); +/** @internal */ +const ignore = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure(cause) { + const failure = findFail(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + }, + onSuccess: _ => void_ + }); +}); +/** @internal */ +const ignoreCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: cause => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: _ => void_ + }); +}); +/** @internal */ +const option = self => match(self, { + onFailure: _Option_js__rspack_import_17.none, + onSuccess: _Option_js__rspack_import_17.some +}); +/** @internal */ +const result = self => matchEager(self, { + onFailure: _Result_js__rspack_import_3/* .fail */.fJ, + onSuccess: _Result_js__rspack_import_3/* .succeed */.Py +}); +// ---------------------------------------------------------------------------- +// pattern matching +// ---------------------------------------------------------------------------- +/** @internal */ +const matchCauseEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + const primitive = Object.create(OnSuccessAndFailureProto); + primitive[_core_js__rspack_import_0/* .args */.a2] = self; + primitive[_core_js__rspack_import_0/* .contA */.ee] = options.onSuccess.length !== 1 ? a => options.onSuccess(a) : options.onSuccess; + primitive[_core_js__rspack_import_0/* .contE */.Sc] = options.onFailure.length !== 1 ? cause => options.onFailure(cause) : options.onFailure; + return primitive; +}); +const OnSuccessAndFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccessAndFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => sync(() => options.onFailure(cause)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => { + const fail = cause.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return fail ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => options.onFailure(fail.error)) : failCause(cause); + }, + onSuccess: options.onSuccess +})); +/** @internal */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: error => sync(() => options.onFailure(error)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(error.success)); + } + return match(self, options); +}); +/** @internal */ +const matchCauseEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(self.cause)); + } + return matchCause(self, options); +}); +/** @internal */ +const exit = self => effectIsExit(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Exit", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause)); + } +}); +// ---------------------------------------------------------------------------- +// Condition checking +// ---------------------------------------------------------------------------- +/** @internal */ +const isFailure = /*#__PURE__*/matchEager({ + onFailure: () => true, + onSuccess: () => false +}); +/** @internal */ +const isSuccess = /*#__PURE__*/matchEager({ + onFailure: () => false, + onSuccess: () => true +}); +// ---------------------------------------------------------------------------- +// delays & timeouts +// ---------------------------------------------------------------------------- +/** @internal */ +const delay = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => andThen(sleep(duration), self)); +/** @internal */ +const timeoutOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => raceFirst(self, flatMap(sleep(options.duration), options.orElse))); +/** @internal */ +const timeout = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => timeoutOrElse(self, { + duration, + orElse: () => fail(new TimeoutError()) +})); +/** @internal */ +const timeoutOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => raceFirst(asSome(self), as(sleep(duration), _Option_js__rspack_import_17.none()))); +/** @internal */ +const timed = self => clockWith(clock => { + const start = clock.monotonicTimeNanosUnsafe(); + return map(self, a => [_Duration_js__rspack_import_20/* .nanos */.cF(clock.monotonicTimeNanosUnsafe() - start), a]); +}); +// ---------------------------------------------------------------------------- +// resources & finalization +// ---------------------------------------------------------------------------- +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => suspend(() => scopeCloseUnsafe(self, exit_) ?? void_); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + if (self.state._tag === "Closed") return; + const closed = { + _tag: "Closed", + exit: exit_ + }; + if (self.state._tag === "Empty") { + self.state = closed; + return; + } + const state = self.state; + self.state = closed; + if (state.finalizer !== undefined) { + return state.finalizer(exit_); + } + const finalizers = state.finalizers; + if (finalizers === undefined || finalizers.size === 0) { + return; + } else if (finalizers.size === 1) { + return finalizers.values().next().value(exit_); + } + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, cause => failCause(causeCombine(exit_.cause, cause))); +const scopeCloseFinalizers = /*#__PURE__*/fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers.values()); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const finalizer = arr[i]; + if (self.strategy === "sequential") { + exits.push(yield* exit(finalizer(exit_))); + } else { + fibers.push(forkUnsafe(parent, finalizer(exit_), true, true, "inherit")); + } + } + if (fibers.length > 0) { + exits = yield* fiberAwaitAll(fibers); + } + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeFork = (scope, finalizerStrategy) => sync(() => scopeForkUnsafe(scope, finalizerStrategy)); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const newScope = scopeMakeUnsafe(finalizerStrategy); + if (scope.state._tag === "Closed") { + newScope.state = scope.state; + return newScope; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, exit => scopeClose(newScope, exit)); + scopeAddFinalizerUnsafe(newScope, key, _ => sync(() => scopeRemoveFinalizerUnsafe(scope, key))); + return newScope; +}; +/** @internal */ +const scopeAddFinalizerExit = (scope, finalizer) => { + return suspend(() => { + if (scope.state._tag === "Closed") { + return finalizer(scope.state.exit); + } + scopeAddFinalizerUnsafe(scope, {}, finalizer); + return void_; + }); +}; +/** @internal */ +const scopeAddFinalizer = (scope, finalizer) => scopeAddFinalizerExit(scope, (0,_Function_js__rspack_import_6/* .constant */.dY)(finalizer)); +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") { + scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: undefined + }; + } else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== undefined) { + state.finalizers = new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = undefined; + state.finalizer = undefined; + state.finalizers.set(key, finalizer); + } else if (state.finalizers === undefined) { + state.finalizerKey = key; + state.finalizer = finalizer; + } else { + state.finalizers.set(key, finalizer); + } + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizerKey === key) { + state.finalizerKey = undefined; + state.finalizer = undefined; + } else if (state.finalizers !== undefined) { + state.finalizers.delete(key); + } + } +}; +/** @internal */ +const scopeFinalizerCountUnsafe = scope => scope.state._tag !== "Open" ? 0 : scope.state.finalizer !== undefined ? 1 : scope.state.finalizers?.size ?? 0; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy = "sequential") => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + state: constScopeEmpty +}); +const constScopeEmpty = { + _tag: "Empty" +}; +/** @internal */ +const scopeMake = finalizerStrategy => sync(() => scopeMakeUnsafe(finalizerStrategy)); +/** @internal */ +const scope = scopeTag; +/** @internal */ +const provideScope = /*#__PURE__*/provideService(scopeTag); +/** @internal */ +const scoped = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.context; + const scope = scopeMakeUnsafe(); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, scopeTag, scope)); + return onExitPrimitive(self, exit => { + fiber.setContext(prev); + return scopeCloseUnsafe(scope, exit); + }); +}); +/** @internal */ +const scopeUse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => onExit(provideScope(self, scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_))); +/** @internal */ +const scopedWith = f => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +/** @internal */ +const acquireRelease = (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)))))); +/** @internal */ +const addFinalizer = finalizer => flatMap(scope, scope => contextWith(context => scopeAddFinalizerExit(scope, exit => provideContext(finalizer(exit), context)))); +/** @internal */ +const onExitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "OnExit", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2][0]; + }, + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible && this[_core_js__rspack_import_0/* .args */.a2][2] !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(eff, _ => exit) : exit; + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(combineFinalizerCause(exit, eff), _ => exit) : exit; + } +}); +/** @internal */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, onExitPrimitive); +/** @internal */ +const ensuring = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onExit(self, _ => finalizer)); +/** @internal */ +const onExitIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExit(self, exit => { + if (!predicate(exit)) { + return void_; + } + return f(exit); +})); +/** @internal */ +const onExitFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + const b = filter(exit); + return _Result_js__rspack_import_3/* .isFailure */.N6(b) ? void_ : f(b.success, exit); +})); +/** @internal */ +const onError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => onExitFilter(self, exitFilterCause, f)); +/** @internal */ +const onErrorIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExitIf(self, exit => { + if (exit._tag !== "Failure") { + return false; + } + return predicate(exit.cause); +}, exit => f(exit.cause))); +/** @internal */ +const onErrorFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + if (exit._tag !== "Failure") { + return void_; + } + const result = filter(exit.cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? void_ : f(result.success, exit.cause); +})); +/** @internal */ +const onInterrupt = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onErrorFilter(causeFilterInterruptors, finalizer)(self)); +/** @internal */ +const acquireUseRelease = (acquire, use, release) => uninterruptibleMask(restore => flatMap(acquire, a => onExitPrimitive(restore(use(a)), exit => release(a, exit), true))); +/** @internal */ +const acquireDisposable = acquire => acquireRelease(acquire, resource => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(resource, Symbol.asyncDispose) ? promise(() => resource[Symbol.asyncDispose]()) : sync(() => resource[Symbol.dispose]())); +// ---------------------------------------------------------------------------- +// Caching +// ---------------------------------------------------------------------------- +/** @internal */ +const cachedInvalidateWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, ttl) => sync(() => { + const ttlMillis = _Duration_js__rspack_import_20/* .toMillis */.kE(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(ttl)); + const isFinite = Number.isFinite(ttlMillis); + const latch = makeLatchUnsafe(false); + let expiresAt = 0; + let running = false; + let exit; + const wait = flatMap(latch.await, () => exit); + return [(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const clock = fiber.getRef(ClockRef); + const now = isFinite ? clock.currentTimeMillisUnsafe() : 0; + if (running || now < expiresAt) return exit ?? wait; + running = true; + latch.closeUnsafe(); + exit = undefined; + return onExit(self, exit_ => sync(() => { + running = false; + expiresAt = clock.currentTimeMillisUnsafe() + ttlMillis; + exit = exit_; + latch.openUnsafe(); + })); + }), sync(() => { + expiresAt = 0; + latch.closeUnsafe(); + exit = undefined; + })]; +})); +/** @internal */ +const cachedWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, timeToLive) => map(cachedInvalidateWithTTL(self, timeToLive), tuple => tuple[0])); +/** @internal */ +const cached = self => cachedWithTTL(self, _Duration_js__rspack_import_20/* .infinity */.Tn); +// ---------------------------------------------------------------------------- +// interruption +// ---------------------------------------------------------------------------- +/** @internal */ +const interrupt = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => failCause(causeInterrupt(fiber.id))); +/** @internal */ +const uninterruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptible = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "SetInterruptible", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + fiber.interruptible = this[_core_js__rspack_import_0/* .args */.a2]; + 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); +}; +/** @internal */ +const interruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return self; + return setFiberInterruptible(fiber) ?? self; +}); +/** @internal */ +const uninterruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return f(interruptible); +}); +/** @internal */ +const interruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + const interrupted = setFiberInterruptible(fiber); + const effect = f(uninterruptible); + return interrupted ?? effect; +}); +/** @internal */ +const abortSignal = /*#__PURE__*/map(/*#__PURE__*/acquireRelease(/*#__PURE__*/sync(() => new AbortController()), controller => sync(() => controller.abort())), _ => _.signal); +// ======================================================================== +// collecting & elements +// ======================================================================== +/** @internal */ +const all = (arg, options) => { + if ((0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(arg)) { + return options?.mode === "result" ? forEach(arg, result, options) : forEach(arg, _Function_js__rspack_import_6/* .identity */.D_, options); + } else if (options?.discard) { + return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), _Function_js__rspack_import_6/* .identity */.D_, options); + } + return suspend(() => { + const out = {}; + return as(forEach(Object.entries(arg), ([key, effect]) => map(options?.mode === "result" ? result(effect) : effect, value => { + _record_js__rspack_import_21/* .assignProperty */.x(out, key, value); + }), { + discard: true, + concurrency: options?.concurrency + }), out); + }); +}; +/** @internal */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => map(forEach(elements, (a, i) => result(f(a, i)), options), results => _Array_js__rspack_import_7/* .partition */.jB(results, _Function_js__rspack_import_6/* .identity */.D_))); +/** @internal */ +const reduce = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (elements, zero, f) => { + const arr = _Array_js__rspack_import_7/* .fromIterable */.Ts(elements); + if (arr.length === 0) return sync(zero); + return suspend(() => { + let index = 0; + let state = zero(); + return map(whileLoop({ + while: () => index < arr.length, + body: () => f(state, arr[index], index), + step(next) { + state = next; + index++; + } + }), () => state); + }); +}); +/** @internal */ +const validate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => flatMap(partition(elements, f, { + concurrency: options?.concurrency +}), ([excluded, satisfying]) => { + if (_Array_js__rspack_import_7/* .isArrayNonEmpty */.CZ(excluded)) { + return fail(excluded); + } + return options?.discard ? void_ : succeed(satisfying); +})); +/** @internal */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, 0, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstLoop = (iterator, index, predicate, value) => flatMap(predicate(value, index), keep => { + if (keep) { + return succeed(_Option_js__rspack_import_17.some(value)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, index + 1, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const findFirstFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, 0, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstFilterLoop = (iterator, index, filter, value) => flatMap(filter(value, index), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + return succeed(_Option_js__rspack_import_17.some(result.success)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, index + 1, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const whileLoop = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "While", + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + this[_core_js__rspack_import_0/* .args */.a2].step(value); + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrencyOption = options?.concurrency ?? 1; + const concurrency = concurrencyOption === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrencyOption); + if (concurrency === 1) { + return forEachSequential(iterable, f, options); + } + const items = _Array_js__rspack_import_7/* .fromIterable */.Ts(iterable); + let length = items.length; + if (length === 0) { + return options?.discard ? void_ : succeed([]); + } + const out = options?.discard ? undefined : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { + concurrency + }); + return eff ? as(eff, out) : succeed(out); +})); +/** @internal */ +const head = self => flatMap(self, elements => { + const result = elements[Symbol.iterator]().next(); + return result.done ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(result.value); +}); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? undefined : []; + 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); +}); +const iterateEagerImpl = options => { + const onItem = options.onItem; + const step = options.step; + const runSequential = (state, items, index, end) => { + for (; index < end; index++) { + const item = items[index]; + const effect = onItem(state, item, index); + if (!effectIsExit(effect)) { + return flatMap(exit(effect), itemExit => step(state, item, itemExit, index) ?? runSequential(state, items, index + 1, end) ?? void_); + } + const terminal = step(state, item, effect, index); + if (terminal) return terminal._tag === "Failure" ? terminal : undefined; + } + }; + return (state, items, opts) => { + let index = 0; + const end = opts?.end ?? items.length; + const concurrency = opts?.concurrency ?? 1; + if (concurrency === 1) { + return runSequential(state, items, 0, end); + } + const orderedStep = opts?.orderedStep === true; + let done = false; + let parentFiber; + let fibers; + let resume; + let interrupted = false; + let terminal; + let effect; + let nextIndex = index; + const exits = orderedStep ? new Array(end) : undefined; + const failDefect = error => { + const defect = (0,_core_js__rspack_import_0/* .exitDie */.V2)(error); + terminal = defect; + done = true; + interrupted = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => defect) : defect; + }; + const runStep = (item, exit, currentIndex) => { + if (!orderedStep) return step(state, item, exit, currentIndex); + if (terminal) return terminal; + exits[currentIndex] = exit; + while (nextIndex < end) { + const nextExit = exits[nextIndex]; + if (nextExit === undefined) return; + exits[nextIndex] = undefined; + const index = nextIndex++; + const result = step(state, items[index], nextExit, index); + if (result) return result; + } + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + // fast case (already an exit) + if (effectIsExit(eff)) { + terminal = runStep(item, eff, index); + if (terminal) break; + // We have an effect, so enter "async" mode + } else if (!parentFiber) { + return callback(cb => { + parentFiber = getCurrentFiber(); + fibers = 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; + interrupted = true; + return fibers ? fiberInterruptAll(fibers) : void_; + }); + }); + // Fork the effect with concurrency > 1 + } else { + // Clear the temporary effect from capturing the parentFiber + effect = undefined; + const fiber = forkUnsafe(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = runStep(item, fiber._exit, index); + if (terminal) break; + continue; + } + // Add the fiber to the Set + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver(exit => { + fibers.delete(fiber); + try { + if (terminal) { + if (!interrupted && exit._tag === "Failure") { + for (const reason of exit.cause.reasons) { + if (reason._tag === "Interrupt") continue;else if (terminal._tag === "Failure") { + ; + terminal.cause.reasons.push(reason); + } else { + terminal = (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)([reason])); + } + } + } + } else { + const result = runStep(item, exit, currentIndex); + if (result) { + terminal = result._tag === "Failure" ? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(result.cause.reasons.slice())) : 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)); + } + }); + // Check if we have reached the concurrency limit + 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(); + }; +}; +/** @internal */ +const iterateEager = () => iterateEagerImpl; +const forEachConcurrent = /*#__PURE__*/iterateEagerImpl({ + 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 filterOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, orElse) => flatMap(self, a => predicate(a) ? succeed(a) : orElse(a))); +/** @internal */ +const filterMapOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, orElse) => flatMap(self, a => { + const result = filter(a); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? orElse(result.failure) : succeed(result.success); +})); +/* @internal */ +const filterMapOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, orFailWith) => filterMapOrElse(self, filter, orFailWith ? x => fail(orFailWith(x)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate, options) => suspend(() => { + const out = []; + return as(forEach(elements, (a, i) => { + const result = predicate(a, i); + if (typeof result === "boolean") { + if (result) out.push(a); + return void_; + } + return map(result, keep => { + if (keep) { + out.push(a); + } + }); + }, { + discard: true, + concurrency: options?.concurrency + }), out); +})); +/** @internal */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const out = []; + for (const a of elements) { + const result = filter(a); + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + } + return succeed(out); +})); +/** @internal */ +const filterMapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter, options) => suspend(() => { + const out = []; + return as(forEach(elements, a => map(filter(a), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + }), { + discard: true, + concurrency: options?.concurrency + }), out); +})); +// ---------------------------------------------------------------------------- +// do notation +// ---------------------------------------------------------------------------- +/** @internal */ +const Do = /*#__PURE__*/succeed({}); +/** @internal */ +const bindTo = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bindTo */.Jr(map); +/** @internal */ +const bind = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bind */.oI(map, flatMap); +/** @internal */ +const let_ = /*#__PURE__*/_doNotation_js__rspack_import_22/* .let_ */.zM(map); +/** @internal */ + +// ---------------------------------------------------------------------------- +// fibers & forking +// ---------------------------------------------------------------------------- +/** @internal */ +const forkChild = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + interruptChildrenPatch(); + return succeed(forkUnsafe(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false)); +})); +/** @internal */ +const forkUnsafe = (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 (immediate) { + child.evaluate(effect); + } else { + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + if (!daemon && !child._exit) { + parentRuntime.children().add(child); + child.addObserver(() => parentRuntime._children.delete(child)); + } + return child; +}; +/** @internal */ +const forkDetach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(forkUnsafe(fiber, self, options?.startImmediately, true, options?.uninterruptible)))); +/** @internal */ +const awaitAllChildren = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const initialChildren = fiber._children && new Set(fiber._children); + return onExit(self, _ => { + let children = fiber._children; + if (children === undefined || children.size === 0) { + return void_; + } else if (initialChildren) { + children = _Iterable_js__rspack_import_23/* .filter */.pb(children, child => !initialChildren.has(child)); + } + return asVoid(fiberAwaitAll(children)); + }); +}); +/** @internal */ +const forkIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, scope, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + if (!fiber._exit) { + if (scope.state._tag !== "Closed") { + const key = {}; + const finalizer = () => withFiberId(interruptor => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); + scopeAddFinalizerUnsafe(scope, key, finalizer); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + } else { + fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); + } + } + return succeed(fiber); +})); +/** @internal */ +const forkScoped = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => flatMap(scope, scope => forkIn(self, scope, options))); +// ---------------------------------------------------------------------------- +// execution +// ---------------------------------------------------------------------------- +/** @internal */ +const runForkWith = context => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? _Context_js__rspack_import_5/* .add */.WQ(context, _Scheduler_js__rspack_import_13/* .Scheduler */._F, 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 fiberRunIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => { + if (self._exit) { + return self; + } else if (scope.state._tag === "Closed") { + self.interruptUnsafe(self.id); + return self; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, () => fiberInterrupt(self)); + self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + return self; +}); +/** @internal */ +const runFork = /*#__PURE__*/runForkWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runCallbackWith = context => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + if (options?.onExit) { + fiber.addObserver(options.onExit); + } + return interruptor => { + return fiber.interruptUnsafe(interruptor); + }; + }; +}; +/** @internal */ +const runCallback = /*#__PURE__*/runCallbackWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 runPromiseExit = /*#__PURE__*/runPromiseExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runPromiseWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runSyncExitWith = context => { + const runFork = runForkWith(context); + return effect => { + if (effectIsExit(effect)) return effect; + const scheduler = new _Scheduler_js__rspack_import_13/* .MixedScheduler */.FG("sync"); + const fiber = runFork(effect, { + scheduler + }); + fiber._dispatcher?.flush(); + return fiber._exit ?? (0,_core_js__rspack_import_0/* .exitDie */.V2)(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncExit = /*#__PURE__*/runSyncExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runSyncWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +const succeedTrue = /*#__PURE__*/succeed(true); +const succeedFalse = /*#__PURE__*/succeed(false); +class Latch { + waiters = []; + scheduled = undefined; + _isOpen; + constructor(isOpen) { + this._isOpen = isOpen; + } + scheduleUnsafe(fiber) { + if (this.waiters.length === 0) { + return succeedTrue; + } + if (this.scheduled === undefined) { + this.scheduled = this.waiters; + fiber.currentDispatcher.scheduleTask(this.flushScheduled, 0); + } else { + for (let i = 0; i < this.waiters.length; i++) { + this.scheduled.push(this.waiters[i]); + } + } + this.waiters = []; + return succeedTrue; + } + flushScheduled = () => { + if (this.scheduled === undefined) return; + const waiters = this.scheduled; + this.scheduled = undefined; + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + }; + flushWaiters() { + // swap both arrays out before any resume runs: a resumed waiter can + // reentrantly close the latch and register new waiters, which must not + // be drained by this flush + const waiters = this.waiters; + this.waiters = []; + this.flushScheduled(); + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + } + open = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (this._isOpen) return succeedFalse; + this._isOpen = true; + return this.scheduleUnsafe(fiber); + }); + release = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => this._isOpen ? succeedFalse : this.scheduleUnsafe(fiber)); + openUnsafe() { + if (this._isOpen) return false; + this._isOpen = true; + this.flushWaiters(); + return true; + } + await = /*#__PURE__*/callback(resume => { + if (this._isOpen) { + return resume(void_); + } + this.waiters.push(resume); + return sync(() => { + let index = this.waiters.indexOf(resume); + if (index !== -1) { + this.waiters.splice(index, 1); + } else if (this.scheduled !== undefined) { + index = this.scheduled.indexOf(resume); + if (index !== -1) { + this.scheduled.splice(index, 1); + } + } + }); + }); + closeUnsafe() { + if (!this._isOpen) return false; + this._isOpen = false; + return true; + } + close = /*#__PURE__*/sync(() => this.closeUnsafe()); + whenOpen = self => flatMap(this.await, () => self); + isOpen() { + return this._isOpen; + } +} +/** @internal */ +const makeLatchUnsafe = open => new Latch(open ?? false); +/** @internal */ +const makeLatch = open => sync(() => makeLatchUnsafe(open)); +// ---------------------------------------------------------------------------- +// Tracer +// ---------------------------------------------------------------------------- +/** @internal */ +const tracer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh))); +/** @internal */ +const withTracer = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (effect, tracer) => provideService(effect, _Tracer_js__rspack_import_14/* .Tracer */.sh, tracer)); +/** @internal */ +const withTracerEnabled = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerEnabled */.rf); +/** @internal */ +const withTracerTiming = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); +const bigint0 = /*#__PURE__*/BigInt(0); +const NoopSpanProto = { + _tag: "Span", + spanId: "noop", + traceId: "noop", + sampled: false, + status: { + _tag: "Ended", + startTime: bigint0, + endTime: bigint0, + exit: exitVoid + }, + attributes: /*#__PURE__*/new Map(), + links: [], + kind: "internal", + attribute() {}, + event() {}, + end() {}, + addLinks() {} +}; +/** @internal */ +const noopSpan = options => Object.assign(Object.create(NoopSpanProto), options); +const filterDisablePropagation = span => { + if (!span) return _Option_js__rspack_import_17.none(); + return _Context_js__rspack_import_5/* .get */.Jt(span.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW) ? span._tag === "Span" ? filterDisablePropagation(_Option_js__rspack_import_17.getOrUndefined(span.parent)) : _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(span); +}; +/** @internal */ +const makeSpanUnsafe = (fiber, name, options) => { + const disablePropagation = !fiber.getRef(_references_js__rspack_import_15/* .TracerEnabled */.rf) || options?.annotations && _Context_js__rspack_import_5/* .get */.Jt(options.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW); + const parent = options?.parent !== undefined ? _Option_js__rspack_import_17.some(options.parent) : options?.root ? _Option_js__rspack_import_17.none() : filterDisablePropagation(fiber.currentSpan); + let span; + if (disablePropagation) { + span = noopSpan({ + name, + parent, + annotations: _Context_js__rspack_import_5/* .add */.WQ(options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), _Tracer_js__rspack_import_14/* .DisablePropagation */.DW, true) + }); + } else { + const tracer = fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + const annotationsFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanAnnotations */.ce); + const linksFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanLinks */.ls); + const level = options?.level ?? fiber.getRef(_Tracer_js__rspack_import_14/* .CurrentTraceLevel */.pX); + const links = options?.links !== undefined ? [...linksFromEnv, ...options.links] : linksFromEnv.length === 0 ? [] : linksFromEnv.slice(); + span = tracer.span({ + name, + parent, + annotations: options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), + links, + startTime: timingEnabled ? clock.currentTimeNanosUnsafe() : BigInt(0), + kind: options?.kind ?? "internal", + root: options?.root ?? _Option_js__rspack_import_17.isNone(parent), + sampled: options?.sampled ?? (_Option_js__rspack_import_17.isSome(parent) && parent.value.sampled === false ? false : !isLogLevelGreaterThan(fiber.getRef(_Tracer_js__rspack_import_14/* .MinimumTraceLevel */.EW), level)) + }); + for (const key in annotationsFromEnv) { + span.attribute(key, annotationsFromEnv[key]); + } + if (options?.attributes !== undefined) { + for (const key in options.attributes) { + span.attribute(key, options.attributes[key]); + } + } + } + return span; +}; +/** @internal */ +const makeSpan = (name, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(makeSpanUnsafe(fiber, name, options))); +/** @internal */ +const makeSpanScoped = (name, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const scope = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag); + const span = makeSpanUnsafe(fiber, name, options ?? {}); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return as(scopeAddFinalizerExit(scope, exit => endSpan(span, exit, clock, timingEnabled)), span); +})); +/** @internal */ +const withSpanScoped = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); + } + return self => flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : _Function_js__rspack_import_6/* .constUndefined */.MN; + return updateService(_references_js__rspack_import_15/* .CurrentStackFrame */.vA, parent => ({ + name, + stack, + parent + })); +}; +/** @internal */ +const spanAnnotations = _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce; +/** @internal */ +const spanLinks = _references_js__rspack_import_15/* .TracerSpanLinks */.ls; +/** @internal */ +const linkSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, span, attributes = {}) => { + const spans = Array.isArray(span) ? span : [span]; + const links = spans.map(span => ({ + span, + attributes + })); + return updateService(self, _references_js__rspack_import_15/* .TracerSpanLinks */.ls, current => [...current, ...links]); +}); +/** @internal */ +const endSpan = (span, exit, clock, timingEnabled) => sync(() => { + if (span.status._tag === "Ended") return; + span.end(timingEnabled ? clock.currentTimeNanosUnsafe() : bigint0, exit); +}); +/** @internal */ +const useSpan = (name, ...args) => { + const options = args.length === 1 ? undefined : args[0]; + const evaluate = args[args.length - 1]; + return (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = makeSpanUnsafe(fiber, name, options); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return onExit((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(span)), exit => endSpan(span, exit, clock, timingEnabled)); + }); +}; +const provideParentSpan = /*#__PURE__*/provideService(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +/** @internal */ +const withParentSpan = function () { + const dataFirst = (0,_core_js__rspack_import_0/* .isEffect */.yw)(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = _Function_js__rspack_import_6/* .identity */.D_; + if (span._tag === "Span") { + options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + if (dataFirst) { + return provideParentSpan(provideStackFrame(arguments[0]), span); + } + return self => provideParentSpan(provideStackFrame(self), span); +}; +/** @internal */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const traceOptions = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(arguments[2]); + if (dataFirst) { + const self = arguments[0]; + return useSpan(name, arguments[2], span => withParentSpan(self, span, traceOptions)); + } + const fnArg = typeof arguments[1] === "function" ? arguments[1] : undefined; + const options = fnArg ? undefined : arguments[1]; + return (self, ...args) => useSpan(name, fnArg ? fnArg(...args) : options, span => withParentSpan(self, span, traceOptions)); +}; +/** @internal */ +const annotateSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (effect, ...args) => updateService(effect, _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + _record_js__rspack_import_21/* .assignProperty */.x(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})); +/** @internal */ +const annotateCurrentSpan = (...args) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + if (span) { + if (args.length === 1) { + for (const [key, value] of Object.entries(args[0])) { + span.attribute(key, value); + } + } else { + span.attribute(args[0], args[1]); + } + } + return void_; +}); +/** @internal */ +const currentSpan = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + return span ? succeed(span) : fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()); +}); +/** @internal */ +const currentParentSpan = /*#__PURE__*/serviceOptional(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +// ---------------------------------------------------------------------------- +// Clock +// ---------------------------------------------------------------------------- +/** @internal */ +const ClockRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Clock", { + defaultValue: () => new ClockImpl() +}); +const MAX_TIMER_MILLIS = 2 ** 31 - 1; +class ClockImpl { + currentTimeMillisUnsafe() { + return Date.now(); + } + currentTimeMillis = /*#__PURE__*/sync(() => this.currentTimeMillisUnsafe()); + currentTimeNanosUnsafe() { + return wallTimeNanos(); + } + currentTimeNanos = /*#__PURE__*/sync(() => this.currentTimeNanosUnsafe()); + monotonicTimeNanosUnsafe() { + return monotonicNowNanos(); + } + monotonicTimeNanos = /*#__PURE__*/sync(() => this.monotonicTimeNanosUnsafe()); + sleep(duration) { + return this.sleepMillis(_Duration_js__rspack_import_20/* .toMillis */.kE(duration)); + } + sleepMillis(millis) { + if (millis <= 0) return yieldNow;else if (!Number.isFinite(millis)) return never; + return callback(resume => { + const continuation = millis > MAX_TIMER_MILLIS ? this.sleepMillis(millis - MAX_TIMER_MILLIS) : void_; + const handle = setTimeout(() => resume(continuation), Math.min(millis, MAX_TIMER_MILLIS)); + return sync(() => clearTimeout(handle)); + }); + } +} +const nanosPerMilli = /*#__PURE__*/BigInt(1_000_000); +const monotonicNowNanos = /*#__PURE__*/function () { + const processHrtime = globalThis.process?.hrtime; + if (typeof processHrtime?.bigint === "function") { + return () => processHrtime.bigint(); + } + if (typeof performance !== "undefined" && typeof performance.now === "function") { + return () => BigInt(Math.round(performance.now() * 1_000_000)); + } + let previous = /*#__PURE__*/BigInt(0); + return () => { + const current = BigInt(Date.now()) * nanosPerMilli; + if (current > previous) { + previous = current; + } + return previous; + }; +}(); +const wallTimeNanos = /*#__PURE__*/function () { + const reanchorThresholdNanos = /*#__PURE__*/BigInt(1_000_000_000); + let origin; + return () => { + const monotonic = monotonicNowNanos(); + const wall = BigInt(Date.now()) * nanosPerMilli; + if (origin === undefined) { + origin = wall - monotonic; + } else { + const projected = origin + monotonic; + const skew = wall > projected ? wall - projected : projected - wall; + if (skew > reanchorThresholdNanos) { + origin = wall - monotonic; + } + } + return origin + monotonic; + }; +}(); +/** @internal */ +const clockWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.getRef(ClockRef))); +/** @internal */ +const sleep = duration => clockWith(clock => clock.sleep(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(duration))); +/** @internal */ +const currentTimeMillis = /*#__PURE__*/clockWith(clock => clock.currentTimeMillis); +/** @internal */ +const currentTimeNanos = /*#__PURE__*/clockWith(clock => clock.currentTimeNanos); +/** @internal */ +const monotonicTimeNanos = /*#__PURE__*/clockWith(clock => clock.monotonicTimeNanos); +// ---------------------------------------------------------------------------- +// Errors +// ---------------------------------------------------------------------------- +/** @internal */ +const TimeoutErrorTypeId = "~effect/Cause/TimeoutError"; +/** @internal */ +const isTimeoutError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, TimeoutErrorTypeId); +/** @internal */ +class TimeoutError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("TimeoutError") { + [TimeoutErrorTypeId] = TimeoutErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const IllegalArgumentErrorTypeId = "~effect/Cause/IllegalArgumentError"; +/** @internal */ +const isIllegalArgumentError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, IllegalArgumentErrorTypeId); +/** @internal */ +class IllegalArgumentError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("IllegalArgumentError") { + [IllegalArgumentErrorTypeId] = IllegalArgumentErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const ExceededCapacityErrorTypeId = "~effect/Cause/ExceededCapacityError"; +/** @internal */ +const isExceededCapacityError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, ExceededCapacityErrorTypeId); +/** @internal */ +class ExceededCapacityError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("ExceededCapacityError") { + [ExceededCapacityErrorTypeId] = ExceededCapacityErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +const isAsyncFiberError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, AsyncFiberErrorTypeId); +/** @internal */ +class AsyncFiberError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("AsyncFiberError") { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +} +/** @internal */ +const UnknownErrorTypeId = "~effect/Cause/UnknownError"; +/** @internal */ +const isUnknownError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, UnknownErrorTypeId); +/** @internal */ +class UnknownError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("UnknownError") { + [UnknownErrorTypeId] = UnknownErrorTypeId; + constructor(cause, message) { + super({ + message, + cause + }); + } +} +// ---------------------------------------------------------------------------- +// Console +// ---------------------------------------------------------------------------- +/** @internal */ +const ConsoleRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Console/CurrentConsole", { + defaultValue: () => globalThis.console +}); +// ---------------------------------------------------------------------------- +// LogLevel +// ---------------------------------------------------------------------------- +/** @internal */ +const logLevelToOrder = level => { + switch (level) { + case "All": + return Number.MIN_SAFE_INTEGER; + case "Fatal": + return 50_000; + case "Error": + return 40_000; + case "Warn": + return 30_000; + case "Info": + return 20_000; + case "Debug": + return 10_000; + case "Trace": + return 0; + case "None": + return Number.MAX_SAFE_INTEGER; + } +}; +/** @internal */ +const LogLevelOrder = /*#__PURE__*/_Order_js__rspack_import_24/* .mapInput */.zQ(_Order_js__rspack_import_24/* .Number */.wN, logLevelToOrder); +/** @internal */ +const isLogLevelGreaterThan = /*#__PURE__*/_Order_js__rspack_import_24/* .isGreaterThan */.yJ(LogLevelOrder); +// ---------------------------------------------------------------------------- +// Logger +// ---------------------------------------------------------------------------- +/** @internal */ +const CurrentLoggers = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Loggers/CurrentLoggers", { + defaultValue: () => new Set([defaultLogger, tracerLogger]) +}); +/** @internal */ +const LogToStderr = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Logger/LogToStderr", { + defaultValue: _Function_js__rspack_import_6/* .constFalse */.f4 +}); +/** @internal */ +const annotateLogsScoped = function () { + const entries = typeof arguments[0] === "string" ? [[arguments[0], arguments[1]]] : Object.entries(arguments[0]); + return uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...prev + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + _record_js__rspack_import_21/* .assignProperty */.x(next, key, value); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...current + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + if (current[key] !== value) continue; + if (Object.hasOwn(prev, key)) { + _record_js__rspack_import_21/* .assignProperty */.x(next, key, prev[key]); + } else { + delete next[key]; + } + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return void_; + }); + })); +}; +/** @internal */ +const LoggerTypeId = "~effect/Logger"; +const LoggerProto = { + [LoggerTypeId]: { + _Message: _Function_js__rspack_import_6/* .identity */.D_, + _Output: _Function_js__rspack_import_6/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } +}; +/** @internal */ +const loggerMake = log => { + const self = Object.create(LoggerProto); + self.log = log; + return self; +}; +/** + * Sanitize a given string by replacing spaces, equal signs, and double quotes + * with underscores. + * + * @internal + */ +const formatLabel = key => key.replace(/[\s="]/g, "_"); +/** + * Formats a log span into a ``. + * + * **Example** (Normalizing input) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.ensure("a") // => ["a"] + * Array.ensure(["a", "b", "c"]) // => ["a", "b", "c"] + * ``` + * + * @see {@link of} — always wrap in a single-element array + * @see {@link fromIterable} — convert any iterable + * + * @category constructors + * @since 3.3.0 + */ +const ensure = self => Array.isArray(self) ? self : [self]; +/** + * Converts a record into an array of `[key, value]` tuples. + * + * **When to use** + * + * Use to convert a record into an array of key-value tuples for iteration or + * transformation. + * + * **Details** + * + * Key order follows `Object.entries` semantics. Empty records produce an empty + * array. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromRecord({ a: 1, b: 2, c: 3 }) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @see {@link Record.toEntries} the equivalent function from the Record module + * @see {@link Record.fromEntries} to build a record from an array of tuples + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = _Record_js__rspack_import_0/* .toEntries */.Wo; +/** + * Converts an `Option` to an array: `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use to convert a single `Option` into an array for downstream array operations. + * + * **Example** (Converting an Option to an array) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.fromOption(Option.some(1)) // => [1] + * Array.fromOption(Option.none()) // => [] + * ``` + * + * @see {@link getSomes} — extract `Some` values from an array of Options + * + * @category converting + * @since 2.0.0 + */ +const fromOption = _Option_js__rspack_import_1.toArray; +/** + * Pattern-matches on an array, handling empty and non-empty cases separately. + * + * **When to use** + * + * Use when you need to branch on whether an array is empty. + * + * **Details** + * + * `onNonEmpty` receives a `NonEmptyReadonlyArray`. Supports both data-first and + * data-last usage. + * + * **Example** (Branching on emptiness) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const describe = Array.match({ + * onEmpty: () => "empty", + * onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}` + * }) + * + * describe([]) // => "empty" + * describe([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link matchLeft} — destructures into head + tail + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(self) : onEmpty()))); +/** + * Pattern-matches on an array from the left, providing the first element and + * the remaining elements separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * first element plus the remaining elements. + * + * **Details** + * + * `onNonEmpty` receives `(head, tail)` where `tail` is the rest of the array. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchLeft = Array.matchLeft({ + * onEmpty: () => "empty", + * onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}` + * }) + * + * matchLeft([]) // => "empty" + * matchLeft([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const matchLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(headNonEmpty(self), tailNonEmpty(self)) : onEmpty()))); +/** + * Pattern-matches on an array from the right, providing all elements except the + * last and the last element separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * elements before the last plus the last element. + * + * **Details** + * + * `onNonEmpty` receives `(init, last)` where `init` is everything but the last element. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchRight = Array.matchRight({ + * onEmpty: () => "empty", + * onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}` + * }) + * + * matchRight([]) // => "empty" + * matchRight([1, 2, 3]) // => "init: 2, last: 3" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchLeft} — destructures into head + tail + * + * @category pattern matching + * @since 2.0.0 + */ +const matchRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self)) : onEmpty()))); +/** + * Adds a single element to the front of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * leading value. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prepend([2, 3, 4], 1) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add to the end + * @see {@link prependAll} — prepend multiple elements + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => [head, ...self]))); +/** + * Prepends all elements from a prefix iterable to the front of an array. + * + * **When to use** + * + * Use to prepend multiple elements from an iterable to the front of an array. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Prepending multiple elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prependAll([2, 3], [0, 1]) // => [0, 1, 2, 3] + * ``` + * + * @see {@link prepend} — add a single element to the front + * @see {@link appendAll} — add elements to the end + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromIterable(that).concat(fromIterable(self))))); +/** + * Adds a single element to the end of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * trailing value. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.append([1, 2, 3], 4) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} — add to the front + * @see {@link appendAll} — append multiple elements + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => [...self, last]))); +/** + * Concatenates two iterables into a single array. + * + * **When to use** + * + * Use to combine two iterable inputs into a new array with the second input's + * elements after the first. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Concatenating arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.appendAll([1, 2], [3, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add a single element to the end + * @see {@link prependAll} — add elements to the front + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => fromIterable(self).concat(fromIterable(that))); +/** + * Folds left-to-right while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator where each intermediate value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it starts with the initial + * value. The result is always a `NonEmptyArray`. Use `reduce` if you only need + * the final accumulated value. + * + * **Example** (Running totals) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [0, 1, 3, 6, 10] + * ``` + * + * @see {@link scanRight} — right-to-left scan + * @see {@link reduce} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const out = [b]; + let i = 0; + for (const a of self) { + out[i + 1] = f(out[i], a); + i++; + } + return out; +}))); +/** + * Folds right-to-left while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator from right to left where each intermediate + * value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it ends with the initial + * value. The result is always a `NonEmptyArray`. + * + * **Example** (Scanning running totals in reverse) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [10, 9, 7, 4, 0] + * ``` + * + * @see {@link scan} — left-to-right scan + * @see {@link reduceRight} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scanRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const input = fromIterable(self); + const out = new Array(input.length + 1); + out[input.length] = b; + for (let i = input.length - 1; i >= 0; i--) { + out[i] = f(out[i + 1], input[i]); + } + return out; +}))); +/** + * Checks whether a value is an `Array`. + * + * **When to use** + * + * Use to verify a value is a mutable array, narrowing its type to `Array`. + * + * **Details** + * + * Acts as a type guard narrowing the input to `Array` and delegates to + * `globalThis.Array.isArray`. + * + * **Example** (Type-guarding an unknown value) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArray(null) // => false + * Array.isArray([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayEmpty} — check for an empty array + * @see {@link isArrayNonEmpty} — check for a non-empty array + * + * @category guards + * @since 2.0.0 + */ +const isArray = Array.isArray; +/** + * Checks whether a mutable `Array` is empty, narrowing the type to `[]`. + * + * **Example** (Checking for an empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayEmpty([]) // => true + * Array.isArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isReadonlyArrayEmpty} — readonly variant + * @see {@link isArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayEmpty = self => self.length === 0; +/** + * Checks whether a `ReadonlyArray` is empty, narrowing the type to `readonly []`. + * + * **Example** (Checking for an empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayEmpty([]) // => true + * Array.isReadonlyArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isArrayEmpty} — mutable variant + * @see {@link isReadonlyArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayEmpty = (/* unused pure expression or super */ null && (isArrayEmpty)); +/** + * Checks whether a mutable `Array` is non-empty, narrowing the type to + * `NonEmptyArray`. + * + * **When to use** + * + * Use when you need the narrowed value to remain a mutable `Array` after proving + * it has at least one element. + * + * **Example** (Checking for a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayNonEmpty([]) // => false + * Array.isArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isReadonlyArrayNonEmpty} — readonly variant + * @see {@link isArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Checks whether a `ReadonlyArray` is non-empty, narrowing the type to + * `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use when you need to prove a readonly array has at least one element without + * requiring mutable array methods afterward. + * + * **Example** (Checking for a non-empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayNonEmpty([]) // => false + * Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayNonEmpty} — mutable variant + * @see {@link isReadonlyArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Returns the number of elements in a `ReadonlyArray`. + * + * **When to use** + * + * Use when you need length as a composable function rather than a property access. + * + * **Example** (Getting the length) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.length([1, 2, 3]) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const length = self => self.length; +/** @internal */ +function isOutOfBounds(i, as) { + return !Number.isFinite(i) || i < 0 || i >= as.length; +} +const clamp = (i, as) => Math.floor(Math.min(Math.max(0, i), as.length)); +/** + * Reads an element at the given index safely, returning `Option.some` or + * `Option.none` if the index is out of bounds. + * + * **When to use** + * + * Use when you need to read an array element by index and handle an + * out-of-bounds index as `Option.none`. + * + * **Details** + * + * The index is floored to an integer. This never throws. + * + * **Example** (Accessing indexes safely) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.get([1, 2, 3], 1) // => Option.some(2) + * Array.get([1, 2, 3], 10) // => Option.none() + * ``` + * + * @see {@link getUnsafe} for indexed access that throws when the index is out of bounds + * @see {@link head} for reading the first element as an `Option` + * @see {@link last} for reading the last element as an `Option` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + return isOutOfBounds(i, self) ? Option.none() : Option.some(self[i]); +}))); +/** + * Reads an element at the given index, throwing if the index is out of bounds. + * + * **When to use** + * + * Use to read an array element at a known valid index when out-of-bounds would + * be a programming error. + * + * **Details** + * + * Throws an `Error` with the message `"Index out of bounds: "`. Prefer + * `get` for safe access. + * + * **Example** (Accessing indexes unsafely) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.getUnsafe([1, 2, 3], 1) // => 2 + * // Array.getUnsafe([1, 2, 3], 10) // throws Error + * ``` + * + * @see {@link get} — safe version returning `Option` + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + if (isOutOfBounds(i, self)) { + throw new Error(`Index out of bounds: ${i}`); + } + return self[i]; +}))); +/** + * Splits a non-empty array into its first element and the remaining elements. + * + * **When to use** + * + * Use when you have a `NonEmptyReadonlyArray` and need both its first element + * and the remaining elements as separate values. + * + * **Details** + * + * Returns a tuple `[head, tail]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unprepend([1, 2, 3, 4]) // => [1, [2, 3, 4]] + * ``` + * + * @see {@link unappend} for splitting a non-empty array into init and last + * @see {@link headNonEmpty} for getting only the first element + * @see {@link tailNonEmpty} for getting only the elements after the first + * + * @category splitting + * @since 2.0.0 + */ +const unprepend = self => [headNonEmpty(self), tailNonEmpty(self)]; +/** + * Splits a non-empty array into all elements except the last, and the last + * element. + * + * **When to use** + * + * Use when you need to split a non-empty array into the elements before the + * last element and the last element. + * + * **Details** + * + * Returns a tuple `[init, last]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unappend([1, 2, 3, 4]) // => [[1, 2, 3], 4] + * ``` + * + * @see {@link unprepend} for splitting a non-empty array into head and tail + * @see {@link initNonEmpty} for getting only the elements before the last + * @see {@link lastNonEmpty} for getting only the last element + * + * @category splitting + * @since 2.0.0 + */ +const unappend = self => [initNonEmpty(self), lastNonEmpty(self)]; +/** + * Returns the first element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the first element of an array that may be empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.head([1, 2, 3]) // => Option.some(1) + * Array.head([]) // => Option.none() + * ``` + * + * @see {@link headNonEmpty} — direct access when array is known non-empty + * @see {@link last} — get the last element + * + * @category getters + * @since 2.0.0 + */ +const head = /*#__PURE__*/(/* unused pure expression or super */ null && (get(0))); +/** + * Returns the first element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the first element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the head of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.headNonEmpty([1, 2, 3, 4]) // => 1 + * ``` + * + * @see {@link head} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const headNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (getUnsafe(0))); +/** + * Returns the last element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the last element of an array that may be empty. + * + * **Example** (Getting the last element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.last([1, 2, 3]) // => Option.some(3) + * Array.last([]) // => Option.none() + * ``` + * + * @see {@link lastNonEmpty} — direct access when array is known non-empty + * @see {@link head} — get the first element + * + * @category getters + * @since 2.0.0 + */ +const last = self => isReadonlyArrayNonEmpty(self) ? Option.some(lastNonEmpty(self)) : Option.none(); +/** + * Returns the last element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the last element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the last of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.lastNonEmpty([1, 2, 3, 4]) // => 4 + * ``` + * + * @see {@link last} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const lastNonEmpty = self => self[self.length - 1]; +/** + * Returns all elements except the first safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements after the first when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(1)`. Empty inputs return `Option.none()`. + * + * **Example** (Getting the tail) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.tail([1, 2, 3, 4]) // => Option.some([2, 3, 4]) + * Array.tail([]) // => Option.none() + * ``` + * + * @see {@link tailNonEmpty} — when the array is known non-empty + * @see {@link init} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +function tail(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(tailNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the first of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements after the first when the array is known to be non-empty. + * + * **Example** (Getting the tail of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.tailNonEmpty([1, 2, 3, 4]) // => [2, 3, 4] + * ``` + * + * @see {@link tail} — safe version for possibly-empty arrays + * @see {@link initNonEmpty} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +const tailNonEmpty = self => self.slice(1); +/** + * Returns all elements except the last safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements before the last when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(0, -1)`. Empty inputs return + * `Option.none()`. + * + * **Example** (Getting init) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.init([1, 2, 3, 4]) // => Option.some([1, 2, 3]) + * Array.init([]) // => Option.none() + * ``` + * + * @see {@link initNonEmpty} — when the array is known non-empty + * @see {@link tail} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +function init(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(initNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the last of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements before the last when the array is known to be non-empty. + * + * **Example** (Getting init of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.initNonEmpty([1, 2, 3, 4]) // => [1, 2, 3] + * ``` + * + * @see {@link init} — safe version for possibly-empty arrays + * @see {@link tailNonEmpty} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +const initNonEmpty = self => self.slice(0, -1); +/** + * Keeps the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep up to the first `n` elements from an iterable as a new array. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.take([1, 2, 3, 4, 5], 3) // => [1, 2, 3] + * ``` + * + * @see {@link takeRight} for keeping elements from the end + * @see {@link takeWhile} for keeping an initial prefix while a predicate holds + * @see {@link drop} for removing elements from the start + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, clamp(n, input)); +}))); +/** + * Keeps the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the last `n` elements of an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeRight([1, 2, 3, 4, 5], 3) // => [3, 4, 5] + * ``` + * + * @see {@link take} — keep from the start + * @see {@link dropRight} — remove from the end + * + * @category getters + * @since 2.0.0 + */ +const takeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + const i = clamp(n, input); + return i === 0 ? [] : input.slice(-i); +}))); +/** + * Takes elements from the start while the predicate holds, stopping at the + * first element that fails. + * + * **When to use** + * + * Use to keep the leading elements of an iterable while each element satisfies + * a predicate, returning the retained prefix as an array. + * + * **Details** + * + * Supports refinements for type narrowing. The predicate receives + * `(element, index)`. + * + * **Example** (Taking while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4) // => [1, 3, 2] + * ``` + * + * @see {@link take} for keeping a fixed number of leading elements + * @see {@link dropWhile} for removing the matching prefix and keeping the rest + * @see {@link span} for splitting the matching prefix from the remaining elements + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + const out = []; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + out.push(a); + i++; + } + return out; +}))); +/** + * Takes elements from the start while a `Filter` succeeds, collecting transformed values. + * + * **When to use** + * + * Use when you need to take a prefix from an iterable while a function can + * successfully extract or transform elements, stopping at the first element + * that produces a failure result. + * + * **Details** + * + * The filter receives `(element, index)` and processing stops at the first + * filter failure. + * + * @see {@link takeWhile} for taking a prefix based on a boolean predicate + * + * @category getters + * @since 4.0.0 + */ +const takeWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + const out = []; + for (const a of self) { + const result = f(a, i); + if (Result.isFailure(result)) { + break; + } + out.push(result.success); + i++; + } + return out; +}))); +const spanIndex = (self, predicate) => { + let i = 0; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + i++; + } + return i; +}; +/** + * Splits an iterable into two arrays: the longest prefix where the predicate + * holds, and the remaining elements. + * + * **When to use** + * + * Use when you need both the longest predicate-matching prefix and the + * remaining elements. + * + * **Details** + * + * Equivalent to `[takeWhile(pred), dropWhile(pred)]`, but more efficient + * because it runs in a single pass. Supports refinements for type narrowing of + * the prefix. + * + * **Example** (Splitting at predicate boundary) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.span([1, 3, 2, 4, 5], (x) => x % 2 === 1) // => [[1, 3], [2, 4, 5]] + * ``` + * + * @see {@link takeWhile} for keeping only the matching prefix + * @see {@link dropWhile} for keeping only the elements after the matching prefix + * @see {@link splitWhere} for splitting at the first element that satisfies a predicate + * + * @category splitting + * @since 2.0.0 + */ +const span = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + return splitAt(input, spanIndex(input, predicate)); +}))); +/** + * Removes the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the suffix of an iterable after skipping a fixed number of + * leading elements. + * + * **Details** + * + * `n` is clamped to `[0, length]`. When `n <= 0`, this returns a copy of the + * full array. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.drop([1, 2, 3, 4, 5], 2) // => [3, 4, 5] + * ``` + * + * @see {@link dropRight} for removing a fixed number of elements from the end + * @see {@link dropWhile} for removing a prefix based on a predicate instead of a fixed count + * @see {@link take} for keeping a fixed number of elements from the start + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(clamp(n, input), input.length); +}))); +/** + * Removes the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to remove the last `n` elements from an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. + * + * **Example** (Dropping from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropRight([1, 2, 3, 4, 5], 2) // => [1, 2, 3] + * ``` + * + * @see {@link drop} — remove from the start + * @see {@link takeRight} — keep from the end + * + * @category getters + * @since 2.0.0 + */ +const dropRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, input.length - clamp(n, input)); +}))); +/** + * Drops elements from the start while the predicate holds, returning the rest. + * + * **When to use** + * + * Use to remove a leading prefix of elements that satisfy a predicate. + * + * **Details** + * + * The predicate receives `(element, index)`. + * + * **Example** (Dropping while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) // => [4, 5] + * ``` + * + * @see {@link takeWhile} — keep the matching prefix instead + * @see {@link drop} — drop a fixed count + * + * @category getters + * @since 2.0.0 + */ +const dropWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (!predicate(input[i], i)) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Drops elements from the start while a `Filter` succeeds. + * + * **When to use** + * + * Use when you need to drop a prefix from an iterable by computing a `Result` + * per element instead of using a simple boolean predicate. + * + * **Details** + * + * The filter receives `(element, index)`. The result contains the remaining + * original elements after the first filter failure. + * + * @see {@link dropWhile} for dropping a prefix with a simple boolean predicate + * @see {@link takeWhileFilter} for keeping only the matching prefix + * + * @category getters + * @since 4.0.0 + */ +const dropWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (Result.isFailure(f(input[i], i))) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Returns the index of the first element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the first matching element from the start of an + * iterable. + * + * **Example** (Finding an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstIndex([5, 3, 8, 9], (x) => x > 5) // => Option.some(2) + * ``` + * + * @see {@link findLastIndex} — search from the end + * @see {@link findFirst} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findFirstIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i)) { + return Option.some(i); + } + i++; + } + return Option.none(); +}))); +/** + * Returns the index of the last element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the last matching element from the end of an array. + * + * **Example** (Finding the last matching index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLastIndex([1, 3, 8, 9], (x) => x < 5) // => Option.some(1) + * ``` + * + * @see {@link findFirstIndex} — search from the start + * @see {@link findLast} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findLastIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + if (predicate(input[i], i)) { + return Option.some(i); + } + } + return Option.none(); +}))); +/** + * Returns the first element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to scan an iterable in iteration order and return the first selected + * element or mapped value as an `Option`. + * + * **Details** + * + * Accepts a predicate `(a, i) => boolean`, a refinement, or a function + * `(a, i) => Option` for simultaneous find-and-transform. If no element + * matches, this returns `Option.none()`. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some(4) + * ``` + * + * @see {@link findLast} — search from the end + * @see {@link findFirstIndex} — get the index instead + * @see {@link findFirstWithIndex} — get both element and index + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _Iterable_js__rspack_import_4/* .findFirst */.i8; +/** + * Returns the first selected value together with its index, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find both the first matching element and its index in one pass. + * + * **Details** + * + * Accepts a predicate, a refinement, or a function returning `Option`. For an + * `Option`-returning function, returns `[mappedValue, index]` for the first + * `Some`, or `Option.none()` if no element is selected. + * + * **Example** (Finding element with its index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some([4, 3]) + * ``` + * + * @see {@link findFirst} — get only the element + * @see {@link findFirstIndex} — get only the index + * + * @category searching + * @since 3.17.0 + */ +const findFirstWithIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some([a, i]); + } + } else { + if (Option.isSome(o)) { + return Option.some([o.value, i]); + } + } + i++; + } + return Option.none(); +}))); +/** + * Returns the last element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to find the last matching element from the end of an array. + * + * **Details** + * + * Searches from the end of the array. If no element matches, this returns + * `Option.none()`. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => Option.some(4) + * ``` + * + * @see {@link findFirst} — search from the start + * @see {@link findLastIndex} — get the index instead + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + const a = input[i]; + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some(a); + } + } else { + if (Option.isSome(o)) { + return o; + } + } + } + return Option.none(); +}))); +/** + * Inserts an element at the specified index safely, returning a new `NonEmptyArray` + * wrapped in an `Option`. + * + * **When to use** + * + * Use to insert a single element at a specific position in an array. + * + * **Details** + * + * Valid indices are `0` to `length`, inclusive. Inserting at `length` appends. + * + * **Example** (Inserting at an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.insertAt(["a", "b", "c", "e"], 3, "d") // => Option.some(["a", "b", "c", "d", "e"]) + * ``` + * + * @see {@link replace} — replace an existing element + * @see {@link modify} — transform an element at an index + * + * @category transforming + * @since 2.0.0 + */ +const insertAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => { + const out = Array.from(self); // copy because `splice` mutates the array + const index = Math.floor(i); + if (index !== out.length && isOutOfBounds(index, out)) { + return Option.none(); + } + out.splice(index, 0, b); + return Option.some(out); +}))); +/** + * Replaces the element at the specified index safely with a new value, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to set a fixed replacement value at a specific index. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Replacing an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.replace([1, 2, 3], 1, 4) // => Option.some([1, 4, 3]) + * ``` + * + * @see {@link modify} — transform an element with a function + * @see {@link insertAt} — insert without removing + * + * @category transforming + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => modify(self, i, () => b)))); +/** + * Applies a function to the element at the specified index safely, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to derive a replacement value from an array element at a specific index + * while leaving the other elements unchanged. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Modifying an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const values = [1, 2, 3, 4] + * const double = (n: number) => n * 2 + * + * Array.modify(values, 2, double) // => Option.some([1, 2, 6, 4]) + * Array.modify(values, 5, double) // => Option.none() + * ``` + * + * @see {@link replace} — set a fixed value at an index + * @see {@link modifyHeadNonEmpty} — modify the first element + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, f) => { + const arr = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, arr)) { + return Option.none(); + } + const out = arr; + const b = f(arr[index]); + out[index] = b; + return Option.some(out); +}))); +/** + * Removes the element at the specified index, returning a new array. If the + * index is out of bounds, returns a copy of the original. + * + * **When to use** + * + * Use when you want a missing index to be a no-op and need a fresh array result + * instead of an optional failure. + * + * **Example** (Removing an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.remove([1, 2, 3, 4], 2) // => [1, 2, 4] + * Array.remove([1, 2, 3, 4], 5) // => [1, 2, 3, 4] + * ``` + * + * @see {@link insertAt} — insert an element + * @see {@link filter} — remove elements by predicate + * + * @category transforming + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, i) => { + const out = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, out)) { + return out; + } + out.splice(index, 1); + return out; +}))); +/** + * Reverses an iterable into a new array. + * + * **When to use** + * + * Use to reverse an iterable into a new array without mutating the original + * input. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. + * + * **Example** (Reversing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reverse([1, 2, 3, 4]) // => [4, 3, 2, 1] + * ``` + * + * @category transforming + * @since 2.0.0 + */ +const reverse = self => Array.from(self).reverse(); +/** + * Sorts an array by the given `Order`, returning a new array. + * + * **When to use** + * + * Use to sort an array using a single `Order` comparator. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. Use `sortWith` to sort by a + * derived key, or `sortBy` for multi-key sorting. + * + * **Example** (Sorting numbers) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sort([3, 1, 4, 1, 5], Order.Number) // => [1, 1, 3, 4, 5] + * ``` + * + * @see {@link sortWith} — sort by a mapping function + * @see {@link sortBy} — sort by multiple orders + * + * @category sorting + * @since 2.0.0 + */ +const sort = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => { + const out = Array.from(self); + out.sort(O); + return out; +}))); +/** + * Sorts an array by a derived key using a mapping function and an `Order` for + * that key. + * + * **When to use** + * + * Use when you need to sort values by a derived key, such as a string length or + * object field, while keeping the original values. + * + * **Details** + * + * Equivalent to `sort(Order.mapInput(order, f))`, but more convenient. + * + * **Example** (Sorting strings by length) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sortWith(["aaa", "b", "cc"], (s) => s.length, Order.Number) // => ["b", "cc", "aaa"] + * ``` + * + * @see {@link sort} for sorting with an `Order` that compares the elements directly + * @see {@link sortBy} for sorting with multiple `Order`s applied in sequence + * + * @category sorting + * @since 2.0.0 + */ +const sortWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, f, order) => Array.from(self).map(a => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _)))); +/** + * Sorts an array by multiple `Order`s applied in sequence: the first order is + * used first; ties are broken by the second order, and so on. + * + * **When to use** + * + * Use to sort by multiple criteria where later orders break ties from earlier + * ones. + * + * **Details** + * + * This is data-last only and returns a function. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Sorting by multiple keys) + * + * ```ts import.meta.vitest + * import { Array, Order, pipe } from "effect" + * + * const users = [ + * { name: "Alice", age: 30 }, + * { name: "Bob", age: 25 }, + * { name: "Charlie", age: 30 } + * ] + * + * const sortedUsers = pipe( + * users, + * Array.sortBy( + * Order.mapInput(Order.Number, (user: (typeof users)[number]) => user.age), + * Order.mapInput(Order.String, (user: (typeof users)[number]) => user.name) + * ) + * ) + * + * sortedUsers.map((user) => user.name).join(",") // => "Bob,Alice,Charlie" + * ``` + * + * @see {@link sort} — sort by a single `Order` + * @see {@link sortWith} — sort by a derived key + * + * @category sorting + * @since 2.0.0 + */ +const sortBy = (...orders) => { + const sortByAll = sort(Order.combineAll(orders)); + return self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return sortByAll(input); + } + return []; + }; +}; +/** + * Pairs elements from two iterables by position. If the iterables differ in + * length, the extra elements from the longer one are discarded. + * + * **When to use** + * + * Use when you need simple pairs of corresponding elements from two iterables. + * + * **Details** + * + * Returns `NonEmptyArray` when both inputs are non-empty. + * + * **Example** (Zipping two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zip([1, 2, 3], ["a", "b"]) // => [[1, "a"], [2, "b"]] + * ``` + * + * @see {@link zipWith} — zip with a combiner function + * @see {@link unzip} — inverse operation + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Combines elements from two iterables pairwise using a function. If the + * iterables differ in length, extra elements are discarded. + * + * **When to use** + * + * Use when zipping two iterables in an array pipeline and each pair should + * become a computed array element instead of a tuple. + * + * **Example** (Zipping with addition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b) // => [5, 7, 9] + * ``` + * + * @see {@link zip} — zip into tuples + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => { + const as = fromIterable(self); + const bs = fromIterable(that); + if (isReadonlyArrayNonEmpty(as) && isReadonlyArrayNonEmpty(bs)) { + const out = [f(headNonEmpty(as), headNonEmpty(bs))]; + const len = Math.min(as.length, bs.length); + for (let i = 1; i < len; i++) { + out[i] = f(as[i], bs[i]); + } + return out; + } + return []; +}))); +/** + * Splits an array of pairs into two arrays. Inverse of {@link zip}. + * + * **Example** (Unzipping pairs) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unzip([[1, "a"], [2, "b"], [3, "c"]]) // => [[1, 2, 3], ["a", "b", "c"]] + * ``` + * + * @see {@link zip} — combine two arrays into pairs + * + * @category zipping + * @since 2.0.0 + */ +const unzip = self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const fa = [input[0][0]]; + const fb = [input[0][1]]; + for (let i = 1; i < input.length; i++) { + fa[i] = input[i][0]; + fb[i] = input[i][1]; + } + return [fa, fb]; + } + return [[], []]; +}; +/** + * Places a separator element between every pair of elements. + * + * **When to use** + * + * Use to insert a separator between elements, for example when preparing data for display or concatenation. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Empty inputs produce an empty + * result. + * + * **Example** (Interspersing a separator) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersperse([1, 2, 3], 0) // => [1, 0, 2, 0, 3] + * ``` + * + * @see {@link join} — intersperse and join into a string + * + * @category transforming + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const tail = tailNonEmpty(input); + for (let i = 0; i < tail.length; i++) { + if (i < tail.length) { + out.push(middle); + } + out.push(tail[i]); + } + return out; + } + return []; +}))); +/** + * Applies a function to the first element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use to transform the first element of a non-empty array while preserving the rest. + * + * **Example** (Modifying the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyHeadNonEmpty([1, 2, 3], (n) => n * 10) // => [10, 2, 3] + * ``` + * + * @see {@link setHeadNonEmpty} — replace with a fixed value + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 4.0.0 + */ +const modifyHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => [f(headNonEmpty(self)), ...tailNonEmpty(self)]))); +/** + * Replaces the first element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current first element. + * + * **Example** (Setting the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setHeadNonEmpty([1, 2, 3], 10) // => [10, 2, 3] + * ``` + * + * @see {@link modifyHeadNonEmpty} — transform the head with a function + * @see {@link setLastNonEmpty} — replace the last element + * + * @category transforming + * @since 4.0.0 + */ +const setHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyHeadNonEmpty(self, () => b)))); +/** + * Applies a function to the last element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use when you already know the array is non-empty and the new last element + * depends on the current last element. + * + * **Example** (Modifying the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyLastNonEmpty([1, 2, 3], (n) => n * 2) // => [1, 2, 6] + * ``` + * + * @see {@link setLastNonEmpty} — replace with a fixed value + * @see {@link modifyHeadNonEmpty} — modify the first element + * + * @category transforming + * @since 4.0.0 + */ +const modifyLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => append(initNonEmpty(self), f(lastNonEmpty(self)))))); +/** + * Replaces the last element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current last element. + * + * **Example** (Setting the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setLastNonEmpty([1, 2, 3], 4) // => [1, 2, 4] + * ``` + * + * @see {@link modifyLastNonEmpty} — transform the last element with a function + * @see {@link setHeadNonEmpty} — replace the first element + * + * @category transforming + * @since 4.0.0 + */ +const setLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyLastNonEmpty(self, () => b)))); +/** + * Transforms an array by rotating it `n` steps. Positive `n` rotates right; negative `n` + * rotates left. + * + * **When to use** + * + * Use when elements should wrap around the end of the array rather than being + * dropped. + * + * **Details** + * + * `n` is rounded to the nearest integer before rotating. The return type + * preserves `NonEmptyArray`. Empty arrays, or rotations normalized to `0`, + * return a copy. + * + * **Example** (Rotating elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.rotate(["a", "b", "c", "d"], 2) // => ["c", "d", "a", "b"] + * ``` + * + * @see {@link take} for taking a fixed number of elements from the start + * @see {@link drop} for dropping a fixed number of elements from the start + * + * @category transforming + * @since 2.0.0 + */ +const rotate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const len = input.length; + const m = Math.round(n) % len; + if (isOutOfBounds(Math.abs(m), input) || m === 0) { + return copy(input); + } + if (m < 0) { + const [f, s] = splitAtNonEmpty(input, -m); + return appendAll(s, f); + } else { + return rotate(input, m - len); + } + } + return []; +}))); +/** + * Returns a membership-test function using a custom equivalence. + * + * **When to use** + * + * Use when checking membership with caller-provided equality instead of + * `Equal.equivalence()`. + * + * **Example** (Checking with custom equality) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * const containsNumber = Array.containsWith((a: number, b: number) => a === b) + * + * pipe([1, 2, 3, 4], containsNumber(3)) // => true + * ``` + * + * @see {@link contains} for the `Equal.equivalence()` variant + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an array contains a value, using `Equal.equivalence()` for + * comparison. + * + * **When to use** + * + * Use to check whether an iterable contains a value using Effect's default + * equality instead of providing a comparison function. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe(["a", "b", "c", "d"], Array.contains("c")) // => true + * ``` + * + * @see {@link containsWith} — use custom equality + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Applies a function repeatedly to consume prefixes of the array and collect + * the values it produces. + * + * **When to use** + * + * Use when you need custom grouping logic where each step returns both a value + * and the remaining input. + * + * **Details** + * + * The function receives a `NonEmptyReadonlyArray` and returns `[value, rest]`. + * Processing continues until the remaining array is empty. + * + * **Example** (Chopping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chop([1, 2, 3, 4, 5], (as): [number, Array] => [as[0] * 2, as.slice(1)]) // => [2, 4, 6, 8, 10] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * @see {@link splitAt} — split at an index + * + * @category splitting + * @since 2.0.0 + */ +const chop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const [b, rest] = f(input); + const out = [b]; + let next = rest; + while (internalArray.isArrayNonEmpty(next)) { + const [b, rest] = f(next); + out.push(b); + next = rest; + } + return out; + } + return []; +}))); +/** + * Splits an iterable into two arrays at the given index. + * + * **When to use** + * + * Use to divide an array into a prefix and suffix at a specific position. + * + * **Details** + * + * `n` can be `0`, in which case all elements are placed in the second array. + * The index is floored to an integer. + * + * **Example** (Splitting at an index) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAt([1, 2, 3, 4, 5], 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link splitAtNonEmpty} — for non-empty arrays + * @see {@link splitWhere} — split at a predicate boundary + * + * @category splitting + * @since 2.0.0 + */ +const splitAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = Array.from(self); + const _n = Math.floor(n); + if (isReadonlyArrayNonEmpty(input)) { + if (_n >= 1) { + return splitAtNonEmpty(input, _n); + } + return [[], input]; + } + return [input, []]; +}))); +/** + * Splits a non-empty array into two parts at the given index. The first part + * is guaranteed to be non-empty (`n` is clamped to >= 1). + * + * **When to use** + * + * Use when downstream code requires the left side of the split to contain at + * least one element. + * + * **Example** (Splitting a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAtNonEmpty(["a", "b", "c", "d", "e"], 3) // => [["a", "b", "c"], ["d", "e"]] + * ``` + * + * @see {@link splitAt} — for possibly-empty arrays + * + * @category splitting + * @since 4.0.0 + */ +const splitAtNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const _n = Math.max(1, Math.floor(n)); + return _n >= self.length ? [copy(self), []] : [prepend(self.slice(1, _n), headNonEmpty(self)), self.slice(_n)]; +}))); +/** + * Splits an iterable into `n` roughly equal-sized chunks. + * + * **When to use** + * + * Use to distribute elements across a fixed number of groups, such as when splitting work across threads. + * + * **Details** + * + * Uses `chunksOf(ceil(length / n))` internally. The last chunk may be shorter. + * + * **Example** (Splitting into groups) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3) // => [[1, 2, 3], [4, 5, 6], [7, 8]] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * + * @category splitting + * @since 2.0.0 + */ +const split = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return chunksOf(input, Math.ceil(input.length / Math.floor(n))); +}))); +/** + * Splits an iterable at the first element matching the predicate. The matching + * element is included in the second array. + * + * **When to use** + * + * Use when you need to split an array at the first element that marks a + * condition boundary. + * + * **Example** (Splitting at a condition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link span} — splits at the first element that fails the predicate + * @see {@link splitAt} — split at a fixed index + * + * @category splitting + * @since 2.0.0 + */ +const splitWhere = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => span(self, (a, i) => !predicate(a, i))))); +/** + * Creates a shallow copy of an array. + * + * **When to use** + * + * Use to create a distinct array reference for an existing array, for example + * before mutating the returned array. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Use this when you need a distinct + * reference, for example before mutating the returned array. + * + * **Example** (Copying an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const original = [1, 2, 3] + * const copied = Array.copy(original) + * + * copied // => [1, 2, 3] + * original === copied // => false + * ``` + * + * @see {@link fromIterable} — returns the same reference for arrays + * + * @category transforming + * @since 2.0.0 + */ +const copy = self => self.slice(); +/** + * Pads or truncates an array to exactly `n` elements, filling with `fill` + * if the array is shorter, or slicing if longer. + * + * **When to use** + * + * Use to ensure an array has a specific length, padding with a fill value or truncating as needed. + * + * **Details** + * + * Returns an empty array when `n <= 0`. + * + * **Example** (Padding an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.pad([1, 2, 3], 6, 0) // => [1, 2, 3, 0, 0, 0] + * ``` + * + * @see {@link take} — truncate without padding + * @see {@link replicate} — create an array of a single repeated value + * + * @category transforming + * @since 3.8.4 + */ +const pad = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, n, fill) => { + if (self.length >= n) { + return take(self, n); + } + return appendAll(self, makeBy(n - self.length, () => fill)); +}))); +/** + * Splits an iterable into chunks of length `n`. The last chunk may be shorter + * if `n` does not evenly divide the length. + * + * **When to use** + * + * Use to divide an iterable into a new array of non-overlapping chunks with a + * maximum chunk size. + * + * **Details** + * + * `chunksOf(n)([])` is `[]`, not `[[]]`. Each chunk is a `NonEmptyArray`, and + * the outer return type preserves `NonEmptyArray`. + * + * **Example** (Chunking an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chunksOf([1, 2, 3, 4, 5], 2) // => [[1, 2], [3, 4], [5]] + * ``` + * + * @see {@link split} — split into a given number of groups + * @see {@link window} — sliding windows + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return chop(input, splitAtNonEmpty(n)); + } + return []; +}))); +/** + * Creates overlapping sliding windows of size `n`. + * + * **When to use** + * + * Use to process sequences with a moving window, such as for computing running averages or detecting patterns. + * + * **Details** + * + * Returns an empty array if `n <= 0` or the array has fewer than `n` elements. + * Each window is a tuple of exactly `n` elements. + * + * **Example** (Creating sliding windows) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const values = [1, 2, 3, 4, 5] + * + * Array.window(values, 3) // => [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + * Array.window(values, 6) // => [] + * ``` + * + * @see {@link chunksOf} — non-overlapping chunks + * + * @category splitting + * @since 3.13.2 + */ +const window = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (n > 0 && isReadonlyArrayNonEmpty(input)) { + return Array.from({ + length: input.length - (n - 1) + }, (_, index) => input.slice(index, index + n)); + } + return []; +}))); +/** + * Groups consecutive equal elements using a custom equivalence function. + * + * **When to use** + * + * Use when you already have a non-empty array arranged so matching elements are + * adjacent and need a custom equivalence function. + * + * **Details** + * + * Only adjacent elements are grouped. Non-adjacent duplicates stay separate. + * Requires a `NonEmptyReadonlyArray`. + * + * **Example** (Grouping consecutive equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.groupWith( + * ["a", "a", "b", "b", "b", "c", "a"], + * (x, y) => x === y + * ) // => [["a", "a"], ["b", "b", "b"], ["c"], ["a"]] + * ``` + * + * @see {@link group} for grouping adjacent elements with `Equal.equivalence()` + * @see {@link groupBy} for grouping all elements into a record by key, regardless of adjacency + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => chop(self, as => { + const h = headNonEmpty(as); + const out = [h]; + let i = 1; + for (; i < as.length; i++) { + const a = as[i]; + if (isEquivalent(a, h)) { + out.push(a); + } else { + break; + } + } + return [out, as.slice(i)]; +})))); +/** + * Groups consecutive equal elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you already have adjacent equal values and Effect's default equality + * is the right comparison. + * + * **Details** + * + * Only adjacent elements are grouped. + * + * **Example** (Grouping adjacent equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.group([1, 1, 2, 2, 2, 3, 1]) // => [[1, 1], [2, 2, 2], [3], [1]] + * ``` + * + * @see {@link groupWith} — use custom equality + * @see {@link groupBy} — group by a key function into a record + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups elements into a record by a key-returning function. Each key maps + * to a `NonEmptyArray` of elements that produced that key. + * + * **When to use** + * + * Use to build buckets of elements indexed by a computed string or symbol key. + * + * **Details** + * + * Unlike `group` and `groupWith`, elements do not need to be adjacent to be + * grouped together. The key function must return a `string` or `symbol`. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a property) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const people = [ + * { name: "Alice", group: "A" }, + * { name: "Bob", group: "B" }, + * { name: "Charlie", group: "A" } + * ] + * + * Object.keys(Array.groupBy(people, (person) => person.group)).join(",") // => "A,B" + * ``` + * + * @see {@link group} — group adjacent equal elements + * @see {@link groupWith} — group adjacent elements by custom equality + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const hashBucketsAdd = (buckets, value) => { + const hash = _Hash_js__rspack_import_5/* .hash */.tW(value); + const bucket = buckets.get(hash); + if (bucket === undefined) { + buckets.set(hash, [value]); + return true; + } + // Hash collisions still require an Effect equality check. + for (const previous of bucket) { + if (_Equal_js__rspack_import_6/* .equals */.aI(previous, value)) { + return false; + } + } + bucket.push(value); + return true; +}; +const makeHashBuckets = values => { + const buckets = new Map(); + for (const value of values) { + hashBucketsAdd(buckets, value); + } + return buckets; +}; +const hashBucketsHas = (buckets, value) => { + const bucket = buckets.get(Hash.hash(value)); + if (bucket === undefined) { + return false; + } + for (const candidate of bucket) { + if (Equal.equals(candidate, value)) { + return true; + } + } + return false; +}; +/** + * Computes the union of two arrays using a custom equivalence, removing + * duplicates. + * + * **When to use** + * + * Use when you need the union of two arrays but duplicate detection must use a + * custom equivalence instead of the default `Equal.equivalence()`. + * + * **Example** (Computing unions with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unionWith([1, 2], [2, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link union} for the `Equal.equivalence()` variant + * @see {@link intersectionWith} for keeping elements present in both arrays + * @see {@link differenceWith} for keeping elements present only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const unionWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, isEquivalent) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + if (isReadonlyArrayNonEmpty(b)) { + const dedupe = dedupeWith(isEquivalent); + return dedupe(appendAll(a, b)); + } + return a; + } + return b; +}))); +/** + * Computes the union of two arrays, removing duplicates using + * `Equal.equivalence()`. + * + * **Example** (Computing array unions) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.union([1, 2], [2, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link unionWith} — use custom equality + * @see {@link intersection} — elements in both arrays + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const union = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + return isReadonlyArrayNonEmpty(b) ? dedupe(appendAll(a, b)) : a; + } + return b; +}); +/** + * Computes the intersection of two arrays using a custom equivalence. Order is + * determined by the first array. + * + * **When to use** + * + * Use when you need to keep only values present in both arrays and equality + * must be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing intersections with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }] + * const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }] + * const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id + * + * Array.intersectionWith(isEquivalent)(array2)(array1) // => [{ id: 1 }, { id: 3 }] + * ``` + * + * @see {@link intersection} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link differenceWith} for keeping values only from the first array with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const intersectionWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => has(thatArray, a)); + }); +}; +/** + * Computes the intersection of two arrays using `Equal.equivalence()`. Order is + * determined by the first array. + * + * **When to use** + * + * Use when Effect equality is the right membership test and you want to keep + * values present in both inputs while preserving the first input's order. + * + * **Example** (Computing array intersections) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersection([1, 2, 3], [3, 4, 1]) // => [1, 3] + * ``` + * + * @see {@link intersectionWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0 || thatArray.length === 0) { + return []; + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => hashBucketsHas(buckets, value)); +}))); +/** + * Computes elements in the first array that are not in the second, using a + * custom equivalence. + * + * **When to use** + * + * Use when you need to keep only values from the first array and equality must + * be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing differences with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.differenceWith((a, b) => a === b)([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link difference} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link intersectionWith} for keeping values present in both arrays with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const differenceWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => !has(thatArray, a)); + }); +}; +/** + * Computes elements in the first array that are not in the second, using + * `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to keep values from the first array that are absent from + * the second and the default `Equal.equivalence()` comparison is appropriate. + * + * **Example** (Computing array differences) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.difference([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link differenceWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link intersection} — elements in both arrays + * + * @category set operations + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0) { + return []; + } + if (thatArray.length === 0) { + return selfArray.filter(() => true); + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => !hashBucketsHas(buckets, value)); +}))); +/** + * 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 + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => []; +/** + * Wraps a single value in a `NonEmptyArray`. + * + * **Example** (Creating a single-element array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.of(1) // => [1] + * ``` + * + * @see {@link make} — create from multiple values + * @see {@link empty} — create an empty array + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element using a function, returning a new array. + * + * **When to use** + * + * Use to transform each element independently while preserving the array shape. + * + * **Details** + * + * The function receives `(element, index)`. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Doubling values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6] + * ``` + * + * @see {@link flatMap} — map and flatten + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map(f)))); +/** + * Maps each element to an array and flattens the results into a single array. + * + * **When to use** + * + * Use to map each array element to zero or more values and concatenate the + * results in one pass. + * + * **Details** + * + * The function receives `(element, index)`. This returns `NonEmptyArray` when + * both the input and mapped arrays are non-empty. + * + * **Example** (Flat mapping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMap([1, 2, 3], (x) => [x, x * 2]) // => [1, 2, 2, 4, 3, 6] + * ``` + * + * @see {@link map} — transform without flattening + * @see {@link flatten} — flatten without mapping + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isReadonlyArrayEmpty(self)) { + return []; + } + const out = []; + for (let i = 0; i < self.length; i++) { + const inner = f(self[i], i); + for (let j = 0; j < inner.length; j++) { + out.push(inner[j]); + } + } + return out; +}))); +/** + * Flattens a nested array of arrays into a single array. + * + * **When to use** + * + * Use to collapse one level of nested arrays when no per-element mapping is + * needed. + * + * **Example** (Flattening nested arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatten([[1, 2], [], [3, 4], [], [5, 6]]) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @see {@link flatMap} — map then flatten in one step + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(identity))); +/** + * Extracts all `Some` values from an iterable of `Option`s, discarding `None`s. + * + * **When to use** + * + * Use to collect only present values from an iterable of `Option` values while + * discarding `None` values. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.getSomes([Option.some(1), Option.none(), Option.some(2)]) // => [1, 2] + * ``` + * + * @see {@link fromOption} — convert a single Option + * @see {@link getSuccesses} — extract successes from Results + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = []; + for (const a of self) { + if (Option.isSome(a)) { + out.push(a.value); + } + } + return out; +}; +/** + * Extracts all failure values from an iterable of `Result`s, discarding + * successes. + * + * **When to use** + * + * Use when you can drop the success channel and only need the failure + * payloads, not the original result wrappers. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getFailures([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => ["err"] + * ``` + * + * @see {@link getSuccesses} — extract success values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = []; + for (const a of self) { + if (Result.isFailure(a)) { + out.push(a.failure); + } + } + return out; +}; +/** + * Extracts all success values from an iterable of `Result`s, discarding + * failures. + * + * **When to use** + * + * Use when you can drop the failure channel and only need the success + * payloads, not the original result wrappers. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getSuccesses([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => [1, 2] + * ``` + * + * @see {@link getFailures} — extract failure values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = []; + for (const a of self) { + if (Result.isSuccess(a)) { + out.push(a.success); + } + } + return out; +}; +/** + * Keeps transformed values for elements where a `Filter` succeeds. + * + * **When to use** + * + * Use to filter an iterable with a `Result`-returning transformation while + * discarding failures. + * + * **Details** + * + * The filter receives `(element, index)`. Failures are discarded. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.filterMap([1, 2, 3, 4], (n) => n % 2 === 0 ? Result.succeed(n * 10) : Result.failVoid) // => [20, 40] + * ``` + * + * @see {@link filter} — keep original elements matching a predicate + * @see {@link partition} for keeping both failures and successes + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + const result = f(as[i], i); + if (Result.isSuccess(result)) { + out.push(result.success); + } + } + return out; +}))); +/** + * Keeps only elements satisfying a predicate (or refinement). + * + * **When to use** + * + * Use to filter an iterable into a new array of original elements that satisfy + * a boolean predicate or refinement. + * + * **Details** + * + * The predicate receives `(element, index)`. Refinements are supported for type + * narrowing. + * + * **Example** (Filtering even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.filter([1, 2, 3, 4], (x) => x % 2 === 0) // => [2, 4] + * ``` + * + * @see {@link partition} — split into matching and non-matching + * @see {@link filterMap} for transforming while filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + if (predicate(as[i], i)) { + out.push(as[i]); + } + } + return out; +}))); +/** + * Splits an iterable using a `Filter` into failures and successes. + * + * **When to use** + * + * Use to partition an iterable by evaluating each element with a + * `Result`-returning filter and keeping both failure and success values. + * + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a filter) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.partition([1, -2, 3], (n, i) => + * n > 0 ? Result.succeed(n + i) : Result.fail(`negative:${n}`) + * ) // => [["negative:-2"], [1, 5]] + * ``` + * + * @see {@link filter} — keep only matching elements + * @see {@link filterMap} for discarding failures + * @see {@link separate} — split an iterable of `Result` values + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, f) => { + const excluded = []; + const satisfying = []; + let i = 0; + for (const a of self) { + const result = f(a, i++); + if (_Result_js__rspack_import_7/* .isSuccess */.oJ(result)) { + satisfying.push(result.success); + } else { + excluded.push(result.failure); + } + } + return [excluded, satisfying]; +}); +/** + * Separates an iterable of `Result`s into failure values and success values. + * + * **When to use** + * + * Use to split an iterable of `Result` values into failure and success arrays. + * + * **Details** + * + * Returns `[failures, successes]`. This is equivalent to + * `partition(identity)`. + * + * **Example** (Separating Results) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.separate([Result.succeed(1), Result.fail("error"), Result.succeed(2)]) // => [["error"], [1, 2]] + * ``` + * + * @see {@link getFailures} — extract only failures + * @see {@link getSuccesses} — extract only successes + * @see {@link partition} for computing `Result` values while splitting + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Folds an iterable from left to right into a single value. + * + * **When to use** + * + * Use to combine all elements into one accumulated value from left to right. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Summing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduce([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduceRight} — fold from right to left + * @see {@link scan} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduce((b, a, i) => f(b, a, i), b)))); +/** + * Folds an iterable from right to left into a single value. + * + * **When to use** + * + * Use when you need to fold values from right to left. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Folding from right to left) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduce} — fold from left to right + * @see {@link scanRight} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduceRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduceRight((b, a, i) => f(b, a, i), b)))); +/** + * Lifts a predicate into an array: returns `[value]` if the predicate holds, + * `[]` otherwise. + * + * **Example** (Wrapping values conditionally) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const fromEven = Array.liftPredicate((n: number) => n % 2 === 0) + * + * fromEven(1) // => [] + * fromEven(2) // => [2] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = predicate => b => predicate(b) ? [b] : []; +/** + * Lifts an `Option`-returning function into one that returns an array: + * `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use when an optional parser or lookup should participate in array pipelines + * as zero-or-one results. + * + * **Example** (Lifting an Option function) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const parseNumber = Array.liftOption((s: string) => { + * const n = Number(s) + * return isNaN(n) ? Option.none() : Option.some(n) + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link liftPredicate} — lift a boolean predicate + * @see {@link liftResult} — lift a Result-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftOption = f => (...a) => fromOption(f(...a)); +/** + * Converts a nullable value to an array: `null`/`undefined` becomes `[]`, + * anything else becomes `[value]`. + * + * **When to use** + * + * Use to treat a nullable single value as zero or one array element. + * + * **Example** (Converting nullable values to an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromNullishOr(1) // => [1] + * Array.fromNullishOr(null) // => [] + * Array.fromNullishOr(undefined) // => [] + * ``` + * + * @see {@link liftNullishOr} — lift a nullable-returning function + * @see {@link fromOption} — convert from Option + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? empty() : [a]; +/** + * Lifts a nullable-returning function into one that returns an array: + * `null`/`undefined` becomes `[]`, anything else becomes `[value]`. + * + * **Example** (Lifting a nullable function) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const parseNumber = Array.liftNullishOr((s: string) => { + * const n = Number(s) + * return isNaN(n) ? null : n + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link fromNullishOr} — convert a single nullable value + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Maps each element with a nullable-returning function, keeping only non-null / + * non-undefined results. + * + * **When to use** + * + * Use when you need to map and filter in one step, where the mapper can return + * `null` or `undefined` to skip elements. + * + * **Example** (Flat mapping with nullable values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMapNullishOr([1, 2, 3], (n) => (n % 2 === 0 ? null : n)) // => [1, 3] + * ``` + * + * @see {@link flatMap} for mapping each element to an array and flattening + * @see {@link fromNullishOr} for converting a single nullable value to an array + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => fromNullishOr(f(a)))))); +/** + * Lifts a `Result`-returning function into one that returns an array: failures + * produce `[]`, successes produce `[value]`. + * + * **When to use** + * + * Use when a fallible parser or lookup should participate in array pipelines as + * zero-or-one results and the failure value should be discarded. + * + * **Example** (Lifting a Result function) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => + * isNaN(Number(s)) + * ? Result.fail(new Error("Not a number")) + * : Result.succeed(Number(s)) + * + * const liftedParseNumber = Array.liftResult(parseNumber) + * + * liftedParseNumber("42") // => [42] + * liftedParseNumber("not a number") // => [] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * @see {@link liftPredicate} — lift a boolean predicate + * + * @category lifting + * @since 4.0.0 + */ +const liftResult = f => (...a) => { + const e = f(...a); + return Result.isFailure(e) ? [] : [e.success]; +}; +/** + * Checks whether all elements satisfy the predicate. Supports refinements for + * type narrowing. + * + * **When to use** + * + * Use to check whether every array element satisfies a predicate, including + * refinement-based type narrowing. + * + * **Example** (Testing all elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.every([2, 4, 6], (x) => x % 2 === 0) // => true + * Array.every([2, 3, 6], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link some} — test if any element matches + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => self.every(refinement)))); +/** + * Checks whether at least one element satisfies the predicate. Narrows the type + * to `NonEmptyReadonlyArray` on success. + * + * **Example** (Testing for any match) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.some([1, 3, 4], (x) => x % 2 === 0) // => true + * Array.some([1, 3, 5], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link every} — test if all elements match + * @see {@link contains} — test for a specific value + * + * @category guards + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => self.some(predicate)))); +/** + * Applies a function to each suffix of the array (starting from each index), + * collecting the results. + * + * **When to use** + * + * Use when you need to compute a result from every suffix of an array, such as + * cumulative aggregations from each position. + * + * **Details** + * + * For index `i`, the function receives `self.slice(i)`. + * + * **Example** (Computing suffix lengths) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.extend([1, 2, 3], (as) => as.length) // => [3, 2, 1] + * ``` + * + * @see {@link scan} for keeping intermediate accumulator values during a fold + * + * @category mapping + * @since 2.0.0 + */ +const extend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map((_, i, as) => f(as.slice(i)))))); +/** + * Returns the minimum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the minimum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.min([3, 1, 2], Order.Number) // => 1 + * ``` + * + * @see {@link max} — find the maximum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.min(O))))); +/** + * Returns the maximum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the maximum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.max([3, 1, 2], Order.Number) // => 3 + * ``` + * + * @see {@link min} — find the minimum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.max(O))))); +/** + * Builds an array by repeatedly applying a function to a seed value. The + * function returns `Option.some([element, nextSeed])` to continue, or + * `Option.none()` to stop. + * + * **Example** (Generating a sequence) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.unfold(1, (n) => n <= 5 ? Option.some([n, n + 1]) : Option.none()) // => [1, 2, 3, 4, 5] + * ``` + * + * @see {@link makeBy} — generate from index + * @see {@link range} — generate a numeric range + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => { + const out = []; + let next = b; + while (true) { + const o = f(next); + if (Option.isNone(o)) { + break; + } + const [a, b] = o.value; + out.push(a); + next = b; + } + return out; +}; +/** + * Creates an `Order` for arrays based on an element `Order`. Arrays are + * compared element-wise; if all compared elements are equal, shorter arrays + * come first. + * + * **Example** (Comparing arrays) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * const arrayOrder = Array.makeOrder(Order.Number) + * + * arrayOrder([1, 2], [1, 3]) // => -1 + * ``` + * + * @see {@link makeEquivalence} — create an equivalence for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeOrder = _Order_js__rspack_import_8/* .Array */.O3; +/** + * Creates an `Equivalence` for arrays based on an element `Equivalence`. Two + * arrays are equivalent when they have the same length and all elements are + * pairwise equivalent. + * + * **Example** (Comparing arrays for equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const eq = Array.makeEquivalence((a, b) => a === b) + * + * eq([1, 2, 3], [1, 2, 3]) // => true + * ``` + * + * @see {@link makeOrder} — create an ordering for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = _Equivalence_js__rspack_import_9/* .Array */.O3; +/** + * Runs a side-effect for each element. The callback receives `(element, index)`. + * + * **When to use** + * + * Use to iterate over an array for side-effects only, when no transformed + * result is needed. + * + * **Example** (Iterating with side-effects) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const visited: Array = [] + * Array.forEach([1, 2, 3], (n) => visited.push(n)) + * + * visited // => [1, 2, 3] + * ``` + * + * @see {@link map} for transforming each element into a new array + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromIterable(self).forEach((a, i) => f(a, i))))); +/** + * Removes duplicates using a custom equivalence, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove all duplicate elements with a custom equivalence when default + * equality is not appropriate. + * + * **Example** (Deduplicating with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupe} — uses default equality + * @see {@link dedupeAdjacentWith} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const rest = tailNonEmpty(input); + for (const r of rest) { + if (out.every(a => !isEquivalent(r, a))) { + out.push(r); + } + } + return out; + } + return []; +}))); +/** + * Removes duplicates using `Equal.equivalence()`, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove repeated values from an iterable when Effect's default equality + * is the right comparison, preserving the first occurrence. + * + * **Example** (Removing duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupe([1, 2, 1, 3, 2, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link dedupeWith} — use custom equality + * @see {@link dedupeAdjacent} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupe = self => { + const input = fromIterable(self); + if (input.length < 2) { + return [...input]; + } + const buckets = new Map(); + const out = []; + for (const value of input) { + if (hashBucketsAdd(buckets, value)) { + out.push(value); + } + } + return out; +}; +/** + * Removes consecutive duplicate elements using a custom equivalence. + * + * **When to use** + * + * Use when consecutive duplicates should be collapsed using a custom + * equivalence, while equivalent values that appear later should remain in the + * result. + * + * **Details** + * + * Non-adjacent duplicates are preserved. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacent} — uses default equality + * @see {@link dedupeWith} — dedupes all duplicates, not just adjacent + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const out = []; + let lastA = Option.none(); + for (const a of self) { + if (Option.isNone(lastA) || !isEquivalent(a, lastA.value)) { + out.push(a); + lastA = Option.some(a); + } + } + return out; +}))); +/** + * Removes consecutive duplicate elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to collapse consecutive duplicates while preserving later + * non-consecutive repeats, and the default equality is sufficient. + * + * **Example** (Removing adjacent duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacent([1, 1, 2, 2, 3, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacentWith} — use custom equality + * @see {@link dedupe} — remove all duplicates + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Joins string elements with a separator. + * + * **Example** (Joining strings) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.join(["a", "b", "c"], "-") // => "a-b-c" + * ``` + * + * @see {@link intersperse} — insert separator elements without joining + * + * @category folding + * @since 2.0.0 + */ +const join = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sep) => fromIterable(self).join(sep)))); +/** + * Maps over an array while threading an accumulator through each step, returning both the final state and the mapped array. + * + * **When to use** + * + * Use when you need to map while threading state through each element and keep + * the final state. + * + * **Details** + * + * Combines `map` and `reduce` in a single pass. The callback receives the + * current state, element, and index, and returns `[nextState, mappedValue]`. + * The result is `[finalState, mappedArray]`. This can be used in both + * data-first and data-last style. + * + * **Example** (Running sum alongside mapped values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n]) // => [6, [1, 3, 6]] + * ``` + * + * @see {@link scan} — when you only need the accumulated results (not the final state) + * @see {@link reduce} — when you only need the final accumulated value + * + * @category folding + * @since 2.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, s, f) => { + let i = 0; + let s1 = s; + const out = []; + for (const a of self) { + const r = f(s1, a, i); + s1 = r[0]; + out.push(r[1]); + i++; + } + return [s1, out]; +}))); +/** + * Computes the cartesian product of two arrays, applying a combiner to each pair. + * + * **When to use** + * + * Use to compute every combination from two arrays and immediately transform + * each pair into a custom result. + * + * **Details** + * + * Produces every combination of an element from `self` with an element from + * `that`, so the result length is `self.length * that.length`. Iteration visits + * every element of `that` for each element of `self`. + * + * **Example** (Combining numbers and letters) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesianWith([1, 2], ["a", "b"], (a, b) => `${a}-${b}`) // => ["1-a", "1-b", "2-a", "2-b"] + * ``` + * + * @see {@link cartesian} for returning tuples instead of applying a combiner + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => flatMap(self, a => map(that, b => f(a, b)))))); +/** + * Computes the cartesian product of two arrays, returning all pairs as tuples. + * + * **When to use** + * + * Use when you need every `[a, b]` pair from two arrays as tuples. + * + * **Details** + * + * Produces every `[a, b]` combination of an element from `self` with an element + * from `that`, so the result length is `self.length * that.length`. + * + * **Example** (Generating all pairs from two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesian([1, 2], ["a", "b"]) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"]] + * ``` + * + * @see {@link cartesianWith} — apply a combiner to each pair + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do simulation" — an array comprehension pattern. + * + * **When to use** + * + * Use when you want array-comprehension style code with do notation. + * + * **Details** + * + * Use {@link bind} to introduce array variables and {@link let_ let} for plain + * values. Each `bind` produces the cartesian product of all bound variables, + * like nested loops. Use `filter` and `map` in the pipeline to add conditions + * and transformations. + * + * **Example** (Building array comprehensions with do notation) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 3, 5]), + * Array.bind("y", () => [2, 4, 6]), + * Array.filter(({ x, y }) => x < y), + * Array.map(({ x, y }) => [x, y] as const) + * ) // => [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]] + * ``` + * + * @see {@link bind} — introduce an array variable into the scope + * @see {@link bindTo} — start a pipeline by naming the first array + * @see {@link let_ let} — introduce a plain computed value + * + * @category constructors + * @since 3.2.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (of({}))); +/** + * Adds a new array variable to a do-notation scope, producing the cartesian product with all previous bindings. + * + * **When to use** + * + * Use to add another array-producing binding to an `Array.Do` pipeline, pairing + * each existing scope with every value returned by the callback. + * + * **Details** + * + * Each `bind` call adds a named property to the accumulated object. The + * callback receives the current scope and must return an array. This is + * equivalent to `flatMap` plus merging the new value into the scope object. + * + * **Example** (Binding two arrays) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 2]), + * Array.bind("y", () => ["a", "b"]) + * ) // => [{ x: 1, y: "a" }, { x: 1, y: "b" }, { x: 2, y: "a" }, { x: 2, y: "b" }] + * ``` + * + * @see {@link Do} — start a do-notation pipeline + * @see {@link bindTo} — name the first array in a pipeline + * @see {@link let_ let} — add a plain computed value + * + * @category sequencing + * @since 3.2.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bind(map, flatMap))); +/** + * Wraps each array element in an object with the given key, starting a do-notation scope. + * + * **When to use** + * + * Use when you already have an array and want to start a do-notation pipeline + * by naming each element. + * + * **Details** + * + * Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. This is an + * alternative to starting with `Do` plus `bind` when you already have an array. + * + * **Example** (Naming an existing array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.bindTo([1, 2, 3], "x") // => [{ x: 1 }, { x: 2 }, { x: 3 }] + * ``` + * + * @see {@link Do} — start with an empty scope + * @see {@link bind} — add another array variable to the scope + * + * @category mapping + * @since 3.2.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.let_(map))); + +const reducer = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make((a, b) => a.concat(b), []))); +/** + * Returns a `Reducer` that combines `ReadonlyArray` values by concatenation. + * + * @see {@link makeReducerConcat} — mutable `Array` variant + * + * @category folding + * @since 4.0.0 + */ +function getReadonlyReducerConcat() { + return reducer; +} +/** + * Returns a `Reducer` that combines `Array` values by concatenation. + * + * @see {@link getReadonlyReducerConcat} — readonly variant + * + * @category folding + * @since 4.0.0 + */ +function makeReducerConcat() { + return reducer; +} +/** + * Computes the number of elements in an iterable that satisfy a predicate. + * + * **When to use** + * + * Use when you need to count how many elements of an iterable satisfy a + * predicate. + * + * **Details** + * + * The predicate receives both the element and its index. Empty iterables return + * `0`. + * + * **Example** (Counting even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @see {@link filter} — when you need the matching elements, not just the count + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + const as = fromIterable(self); + for (let i = 0; i < as.length; i++) { + const a = as[i]; + if (f(a, i)) { + count++; + } + } + return count; +}))); +//# sourceMappingURL=Array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + CZ: isArrayNonEmpty, + ET: isReadonlyArrayNonEmpty, + Ie: empty, + KC: union, + Ts: fromIterable, + jB: partition, + of: of +}); + + +}, +"./node_modules/effect/dist/Cause.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/** + * Records the full reason an `Effect` failed. + * + * A `Cause` can contain typed failures, unexpected defects, interruptions, + * and annotations. Keeping those details together lets code inspect or format + * failures without first collapsing them to a single error value. This module + * includes the `Cause` and `Reason` data types, helpers for building and + * checking causes, and small error types used by several Effect APIs. + * + * @since 2.0.0 + */ + + + +/** + * Unique brand for `Cause` values, used for runtime type checks via {@link isCause}. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .CauseTypeId */.PX; +/** + * Unique brand for `Reason` values, used for runtime type checks via {@link isReason}. + * + * @category type IDs + * @since 4.0.0 + */ +const ReasonTypeId = _internal_core_js__rspack_import_0/* .CauseReasonTypeId */.B4; +/** + * Checks whether an arbitrary value is a `Cause`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isCause(Cause.fail("error")) // => true + * Cause.isCause("not a cause") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isCause = _internal_core_js__rspack_import_0/* .isCause */.Aj; +/** + * Checks whether an arbitrary value is a `Reason` (`Fail`, `Die`, or `Interrupt`). + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reason = Cause.fail("error").reasons[0] + * Cause.isReason(reason) // => true + * Cause.isReason("not a reason") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isReason = _internal_core_js__rspack_import_0/* .isCauseReason */.Wg; +/** + * Narrows a `Reason` to `Fail`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering fail reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const fails = cause.reasons.filter(Cause.isFailReason) + * fails[0].error // => "error" + * ``` + * + * @see {@link isDieReason} — narrow to `Die` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isFailReason = _internal_core_js__rspack_import_0/* .isFailReason */.lC; +/** + * Narrows a `Reason` to `Die`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Die` (defect) reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering die reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.die("defect") + * const dies = cause.reasons.filter(Cause.isDieReason) + * dies[0].defect // => "defect" + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isDieReason = _internal_core_js__rspack_import_0/* .isDieReason */.Xb; +/** + * Narrows a `Reason` to `Interrupt`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Interrupt` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering interrupt reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.interrupt(123) + * const interrupts = cause.reasons.filter(Cause.isInterruptReason) + * interrupts[0].fiberId // => 123 + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isDieReason} — narrow to `Die` + * + * @category guards + * @since 4.0.0 + */ +const isInterruptReason = _internal_core_js__rspack_import_0/* .isInterruptReason */.ik; +/** + * Creates a `Cause` from an array of `Reason` values. + * + * **When to use** + * + * Use when you already have individual reasons (e.g. from filtering or + * transforming another cause's `reasons` array) and need to wrap them back + * into a `Cause`. + * + * **Details** + * + * - Returns a new `Cause`. + * - An empty array produces a cause equivalent to `empty`. + * + * **Gotchas** + * + * The `reasons` array is stored as provided. Treat the array as immutable + * after passing it to this function. + * + * **Example** (Building a cause from reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reasons = [ + * Cause.makeFailReason("err1"), + * Cause.makeFailReason("err2") + * ] + * Cause.fromReasons(reasons) // => Cause.combine(Cause.fail("err1"), Cause.fail("err2")) + * ``` + * + * @see {@link combine} — merge two existing causes + * + * @category constructors + * @since 4.0.0 + */ +const fromReasons = _internal_core_js__rspack_import_0/* .causeFromReasons */.b5; +/** + * Represents a `Cause` with an empty `reasons` array. + * + * **When to use** + * + * Use to represent the absence of failure when constructing or combining + * causes. + * + * **Details** + * + * Represents the absence of failure. Combining any cause with `empty` via + * {@link combine} returns the original cause unchanged. + * + * **Example** (Combining with the empty cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.combine(Cause.empty, Cause.fail("boom")) // => Cause.fail("boom") + * ``` + * + * @see {@link combine} for merging causes where `empty` acts as the identity + * + * @category constructors + * @since 2.0.0 + */ +const empty = _internal_core_js__rspack_import_0/* .causeEmpty */.DH; +/** + * Creates a `Cause` containing a single `Fail` reason with the + * given typed error. + * + * **When to use** + * + * Use to construct a cause from an expected typed error. + * + * **Example** (Creating a fail cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.fail("Something went wrong") // => Cause.fromReasons([Cause.makeFailReason("Something went wrong")]) + * ``` + * + * @see {@link die} — for untyped defects + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .causeFail */.OE; +/** + * Creates a `Cause` containing a single `Die` reason with the + * given defect. + * + * **When to use** + * + * Use to construct a cause from an untyped defect or unexpected thrown value. + * + * **Example** (Creating a die cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .causeDie */.Iu; +/** + * Creates a `Cause` containing a single `Interrupt` reason, + * optionally carrying the interrupting fiber's ID. + * + * **Example** (Creating an interrupt cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.interrupt(123) // => Cause.fromReasons([Cause.makeInterruptReason(123)]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link die} — for untyped defects + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .causeInterrupt */.nIy; +/** + * Creates a standalone `Fail` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone typed failure reason for + * {@link fromReasons} or direct comparison. + * + * **Example** (Creating a Fail reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeFailReason("error") // => Cause.fail("error").reasons[0] + * ``` + * + * @see {@link makeDieReason} — create a `Die` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeFailReason = error => new core.Fail(error); +/** + * Creates a standalone `Die` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone defect reason for {@link fromReasons} or + * direct comparison. + * + * **Example** (Creating a Die reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeDieReason("bug") // => Cause.die("bug").reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeDieReason = defect => new core.Die(defect); +/** + * Creates a standalone `Interrupt` reason (not wrapped in a `Cause`), + * optionally carrying the interrupting fiber's ID. + * + * **When to use** + * + * Use when constructing a standalone interrupt reason for {@link fromReasons} + * or direct comparison. + * + * **Example** (Creating an Interrupt reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeInterruptReason(42) // => Cause.interrupt(42).reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeDieReason} — create a `Die` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeInterruptReason = _internal_effect_js__rspack_import_1/* .makeInterruptReason */.ORc; +/** + * Returns `true` if every reason in the cause is an `Interrupt` (and + * there is at least one reason). + * + * **When to use** + * + * Use when you need to detect failures caused only by interruption. + * + * **Example** (Checking interrupt-only causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterruptsOnly(Cause.interrupt(123)) // => true + * Cause.hasInterruptsOnly(Cause.fail("error")) // => false + * Cause.hasInterruptsOnly(Cause.empty) // => false + * ``` + * + * @see {@link hasInterrupts} — `true` if the cause contains *any* interrupts + * + * @category predicates + * @since 4.0.0 + */ +const hasInterruptsOnly = _internal_effect_js__rspack_import_1/* .hasInterruptsOnly */.nn5; +/** + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** + * + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. + * + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. + * + * **Example** (Mapping errors to uppercase) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const mapped = Cause.map(cause, (e) => e.toUpperCase()) + * const reason = mapped.reasons[0] + * if (Cause.isFailReason(reason)) { + * reason.error // => "ERROR" + * } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .causeMap */.O$X; +/** + * Merges two causes into a single cause whose `reasons` array is the union + * of both inputs (de-duplicated by value equality). + * + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. + * - If the result is structurally equal to `self`, `self` is returned + * (referential shortcut). + * + * **Example** (Combining two causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const combined = Cause.combine(Cause.fail("error1"), Cause.fail("error2")) + * combined // => Cause.fromReasons([Cause.makeFailReason("error1"), Cause.makeFailReason("error2")]) + * ``` + * + * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining + * + * @category combining + * @since 4.0.0 + */ +const combine = _internal_effect_js__rspack_import_1/* .causeCombine */.h2c; +/** + * Collapses a `Cause` into a single `unknown` value, picking the "most + * important" failure in this order: + * + * **When to use** + * + * Use to collapse a structured cause to the single value that synchronous and + * promise runners would throw. + * + * **Details** + * + * 1. First `Fail` error (the `E` value) + * 2. First `Die` defect + * 3. A generic `Error("All fibers interrupted without error")` for interrupt-only causes + * 4. A generic `Error("Empty cause")` for `empty` + * + * This is the function used by `Effect.runPromise` and `Effect.runSync` to + * decide what to throw. + * + * **Gotchas** + * + * This function is lossy. Use {@link prettyErrors} or iterate `cause.reasons` + * when you need all failures. + * + * **Example** (Squashing a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.squash(Cause.fail("error")) // => "error" + * Cause.squash(Cause.die("defect")) // => "defect" + * ``` + * + * @see {@link prettyErrors} — non-lossy conversion to `Array` + * @see {@link pretty} — human-readable string rendering + * + * @category destructors + * @since 2.0.0 + */ +const squash = _internal_effect_js__rspack_import_1/* .causeSquash */.ReC; +/** + * Returns `true` if the cause contains at least one `Fail` reason. + * + * **When to use** + * + * Use to check whether a cause includes typed failures before extracting, + * mapping, or rendering them. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasFails(Cause.fail("error")) // => true + * Cause.hasFails(Cause.die("defect")) // => false + * ``` + * + * @see {@link hasDies} — check for defects + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .hasFails */.myX; +/** + * Returns a `Result` whose success value is the first `Fail` reason in + * the cause, including its annotations. If the cause has no `Fail` reason, the + * failure value is the original cause narrowed to `Cause`, because it + * contains no typed error reasons. + * + * **When to use** + * + * Use when you need the full `Fail` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Fail reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findFail(Cause.fail("error")) // => Result.succeed(Cause.makeFailReason("error")) + * ``` + * + * @see {@link findError} — extract the unwrapped `E` value + * @see {@link findDie} — extract the first `Die` reason + * + * @category filtering + * @since 4.0.0 + */ +const findFail = _internal_effect_js__rspack_import_1/* .findFail */.QE5; +/** + * Returns a `Result` whose success value is the first typed error value `E` + * from a `Fail` reason in the cause. If the cause has no `Fail` reason, + * the failure value is the original cause narrowed to `Cause`, because + * it contains no typed error reasons. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as a `Result` + * that preserves the original cause when no match is found. + * + * **Example** (Extracting the first error value) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findError(Cause.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link findFail} — extract the full `Fail` reason + * @see {@link findErrorOption} — `Option`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .findError */.khU; +/** + * Returns the first typed error value `E` from a cause wrapped in + * `Option.some`, or `Option.none` if no `Fail` reason exists. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as an `Option`, + * discarding the original cause. + * + * **Example** (Extracting an error as Option) + * + * ```ts import.meta.vitest + * import { Cause, Option } from "effect" + * + * Cause.findErrorOption(Cause.fail("error")) // => Option.some("error") + * Cause.findErrorOption(Cause.die("defect")) // => Option.none() + * ``` + * + * @see {@link findError} — `Result`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .findErrorOption */.L$u; +/** + * Returns `true` if the cause contains at least one `Die` reason. + * + * **When to use** + * + * Use to check whether a cause includes defects before extracting or rendering + * them. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasDies(Cause.die("defect")) // => true + * Cause.hasDies(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasFails} — check for typed errors + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .hasDies */.gpn; +/** + * Returns a `Result` whose success value is the first `Die` reason in + * the cause, including its annotations. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the full `Die` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Die reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDie(Cause.die("defect")) // => Result.succeed(Cause.makeDieReason("defect")) + * ``` + * + * @see {@link findDefect} — extract the unwrapped defect value + * @see {@link findFail} — extract the first `Fail` reason + * + * @category filtering + * @since 4.0.0 + */ +const findDie = _internal_effect_js__rspack_import_1/* .findDie */.k7S; +/** + * Returns a `Result` whose success value is the first defect value from a + * `Die` reason in the cause. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the first defect value from a `Cause` as a `Result`, + * without the full `Die` reason. + * + * **Example** (Extracting the first defect) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDefect(Cause.die("defect")) // => Result.succeed("defect") + * ``` + * + * @see {@link findDie} — extract the full `Die` reason + * @see {@link findError} — extract the first typed error + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .findDefect */.BbX; +/** + * Returns `true` if the cause contains at least one `Interrupt` reason. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterrupts(Cause.interrupt(123)) // => true + * Cause.hasInterrupts(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasInterruptsOnly} — `true` only when *all* reasons are interrupts + * @see {@link hasFails} — check for typed errors + * @see {@link hasDies} — check for defects + * + * @category predicates + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .hasInterrupts */.prj; +/** + * Returns a `Result` whose success value is the first `Interrupt` reason + * in the cause, including its annotations. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need the first `Interrupt` reason from a `Cause`, including the + * fiber ID and annotations. + * + * **Example** (Extracting the first interrupt) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findInterrupt(Cause.interrupt(42)) // => Result.succeed(Cause.makeInterruptReason(42)) + * ``` + * + * @see {@link interruptors} — collect all interrupting fiber IDs as a `Set` + * + * @category filtering + * @since 4.0.0 + */ +const findInterrupt = _internal_effect_js__rspack_import_1/* .findInterrupt */.tU5; +/** + * Collects the defined fiber IDs from all `Interrupt` reasons in the + * cause into a `ReadonlySet`. Interrupt reasons without a `fiberId` are + * ignored. Returns an empty set when the cause has no interrupting fiber IDs. + * + * **When to use** + * + * Use when you need interrupting fiber IDs as a set, with absence represented + * as an empty set. + * + * **Example** (Collecting interruptors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.combine( + * Cause.interrupt(1), + * Cause.interrupt(2) + * ) + * + * Cause.interruptors(cause) // => new Set([1, 2]) + * ``` + * + * @see {@link filterInterruptors} — `Result`-based variant + * + * @category getters + * @since 2.0.0 + */ +const interruptors = _internal_effect_js__rspack_import_1/* .causeInterruptors */.h74; +/** + * Returns a `Result` whose success value is the set of defined fiber IDs from + * the cause's `Interrupt` reasons. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need absence of interrupt reasons to fail with the original + * cause. + * + * **Gotchas** + * + * Interrupt reasons without a `fiberId` still count as interrupts, so the + * function succeeds with an empty `Set` when every interrupt reason has an + * undefined fiber ID. + * + * **Example** (Extracting interruptors with Result) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.filterInterruptors(Cause.interrupt(1)) // => Result.succeed(new Set([1])) + * ``` + * + * @see {@link interruptors} — always-succeeding variant + * + * @category filtering + * @since 4.0.0 + */ +const filterInterruptors = _internal_effect_js__rspack_import_1/* .causeFilterInterruptors */.Bou; +/** + * Converts a `Cause` into an `Array` suitable for logging or + * rethrowing. + * + * **When to use** + * + * Use to convert every renderable failure in a cause into individual `Error` + * values before logging or rethrowing. + * + * **Details** + * + * Each `Fail` and `Die` reason is converted into a standard + * `Error`: + * + * - **Objects / Error instances** — `message`, `name`, `stack`, and `cause` + * are preserved. Extra enumerable properties are copied. Stack traces are + * cleaned up and enriched with span annotations when available. + * - **Strings** — used directly as the `Error` message. + * - **Other primitives** (`null`, `undefined`, numbers, …) — wrapped in an + * `Error` with message `"Unknown error: "`. + * + * `Interrupt` reasons are collected separately. If the cause contains + * **only** interrupts (no `Fail` or `Die`), a single `InterruptError` is + * returned whose `cause` lists the interrupting fiber IDs. + * + * An empty cause returns an empty array. + * + * **Example** (Converting a cause to errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.prettyErrors(Cause.fail(new Error("boom")))[0].message // => "boom" + * ``` + * + * @see {@link pretty} — renders the cause as a single string + * @see {@link squash} — lossy collapse to a single thrown value + * + * @category formatting + * @since 3.2.0 + */ +const prettyErrors = _internal_effect_js__rspack_import_1/* .causePrettyErrors */.RJ6; +/** + * Formats a `Cause` as a human-readable string for logging or debugging. + * + * **When to use** + * + * Use to render a whole cause as one human-readable string for logs or + * diagnostics. + * + * **Details** + * + * Delegates to {@link prettyErrors} to convert each reason to an `Error`, + * then joins their stack traces with newlines. Nested `Error.cause` chains + * are rendered inline with indentation: + * + * ```text + * ErrorName: message + * at ... + * at ... { + * [cause]: NestedError: message + * at ... + * } + * ``` + * + * Span annotations are appended to the relevant stack frames when available. + * + * **Gotchas** + * + * Rendering an empty cause produces an empty string because there are no + * errors to render. + * + * **Example** (Rendering a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.pretty(Cause.fail("something went wrong")).includes("something went wrong") // => true + * ``` + * + * @see {@link prettyErrors} — get the individual `Error` instances + * + * @category formatting + * @since 2.0.0 + */ +const pretty = _internal_effect_js__rspack_import_1/* .causePretty */.GyP; +/** + * Checks whether an arbitrary value is a `NoSuchElementError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isNoSuchElementError(new Cause.NoSuchElementError()) // => true + * Cause.isNoSuchElementError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isNoSuchElementError = _internal_core_js__rspack_import_0/* .isNoSuchElementError */.PW; +/** + * Unique brand for `NoSuchElementError`. + * + * @category type IDs + * @since 4.0.0 + */ +const NoSuchElementErrorTypeId = _internal_core_js__rspack_import_0/* .NoSuchElementErrorTypeId */.qB; +/** + * Constructs a `NoSuchElementError` with an optional message. + * + * **When to use** + * + * Use to create the error value for APIs that intentionally fail when an + * expected element is absent. + * + * **Example** (Creating a NoSuchElementError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.NoSuchElementError("Element not found").message // => "Element not found" + * ``` + * + * @see {@link isNoSuchElementError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const NoSuchElementError = _internal_core_js__rspack_import_0/* .NoSuchElementError */.Xm; +/** + * Checks whether an arbitrary value is a `Done` signal. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isDone(Cause.Done()) // => true + * Cause.isDone("not done") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isDone = _internal_core_js__rspack_import_0/* .isDone */.$L; +/** + * Unique brand for `Done` values. + * + * @category type IDs + * @since 4.0.0 + */ +const DoneTypeId = _internal_core_js__rspack_import_0/* .DoneTypeId */.q_; +/** + * Creates a `Done` signal with an optional value. + * + * **When to use** + * + * Use when you need to construct a low-level pull completion signal directly. + * + * @see {@link done} — create a failing `Effect` with `Done` + * + * @category constructors + * @since 4.0.0 + */ +const Done = _internal_core_js__rspack_import_0/* .Done */.RS; +/** + * Creates an Effect that fails with a `Done` error. Shorthand for + * `Effect.fail(Cause.Done(value))`. + * + * **When to use** + * + * Use when you model stream or queue completion through the error channel. + * + * **Example** (Failing with Done) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const program = Cause.done("finished") + * + * await Effect.runPromiseExit(program) // => Exit.fail(Cause.Done("finished")) + * ``` + * + * @see {@link Done} — create the signal value without an Effect + * + * @category constructors + * @since 4.0.0 + */ +const done = _internal_core_js__rspack_import_0/* .done */.Vw; +/** + * Unique brand for `TimeoutError`. + * + * @category type IDs + * @since 4.0.0 + */ +const TimeoutErrorTypeId = _internal_effect_js__rspack_import_1/* .TimeoutErrorTypeId */.DQo; +/** + * Checks whether an arbitrary value is a `TimeoutError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isTimeoutError(new Cause.TimeoutError()) // => true + * Cause.isTimeoutError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isTimeoutError = _internal_effect_js__rspack_import_1/* .isTimeoutError */.c8t; +/** + * Constructs a `TimeoutError` with an optional message. + * + * **Example** (Creating a TimeoutError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.TimeoutError("Operation timed out").message // => "Operation timed out" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const TimeoutError = _internal_effect_js__rspack_import_1/* .TimeoutError */.MUS; +/** + * Unique brand for `IllegalArgumentError`. + * + * @category type IDs + * @since 4.0.0 + */ +const IllegalArgumentErrorTypeId = _internal_effect_js__rspack_import_1/* .IllegalArgumentErrorTypeId */.t8c; +/** + * Checks whether an arbitrary value is an `IllegalArgumentError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isIllegalArgumentError(new Cause.IllegalArgumentError()) // => true + * Cause.isIllegalArgumentError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isIllegalArgumentError = _internal_effect_js__rspack_import_1/* .isIllegalArgumentError */._y; +/** + * Constructs an `IllegalArgumentError` with an optional message. + * + * **Example** (Creating an IllegalArgumentError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.IllegalArgumentError("Invalid argument").message // => "Invalid argument" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const IllegalArgumentError = _internal_effect_js__rspack_import_1/* .IllegalArgumentError */.qwd; +/** + * Checks whether an arbitrary value is an `ExceededCapacityError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isExceededCapacityError(new Cause.ExceededCapacityError()) // => true + * Cause.isExceededCapacityError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isExceededCapacityError = _internal_effect_js__rspack_import_1/* .isExceededCapacityError */.ASO; +/** + * Unique brand for `ExceededCapacityError`. + * + * @category type IDs + * @since 4.0.0 + */ +const ExceededCapacityErrorTypeId = _internal_effect_js__rspack_import_1/* .ExceededCapacityErrorTypeId */.F7W; +/** + * Constructs an `ExceededCapacityError` with an optional message. + * + * **When to use** + * + * Use to create the error value for bounded-resource capacity failures. + * + * **Example** (Creating an ExceededCapacityError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.ExceededCapacityError("Queue full").message // => "Queue full" + * ``` + * + * @see {@link isExceededCapacityError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const ExceededCapacityError = _internal_effect_js__rspack_import_1/* .ExceededCapacityError */.Aub; +/** + * Unique brand present on `AsyncFiberError` values and used by + * `isAsyncFiberError` for runtime checks. + * + * @category type IDs + * @since 4.0.0 + */ +const AsyncFiberErrorTypeId = _internal_effect_js__rspack_import_1/* .AsyncFiberErrorTypeId */.cOF; +/** + * Checks whether an arbitrary value is an `AsyncFiberError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * const error = new Cause.AsyncFiberError(fiber) + * Cause.isAsyncFiberError(error) // => true + * Cause.isAsyncFiberError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isAsyncFiberError = _internal_effect_js__rspack_import_1/* .isAsyncFiberError */.Rft; +/** + * Constructs an `AsyncFiberError` for a fiber that could not be resolved + * synchronously. + * + * **When to use** + * + * Use to create the error value for a fiber that could not be completed by a + * synchronous runner. + * + * **Example** (Creating an AsyncFiberError) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * new Cause.AsyncFiberError(fiber).message // => "An asynchronous Effect was executed with Effect.runSync" + * ``` + * + * @see {@link isAsyncFiberError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const AsyncFiberError = _internal_effect_js__rspack_import_1/* .AsyncFiberError */.RD4; +/** + * Unique brand for `UnknownError`. + * + * @category type IDs + * @since 4.0.0 + */ +const UnknownErrorTypeId = _internal_effect_js__rspack_import_1/* .UnknownErrorTypeId */.Kkt; +/** + * Checks whether an arbitrary value is an `UnknownError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isUnknownError(new Cause.UnknownError("x")) // => true + * Cause.isUnknownError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isUnknownError = _internal_effect_js__rspack_import_1/* .isUnknownError */.PnV; +/** + * Constructs an `UnknownError`. The first argument is the original + * cause (stored in `Error.cause`); the second is an optional human-readable + * message. + * + * **Example** (Creating an UnknownError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.UnknownError({ raw: true }, "Unexpected value").message // => "Unexpected value" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const UnknownError = _internal_effect_js__rspack_import_1/* .UnknownError */.Bk6; +/** + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** + * + * Annotations are stored as a `Context` on each reason and can be + * retrieved later via {@link reasonAnnotations} or {@link annotations}. + * The runtime uses this to attach stack traces and spans. + * + * - Returns a new `Cause`. + * - By default, existing keys are preserved. Pass `{ overwrite: true }` to + * replace them. + * + * **Example** (Annotating a cause) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const annotated = Cause.annotate(Cause.fail("error"), Context.make(RequestId, "req-1")) + * Context.getOrUndefined(Cause.annotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotate = _internal_core_js__rspack_import_0/* .causeAnnotate */.Eh; +/** + * Reads the annotations from a single `Reason` as a `Context`. + * + * **When to use** + * + * Use when you need tracing metadata (e.g. `StackTrace`) from + * a specific reason rather than the whole cause. + * + * **Example** (Reading reason annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const reason = Cause.makeFailReason("error") + * const annotated = reason.annotate(Context.make(RequestId, "req-1")) + * + * Context.getOrUndefined(Cause.reasonAnnotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} — merged annotations from all reasons in a cause + * + * @category annotations + * @since 4.0.0 + */ +const reasonAnnotations = _internal_effect_js__rspack_import_1/* .reasonAnnotations */.tQ6; +/** + * Reads the merged annotations from all reasons in a `Cause`. + * + * **When to use** + * + * Use to read diagnostic metadata merged from the whole cause. + * + * **Gotchas** + * + * When multiple reasons contain the same annotation key, the value from the + * later reason wins. + * + * **Example** (Reading merged annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const cause = Cause.annotate( + * Cause.fail("error"), + * Context.make(RequestId, "req-1") + * ) + * + * Context.getOrUndefined(Cause.annotations(cause), RequestId) // => "req-1" + * ``` + * + * @see {@link reasonAnnotations} — annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotations = _internal_effect_js__rspack_import_1/* .causeAnnotations */.On5; +/** + * Context annotation used to store the stack frame captured at the point of failure. + * + * **When to use** + * + * Use to read the failure stack-frame annotation from a `Reason` when building + * diagnostics, logging, or custom cause renderers. + * + * **Details** + * + * The runtime annotates every reason with this when a stack frame is + * available. Retrieve it via + * `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`. + * + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link InterruptorStackTrace} for the interrupt-specific stack-frame annotation + * + * @category services + * @since 4.0.0 + */ +class StackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/StackTrace"))) {} +/** + * Context annotation used to store the stack frame captured at the point of + * interruption. + * + * **When to use** + * + * Use when you need the stack-frame annotation used by interrupt-only cause + * rendering. + * + * **Details** + * + * Similar to `StackTrace` but specific to `Interrupt` reasons. + * + * @see {@link StackTrace} for stack frames attached to failures + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotate} for attaching annotations to a cause + * + * @category services + * @since 4.0.0 + */ +class InterruptorStackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/InterruptorStackTrace"))) {} +//# sourceMappingURL=Cause.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + $L: isDone, + Vw: done, + iw: squash, + kO: fromReasons, + nn: hasInterruptsOnly +}); + + +}, +"./node_modules/effect/dist/Channel.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Cause_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var _Exit_js__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var _Fiber_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Fiber.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_13 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Iterable_js__rspack_import_15 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Latch_js__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Latch.js"); +/* import */ var _MutableRef_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/MutableRef.js"); +/* import */ var _Pipeable_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Pull_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Pull.js"); +/* import */ var _Queue_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Queue.js"); +/* import */ var _Result_js__rspack_import_16 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/* import */ var _Scope_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Scope.js"); +/* import */ var _Semaphore_js__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/Semaphore.js"); +/** + * Provides low-level building blocks for streaming data through Effect. + * + * A `Channel` can read input elements, write output elements, fail with a typed + * error, and finish with a typed result while managing resources safely. + * Streams and sinks are built on channels, so most application code uses those + * higher-level modules instead. This module is useful when implementing stream + * operators or specialized streaming workflows. + * + * @since 2.0.0 + */ +// @effect-diagnostics returnEffectInGen:off + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * Runtime identifier stored on `Channel` values and used by `isChannel` to + * recognize them. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = "~effect/Channel"; +/** + * Checks whether a value is a `Channel`. + * + * **Example** (Checking for channels) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * const channel = Channel.succeed(42) + * Channel.isChannel(channel) // => true + * Channel.isChannel("not a channel") // => false + * ``` + * + * @category guards + * @since 3.5.4 + */ +const isChannel = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +const ChannelProto = { + [TypeId]: { + _Env: _Function_js__rspack_import_1/* .identity */.D_, + _InErr: _Function_js__rspack_import_1/* .identity */.D_, + _InElem: _Function_js__rspack_import_1/* .identity */.D_, + _OutErr: _Function_js__rspack_import_1/* .identity */.D_, + _OutElem: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_2/* .pipeArguments */.tT)(this, arguments); + } +}; +// ----------------------------------------------------------------------------- +// Constructors +// ----------------------------------------------------------------------------- +/** + * Creates a `Channel` from a transformation function that operates on upstream pulls. + * + * **Example** (Creating channels from transforms) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromTransform((upstream, scope) => + * Effect.succeed(upstream) + * ) + * await Effect.runPromise(Channel.runCollect(channel)) // => [] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromTransform = transform => { + const self = Object.create(ChannelProto); + self.transform = (upstream, scope) => _Effect_js__rspack_import_3/* .catchCause */.Tyx(transform(upstream, scope), cause => _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .failCause */.ATB(cause))); + return self; +}; +/** + * Transforms a Channel by applying a function to its Pull implementation. + * + * **Example** (Transforming pull behavior) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Transform a channel by modifying its pull behavior + * const originalChannel = Channel.fromIterable([1, 2, 3]) + * + * const transformedChannel = Channel.transformPull( + * originalChannel, + * (pull, scope) => + * Effect.succeed( + * Effect.map(pull, (value) => value * 2) + * ) + * ) + * await Effect.runPromise(Channel.runCollect(transformedChannel)) // => [2, 4, 6] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPull = (self, f) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .flatMap */.qIB(toTransform(self)(upstream, scope), pull => f(pull, scope))); +/** + * Creates a `Channel` from an `Effect` that produces a `Pull`. + * + * **Example** (Creating channels from pulls) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect } from "effect" + * + * const channel = Channel.fromPull(Effect.sync(() => { + * let emitted = false + * return Effect.suspend(() => { + * if (emitted) return Cause.done() + * emitted = true + * return Effect.succeed(42) + * }) + * })) + * await Effect.runPromise(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPull = effect => fromTransform((_, __) => effect); +/** + * Creates a `Channel` from a transformation function that operates on upstream + * pulls, but also provides a forked scope that closes when the resulting + * Channel completes. + * + * **When to use** + * + * Use when building channels that require scoped resource lifecycle management, + * providing both the channel scope and a forked scope that automatically closes + * when the channel completes. + * + * @see {@link fromTransform} for a simpler transformation without a forked scope + * @category constructors + * @since 4.0.0 + */ +const fromTransformBracket = f => fromTransform(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope) { + const closableScope = _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(scope); + const onCause = cause => _Scope_js__rspack_import_4/* .close */.VN(closableScope, _Pull_js__rspack_import_5/* .doneExitFromCause */.aU(cause)); + const pull = yield* _Effect_js__rspack_import_3/* .onError */.S5A(f(upstream, scope, closableScope), onCause); + return _Effect_js__rspack_import_3/* .onError */.S5A(pull, onCause); +})); +/** + * Converts a `Channel` back to its underlying transformation function. + * + * **Example** (Extracting channel transforms) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.succeed(42) + * const transform = Channel.toTransform(channel) + * typeof transform // => "function" + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toTransform = channel => channel.transform; +/** + * The default chunk size used by channels for batching operations. + * + * **Example** (Reading the default chunk size) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * Channel.DefaultChunkSize // => 4096 + * ``` + * + * @category constants + * @since 4.0.0 + */ +const DefaultChunkSize = 4096; +const asyncQueue = (scope, f, options) => Queue.make({ + capacity: options?.bufferSize, + strategy: options?.strategy +}).pipe(Effect.tap(queue => Scope.addFinalizer(scope, Queue.shutdown(queue))), Effect.tap(queue => Effect.forkIn(Scope.provide(f(queue), scope), scope))); +/** + * Creates a `Channel` that interacts with a callback function using a queue. + * + * **Example** (Creating channels from callbacks) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Queue } from "effect" + * + * const channel = Channel.callback((queue) => + * Effect.gen(function*() { + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * yield* Queue.end(queue) + * }) + * ) + * await Effect.runPromise(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.take)); +/** + * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays. + * + * **Example** (Creating array channels from callbacks) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Queue } from "effect" + * + * const channel = Channel.callbackArray(Effect.fn(function*(queue) { + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.end(queue) + * })) + * await Effect.runPromise(Channel.runCollect(channel)) // => [[1, 2]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callbackArray = (f, options) => fromTransform((_, scope) => Effect.map(asyncQueue(scope, f, options), Queue.takeAll)); +/** + * Creates a `Channel` that lazily evaluates to another channel. + * + * **Example** (Suspending channel creation) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.suspend(() => Channel.succeed(42)) + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = evaluate => fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope))); +/** + * Acquires a resource, uses it to build a `Channel`, and guarantees that + * `release` runs with the channel's `Exit` when the channel completes, fails, + * or is interrupted. + * + * **Details** + * + * Acquisition is uninterruptible. If acquisition fails, `use` is not run and + * `release` is not registered. + * + * **Example** (Managing resources with acquire-use-release) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const released: Array = [] + * const channel = Channel.acquireUseRelease( + * Effect.succeed("resource"), + * (resource) => Channel.succeed(resource.toUpperCase()), + * (resource, exit) => Effect.sync(() => released.push(resource)) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [["RESOURCE"], ["resource"]] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const acquireUseRelease = (acquire, use, release) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) { + let option = Option.none(); + yield* Scope.addFinalizerExit(forkedScope, exit => Option.isSome(option) ? release(option.value, exit) : Effect.void); + const value = yield* Effect.uninterruptible(acquire); + option = Option.some(value); + return yield* toTransform(use(value))(upstream, scope); +})); +/** + * Acquires a resource, emits the acquired value as a single channel element, + * and registers `release` in the channel scope. + * + * **Details** + * + * The release action runs when the channel scope closes and receives the scope + * exit. If acquisition fails, no element is emitted and `release` is not + * registered. + * + * **Example** (Managing resources with acquire-release) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const released: Array = [] + * const channel = Channel.acquireRelease( + * Effect.succeed("resource"), + * (resource, exit) => Effect.sync(() => released.push(resource)) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channel)), released] // => [["resource"], ["resource"]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const acquireRelease = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, release) => unwrap(Effect.map(Effect.acquireRelease(self, release), succeed))))); +/** + * Creates a `Channel` from an iterator. + * + * **Example** (Creating channels from iterators) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const channel = Channel.fromIterator(() => numbers[Symbol.iterator]()) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterator = iterator => fromPull(Effect.sync(() => { + const iter = iterator(); + return Effect.suspend(() => { + const state = iter.next(); + return state.done ? Cause.done(state.value) : Effect.succeed(state.value); + }); +})); +/** + * Creates a `Channel` that emits all elements from an array. + * + * **Example** (Creating channels from arrays) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromArray([1, 2, 3, 4, 5]) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArray = array => fromPull(Effect.sync(() => { + let index = 0; + return Effect.suspend(() => index >= array.length ? Cause.done() : Effect.succeed(array[index++])); +})); +/** + * Creates a `Channel` that emits all elements from a chunk. + * + * **Example** (Creating channels from chunks) + * + * ```ts import.meta.vitest + * import { Channel, Chunk, Effect } from "effect" + * + * const chunk = Chunk.make(1, 2, 3) + * const channel = Channel.fromChunk(chunk) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromChunk = chunk => fromArray(Chunk.toReadonlyArray(chunk)); +/** + * Creates a `Channel` from an iterator that emits arrays of elements. + * + * **Example** (Batching iterator output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel from a simple iterator + * const numberIterator = (): Iterator => { + * let count = 0 + * return { + * next: () => { + * if (count < 3) { + * return { value: count++, done: false } + * } + * return { value: "finished", done: true } + * } + * } + * } + * + * const channel = Channel.fromIteratorArray(() => numberIterator(), 2) + * Effect.runSync(Channel.runCollect(channel)) // => [[0, 1], [2]] + * ``` + * + * **Example** (Batching generator output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create channel from a generator function + * function* fibonacci(): Generator { + * let a = 0, b = 1 + * for (let i = 0; i < 5; i++) { + * yield a + * ;[a, b] = [b, a + b] + * } + * } + * + * const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3) + * Effect.runSync(Channel.runCollect(fibChannel)) // => [[0, 1, 1], [2, 3]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIteratorArray = (iterator, chunkSize = DefaultChunkSize) => fromPull(Effect.sync(() => { + const iter = iterator(); + let done = Option.none(); + return Effect.suspend(() => { + if (done._tag === "Some") return Cause.done(done.value); + const buffer = []; + while (buffer.length < chunkSize) { + const state = iter.next(); + if (state.done) { + if (buffer.length === 0) { + return Cause.done(state.value); + } + done = Option.some(state.value); + break; + } + buffer.push(state.value); + } + return Effect.succeed(buffer); + }); +})); +/** + * Creates a `Channel` that emits all elements from an iterable. + * + * **Example** (Creating channels from iterables) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const set = new Set([1, 2, 3]) + * const channel = Channel.fromIterable(set) + * Effect.runSync(Channel.runCollect(channel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterable = iterable => fromIterator(() => iterable[Symbol.iterator]()); +/** + * Creates a `Channel` that emits arrays of elements from an iterable. + * + * **Example** (Batching iterable output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const channel = Channel.fromIterableArray(numbers, 4) + * Effect.runSync(Channel.runCollect(channel)) // => [[1, 2, 3, 4], [5]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterableArray = (iterable, chunkSize = DefaultChunkSize) => fromIteratorArray(() => iterable[Symbol.iterator](), chunkSize); +/** + * Creates a `Channel` that emits a single value and then ends. + * + * **Example** (Creating channels that succeed) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.succeed(42) + * Effect.runSync(Channel.runCollect(channel)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeed = value => fromEffect(_Effect_js__rspack_import_3/* .succeed */.PyW(value)); +/** + * Creates a `Channel` that immediately ends with the specified value. + * + * **Example** (Ending with a value) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.end("done") + * Effect.runSync(Channel.runCollect(channel)) // => [] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const end = value => fromPull(Effect.succeed(Cause.done(value))); +/** + * Creates a `Channel` that immediately ends with the lazily evaluated value. + * + * @category constructors + * @since 4.0.0 + */ +const endSync = evaluate => fromPull(Effect.sync(() => Cause.done(evaluate()))); +/** + * Creates a `Channel` that emits a single value computed by a lazy evaluation. + * + * **Example** (Computing values lazily) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * let requests = 0 + * + * const channel = Channel.sync(() => { + * requests += 1 + * return `request-${requests}` + * }) + * Effect.runSync(Channel.runCollect(channel)) // => ["request-1"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sync = evaluate => fromEffect(Effect.sync(evaluate)); +/** + * Represents a `Channel` that emits no elements. + * + * **Example** (Creating empty channels) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create an empty channel + * const emptyChannel = Channel.empty + * + * // Use empty channel in composition + * const combined = Channel.concatWith(emptyChannel, () => Channel.succeed(42)) + * // Will immediately provide the second channel's output + * + * // Empty channel can be used as a no-op in conditional logic + * const conditionalChannel = (shouldEmit: boolean) => + * shouldEmit ? Channel.succeed("data") : Channel.empty + * + * Effect.runSync(Channel.runCollect(conditionalChannel(true))) // => ["data"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const empty = /*#__PURE__*/fromPull(/*#__PURE__*/_Effect_js__rspack_import_3/* .succeed */.PyW(/*#__PURE__*/_Cause_js__rspack_import_6/* .done */.Vw())); +/** + * Represents a `Channel` that never completes. + * + * **Example** (Creating non-terminating channels) + * + * ```ts import.meta.vitest + * import { Channel } from "effect" + * + * // Create a channel that never completes + * const neverChannel = Channel.never + * + * // Use in conditional logic + * const withFallback = Channel.concatWith( + * neverChannel, + * () => Channel.succeed("fallback") + * ) + * + * // Never channel is useful for testing or as a placeholder + * const conditionalChannel = (shouldComplete: boolean) => + * shouldComplete ? Channel.succeed("done") : Channel.never + * + * Channel.isChannel(conditionalChannel(false)) // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = /*#__PURE__*/fromPull(/*#__PURE__*/_Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .never */.ZmZ)); +/** + * Constructs a channel that fails immediately with the specified error. + * + * **Example** (Failing with an error) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Exit } from "effect" + * + * const failedChannel = Channel.fail("Something went wrong") + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.fail("Something went wrong") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fail = error => fromPull(Effect.succeed(Effect.fail(error))); +/** + * Constructs a channel that fails immediately with the specified lazily + * evaluated error. + * + * **When to use** + * + * Use when the error value should be computed each time the channel runs instead + * of when the channel is constructed. + * + * **Example** (Failing with a lazy error) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Exit } from "effect" + * + * let attempts = 0 + * const conditionalError = Channel.failSync(() => { + * attempts += 1 + * return `Error after attempt ${attempts}` + * }) + * const observed = [ + * Effect.runSync(Effect.exit(Channel.runCollect(conditionalError))), + * attempts + * ] // => [Exit.fail("Error after attempt 1"), 1] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = evaluate => fromPull(Effect.failSync(evaluate)); +/** + * Constructs a channel that fails immediately with the specified `Cause`. + * + * **When to use** + * + * Use when the channel failure must preserve a full `Cause`, such as defects, + * interruptions, or combined failures. + * + * **Example** (Failing with causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * const simpleCause = Cause.fail("Simple error") + * const failedChannel = Channel.failCause(simpleCause) + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))) // => Exit.failCause(simpleCause) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = cause => fromPull(Effect.failCause(cause)); +/** + * Constructs a channel that fails immediately with the specified lazily + * evaluated `Cause`. + * + * **Example** (Failing with lazy causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * // Create a channel that fails with a lazily computed cause + * let attempts = 0 + * const failedChannel = Channel.failCauseSync(() => { + * attempts += 1 + * return Cause.fail(`Runtime error after attempt ${attempts}`) + * }) + * + * const observed = [ + * Effect.runSync(Effect.exit(Channel.runCollect(failedChannel))), + * attempts + * ] // => [Exit.fail("Runtime error after attempt 1"), 1] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = evaluate => fromPull(Effect.failCauseSync(evaluate)); +/** + * Constructs a channel that fails immediately with the specified defect. + * + * **Example** (Dying with defects) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Exit } from "effect" + * + * const defect = "Unrecoverable error" + * const diedChannel = Channel.die(defect) + * Effect.runSync(Effect.exit(Channel.runCollect(diedChannel))) // => Exit.failCause(Cause.die(defect)) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const die = defect => failCause(Cause.die(defect)); +/** + * Uses an effect to write a single value to the channel. + * + * **Example** (Creating channels from effects) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const successChannel = Channel.fromEffect( + * Effect.succeed("Hello from effect!") + * ) + * Effect.runSync(Channel.runCollect(successChannel)) // => ["Hello from effect!"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEffect = effect => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let done = false; + return _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (done) return _Cause_js__rspack_import_6/* .done */.Vw(); + done = true; + return effect; + }); +})); +/** + * Creates a channel that evaluates an effect and uses its successful value as + * the channel's done value without emitting any output elements. + * + * **Details** + * + * If the effect fails, the channel fails with the effect's error. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDone = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))); +/** + * Uses an effect and discards its result. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDrain = effect => fromPull(Effect.flatMap(effect, () => Cause.done())); +/** + * Creates a channel from an effect that produces a `Take`. + * + * **Details** + * + * A successful `Take` emits a non-empty array of output elements. A failed + * `Take` fails the channel. A done `Take` completes the channel with its done + * value. + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectTake = effect => fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull))); +/** + * Creates a channel from a queue. + * + * **Example** (Creating channels from queues) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * yield* Queue.offerAll(queue, ["item1", "item2", "item3"]) + * yield* Queue.end(queue) + * const channel = Channel.fromQueue(queue) + * return yield* Channel.runCollect(channel) + * }) + * await Effect.runPromise(program) // => ["item1", "item2", "item3"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromQueue = queue => fromPull(Effect.succeed(Queue.take(queue))); +/** + * Creates a channel from a queue that emits arrays of elements. + * + * **Example** (Creating batched channels from queues) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(4) + * yield* Queue.offerAll(queue, [1, 2, 3, 4]) + * yield* Queue.end(queue) + * const arrayChannel = Channel.fromQueueArray(queue) + * return yield* Channel.runCollect(arrayChannel) + * }) + * await Effect.runPromise(program) // => [[1, 2, 3, 4]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromQueueArray = queue => fromPull(Effect.succeed(Queue.takeAll(queue))); +/** + * Creates a channel that forwards upstream input elements, input errors, and + * the upstream done value unchanged. + * + * @category constructors + * @since 2.0.0 + */ +const identity = () => fromTransform((upstream, _scope) => Effect.succeed(upstream)); +/** + * Creates a channel from a PubSub subscription. + * + * **Example** (Creating channels from subscriptions) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class SubscriptionError extends Data.TaggedError("SubscriptionError")<{ + * readonly reason: string + * }> {} + * + * const program = Effect.gen(function*() { + * // Create a PubSub + * const pubsub = yield* PubSub.bounded(32) + * + * // Create a subscription + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Publish some messages + * yield* PubSub.publish(pubsub, "Hello") + * yield* PubSub.publish(pubsub, "World") + * yield* PubSub.publish(pubsub, "from") + * yield* PubSub.publish(pubsub, "PubSub") + * + * // Create a channel from the subscription + * const channel = Channel.fromSubscription(subscription) + * + * // The channel will receive all published messages + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some("Hello") + * + * // Real-time notifications example + * const notificationChannel = Effect.gen(function*() { + * const eventBus = yield* PubSub.unbounded<{ type: string; payload: any }>() + * const userSubscription = yield* PubSub.subscribe(eventBus) + * + * return Channel.fromSubscription(userSubscription) + * }) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscription = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done()))); +/** + * Creates a channel from a PubSub subscription that outputs arrays of values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub subscription and outputs + * arrays of values in chunks. It's useful when you want to process multiple values at once + * for better performance. + * + * **Example** (Batching subscription values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.bounded(16) + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Create a channel that reads arrays of values + * const channel = Channel.fromSubscriptionArray(subscription) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * yield* PubSub.publish(pubsub, 4) + * + * // The channel will output arrays like [1, 2, 3] and [4] + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4]) + * ``` + * + * **Example** (Processing subscription values in batches) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class BatchProcessingError extends Data.TaggedError("BatchProcessingError")<{ + * readonly reason: string + * }> {} + * + * const batchProcessor = Effect.gen(function*() { + * const pubsub = yield* PubSub.bounded(32) + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Create a channel that processes items in batches + * const batchChannel = Channel.fromSubscriptionArray(subscription) + * + * // Transform to process each batch + * const processedChannel = Channel.map(batchChannel, (batch) => + * batch.map((item) => item.toUpperCase()) + * ) + * + * yield* PubSub.publishAll(pubsub, ["one", "two"]) + * return processedChannel + * }) + * const batch = Effect.scoped(Effect.flatMap(batchProcessor, Channel.runHead)) + * await Effect.runPromise(batch) // => Option.some(["ONE", "TWO"]) + * ``` + * + * **Example** (Aggregating subscription metrics) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * const metricsAggregator = Effect.gen(function*() { + * const metricsPubSub = yield* PubSub.bounded< + * { timestamp: number; value: number } + * >(100) + * const subscription = yield* PubSub.subscribe(metricsPubSub) + * + * // Create a channel that collects metrics in chunks + * const metricsChannel = Channel.fromSubscriptionArray(subscription) + * + * // Transform to calculate aggregate statistics + * const aggregatedChannel = Channel.map(metricsChannel, (metrics) => { + * const values = metrics.map((m) => m.value) + * const sum = values.reduce((a, b) => a + b, 0) + * const avg = sum / values.length + * const min = Math.min(...values) + * const max = Math.max(...values) + * + * return { + * count: values.length, + * sum, + * average: avg, + * min, + * max, + * firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)), + * lastTimestamp: Math.max(...metrics.map((m) => m.timestamp)) + * } + * }) + * + * yield* PubSub.publish(metricsPubSub, { timestamp: 1, value: 10 }) + * return aggregatedChannel + * }) + * const metric = Effect.scoped(Effect.flatMap(metricsAggregator, Channel.runHead)) + * const result = await Effect.runPromise(metric) + * Option.map(result, ({ count, sum, average, min, max }) => ({ count, sum, average, min, max })) // => Option.some({ count: 1, sum: 10, average: 10, min: 10, max: 10 }) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscriptionArray = subscription => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done()))); +/** + * Creates a channel from a PubSub that outputs individual values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub by automatically + * subscribing to it. The channel outputs individual values as they are published + * to the PubSub, making it ideal for real-time streaming scenarios. + * + * **Example** (Creating channels from PubSubs) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 3 }) + * + * // Create a channel that reads individual values + * const channel = Channel.fromPubSub(pubsub) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * + * // The channel will output: 1, 2, 3 (individual values) + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some(1) + * ``` + * + * **Example** (Streaming PubSub notifications) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * const notificationService = Effect.gen(function*() { + * const notificationPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel for real-time notifications + * const notificationChannel = Channel.fromPubSub(notificationPubSub) + * + * // Transform notifications to add timestamps + * const receivedAt = "2024-01-01T00:00:00.000Z" + * const timestampedChannel = Channel.map(notificationChannel, (message) => ({ + * message, + * receivedAt, + * id: `notification:${message}` + * })) + * + * yield* PubSub.publish(notificationPubSub, "ready") + * return timestampedChannel + * }) + * const notification = Effect.scoped(Effect.flatMap(notificationService, Channel.runHead)) + * await Effect.runPromise(notification) // => Option.some({ message: "ready", receivedAt: "2024-01-01T00:00:00.000Z", id: "notification:ready" }) + * ``` + * + * **Example** (Processing PubSub events) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface DomainEvent { + * readonly type: string + * readonly payload: unknown + * readonly timestamp: number + * } + * + * const eventProcessor = Effect.gen(function*() { + * const eventPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel for processing domain events + * const eventChannel = Channel.fromPubSub(eventPubSub) + * + * // Filter and transform events + * const processedChannel = Channel.map(eventChannel, (event) => { + * if (event.type === "user.created") { + * return { + * ...event, + * processed: true, + * processedAt: event.timestamp + 1 + * } + * } + * return event + * }) + * + * yield* PubSub.publish(eventPubSub, { type: "user.created", payload: {}, timestamp: 1 }) + * return processedChannel + * }) + * const event = Effect.scoped(Effect.flatMap(eventProcessor, Channel.runHead)) + * const result = await Effect.runPromise(event) // => Option.some({ type: "user.created", payload: {}, timestamp: 1, processed: true, processedAt: 2 }) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPubSub = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription)); +/** + * Creates a channel from a PubSub that outputs arrays of values. + * + * **Details** + * + * This constructor creates a channel that reads from a PubSub by automatically + * subscribing to it and collecting values into arrays. The channel outputs + * arrays of values in chunks, making it ideal for batch processing scenarios. + * + * **Example** (Batching PubSub values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Option, PubSub } from "effect" + * + * class BatchError extends Data.TaggedError("BatchError")<{ + * readonly message: string + * }> {} + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 4 }) + * + * // Create a channel that reads arrays of values + * const channel = Channel.fromPubSubArray(pubsub) + * + * // Publish some values + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * yield* PubSub.publish(pubsub, 4) + * + * // The channel will output arrays like [1, 2, 3] and [4] + * return channel + * }) + * const result = Effect.scoped(Effect.flatMap(program, Channel.runHead)) + * await Effect.runPromise(result) // => Option.some([1, 2, 3, 4]) + * ``` + * + * **Example** (Processing PubSub orders in batches) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface Order { + * readonly id: string + * readonly customerId: string + * readonly items: ReadonlyArray + * readonly total: number + * readonly submittedAt: number + * } + * + * const orderBatchProcessor = Effect.gen(function*() { + * const orderPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel that processes orders in batches + * const orderChannel = Channel.fromPubSubArray(orderPubSub) + * + * // Transform to process each batch of orders + * const processedChannel = Channel.map(orderChannel, (orderBatch) => { + * const totalRevenue = orderBatch.reduce((sum, order) => sum + order.total, 0) + * const customerCount = new Set(orderBatch.map((order) => + * order.customerId + * )).size + * + * return { + * batchSize: orderBatch.length, + * totalRevenue, + * uniqueCustomers: customerCount, + * firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)), + * orders: orderBatch + * } + * }) + * + * yield* PubSub.publish(orderPubSub, { + * id: "1", customerId: "a", items: ["book"], total: 10, submittedAt: 1 + * }) + * return processedChannel + * }) + * const order = Effect.scoped(Effect.flatMap(orderBatchProcessor, Channel.runHead)) + * const result = await Effect.runPromise(order) + * Option.map(result, (batch) => [batch.batchSize, batch.totalRevenue, batch.uniqueCustomers]) // => Option.some([1, 10, 1]) + * ``` + * + * **Example** (Processing PubSub logs in batches) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Option, PubSub } from "effect" + * + * interface LogEntry { + * readonly timestamp: number + * readonly level: "info" | "warn" | "error" + * readonly message: string + * readonly source: string + * } + * + * const logAggregator = Effect.gen(function*() { + * const logPubSub = yield* PubSub.unbounded({ replay: 1 }) + * + * // Create a channel that collects logs in batches + * const logChannel = Channel.fromPubSubArray(logPubSub) + * + * // Transform to analyze log batches + * const analysisChannel = Channel.map(logChannel, (logBatch) => { + * const errorCount = logBatch.filter((log) => log.level === "error").length + * const warnCount = logBatch.filter((log) => log.level === "warn").length + * const infoCount = logBatch.filter((log) => log.level === "info").length + * + * const timeRange = { + * start: Math.min(...logBatch.map((log) => log.timestamp)), + * end: Math.max(...logBatch.map((log) => log.timestamp)) + * } + * + * return { + * batchId: `${timeRange.start}-${timeRange.end}`, + * totalEntries: logBatch.length, + * errorCount, + * warnCount, + * infoCount, + * timeRange, + * sources: [...new Set(logBatch.map((log) => log.source))] + * } + * }) + * + * yield* PubSub.publish(logPubSub, { + * timestamp: 1, + * level: "info", + * message: "ready", + * source: "app" + * } satisfies LogEntry) + * return analysisChannel + * }) + * const log = Effect.scoped(Effect.flatMap(logAggregator, Channel.runHead)) + * const result = await Effect.runPromise(log) + * Option.map(result, (batch) => [batch.batchId, batch.totalEntries, batch.infoCount]) // => Option.some(["1-1", 1, 1]) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubArray = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray)); +/** + * Subscribes to a `PubSub` of `Take` values and exposes them as a channel. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the channel. Done `Take` values complete the channel. + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubTake = pubsub => unwrap(Effect.map(PubSub.subscribe(pubsub), sub => fromEffectTake(PubSub.take(sub)))); +/** + * Creates a Channel from a Schedule. + * + * @category constructors + * @since 4.0.0 + */ +const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => step(void 0))); +/** + * Creates a channel from a lazily supplied Web `ReadableStream`. + * + * **Example** (Reading from a Web stream) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromReadableStream({ + * evaluate: () => new ReadableStream({ + * start(controller) { + * controller.enqueue(1) + * controller.close() + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * await Effect.runPromise(Channel.runCollect(channel)) // => [[1]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromReadableStream = options => fromTransform((_, scope) => readableStreamToPullUnsafe({ + scope, + readable: options.evaluate(), + onError: options.onError, + releaseLockOnEnd: options.releaseLockOnEnd +})); +/** @internal */ +const pullIntoWritableStream = options => Effect.acquireUseRelease(Effect.sync(() => options.writable.getWriter()), writer => { + const loop = options.pull.pipe(Effect.flatMap(chunk => Effect.forEach(chunk, value => Effect.tryPromise({ + try: () => writer.ready.then(() => writer.write(value)), + catch: options.onError + }), { + discard: true + })), Effect.forever({ + disableYield: true + })); + const withClose = options.closeOnDone !== false ? Pull.catchDone(loop, done => Effect.andThen(Effect.tryPromise({ + try: () => writer.close(), + catch: options.onError + }), Cause.done(done))) : loop; + return Effect.onError(withClose, cause => Pull.isDoneCause(cause) ? Effect.void : Effect.promise(() => writer.abort(cause).catch(constVoid))); +}, writer => Effect.sync(() => writer.releaseLock())); +/** + * Creates a channel that writes upstream values to a lazily supplied Web + * `WritableStream`. + * + * **Example** (Writing channel input) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const written: Array = [] + * const sink = Channel.fromWritableStream({ + * evaluate: () => new WritableStream({ + * write(value) { + * written.push(value) + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe( + * Channel.pipeTo(sink), + * Channel.runDrain + * ) + * + * await Effect.runPromise(program) + * written // => [1, 2] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromWritableStream = options => fromTransform(pull => { + const writable = options.evaluate(); + return Effect.succeed(pullIntoWritableStream({ + ...options, + writable, + pull + })); +}); +/** + * Creates a channel backed by a Web `TransformStream`, writing upstream values + * while emitting transformed values from its readable side. + * + * **Example** (Transforming channel input) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const transform = Channel.fromTransformStream({ + * evaluate: () => new TransformStream({ + * transform(value, controller) { + * controller.enqueue(value * 2) + * } + * }), + * onError: (cause) => new Error(String(cause)) + * }) + * + * const program = Channel.fromArray([[1, 2] as [number, number]]).pipe( + * Channel.pipeTo(transform), + * Channel.runCollect + * ) + * + * await Effect.runPromise(program) // => [[2], [4]] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromTransformStream = options => fromTransform((upstream, scope) => { + const transform = options.evaluate(); + const exit = MutableRef.make(undefined); + return pullIntoWritableStream({ + pull: upstream, + writable: transform.writable, + onError: options.onError, + closeOnDone: options.closeOnDone + }).pipe(Effect.catchCause(cause => { + if (!Pull.isDoneCause(cause)) { + exit.current = Exit.failCause(cause); + } + return Effect.void; + }), Effect.forkIn(scope), Effect.flatMap(() => readableStreamToPullUnsafe({ + scope, + exit, + readable: transform.readable, + onError: options.onError, + releaseLockOnEnd: options.releaseLockOnEnd + }))); +}); +const readableStreamToPullUnsafe = options => { + const reader = options.readable.getReader(); + const exit = options.exit ?? _MutableRef_js__rspack_import_7/* .make */.L8(undefined); + const pull = _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (exit.current) return exit.current; + return _Effect_js__rspack_import_3/* .matchCauseEffect */.khu(_Effect_js__rspack_import_3/* .tryPromise */.$mh({ + try: () => reader.read(), + catch: options.onError + }), { + onFailure: cause => exit.current ?? _Effect_js__rspack_import_3/* .failCause */.ATB(cause), + onSuccess: ({ + done, + value + }) => { + if (exit.current) return exit.current; + return done ? _Cause_js__rspack_import_6/* .done */.Vw() : _Effect_js__rspack_import_3/* .succeed */.PyW(_Array_js__rspack_import_8.of(value)); + } + }); + }); + return _Effect_js__rspack_import_3.as(_Scope_js__rspack_import_4/* .addFinalizer */.U9(options.scope, options.releaseLockOnEnd ? _Effect_js__rspack_import_3/* .sync */.OH5(() => reader.releaseLock()) : _Effect_js__rspack_import_3/* .promise */.ivC(() => reader.cancel().catch(_Function_js__rspack_import_1/* .constVoid */.Yi))), pull); +}; +/** + * Creates a channel that pulls values from an `AsyncIterable`. + * + * **Details** + * + * Each yielded value is emitted as an output element. The iterator's return + * value becomes the channel's done value. Thrown or rejected iterator errors + * are converted with `onError`. If the channel scope closes early and the + * iterator has a `return` method, that method is called. + * + * @category constructors + * @since 4.0.0 + */ +const fromAsyncIterable = (iterable, onError) => fromTransform(Effect.fnUntraced(function* (_, scope) { + const iter = iterable[Symbol.asyncIterator](); + if (iter.return) { + yield* Scope.addFinalizer(scope, Effect.promise(() => iter.return())); + } + return Effect.flatMap(Effect.tryPromise({ + try: () => iter.next(), + catch: onError + }), result => result.done ? Cause.done(result.value) : Effect.succeed(result.value)); +})); +/** + * Creates a channel from an `AsyncIterable`, emitting each yielded value as a + * single-element non-empty array. + * + * **Details** + * + * The iterator's return value becomes the channel's done value. Thrown or + * rejected iterator errors are converted with `onError`. If the channel scope + * closes early and the iterator has a `return` method, that method is called. + * + * @category constructors + * @since 4.0.0 + */ +const fromAsyncIterableArray = (iterable, onError) => map(fromAsyncIterable(iterable, onError), Arr.of); +/** + * Maps the output of this channel using the specified function. + * + * **Example** (Mapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class TransformError extends Data.TaggedError("TransformError")<{ + * readonly reason: string + * }> {} + * + * // Basic mapping of channel values + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * const doubledChannel = Channel.map(numbersChannel, (n) => n * 2) + * Effect.runSync(Channel.runCollect(doubledChannel)) // => [2, 4, 6, 8, 10] + * + * // Transform string data + * const wordsChannel = Channel.fromIterable(["hello", "world", "effect"]) + * const upperCaseChannel = Channel.map(wordsChannel, (word) => word.toUpperCase()) + * Effect.runSync(Channel.runCollect(upperCaseChannel)) // => ["HELLO", "WORLD", "EFFECT"] + * + * // Complex object transformation + * type User = { id: number; name: string } + * type UserDisplay = { displayName: string; isActive: boolean } + * + * const usersChannel = Channel.fromIterable([ + * { id: 1, name: "Alice" }, + * { id: 2, name: "Bob" } + * ]) + * const displayChannel = Channel.map(usersChannel, (user): UserDisplay => ({ + * displayName: `User: ${user.name}`, + * isActive: true + * })) + * Effect.runSync(Channel.runCollect(displayChannel)) // => [{ displayName: "User: Alice", isActive: true }, { displayName: "User: Bob", isActive: true }] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => transformPull(self, pull => _Effect_js__rspack_import_3/* .sync */.OH5(() => { + let i = 0; + return _Effect_js__rspack_import_3/* .map */.TjK(pull, o => f(o, i++)); +}))); +/** + * Maps the done value of this channel using the specified function. + * + * @category sequencing + * @since 4.0.0 + */ +const mapDone = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => mapDoneEffect(self, o => Effect.succeed(f(o)))))); +/** + * Maps the done value of this channel using the specified effectful function. + * + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 + */ +const mapDoneEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, done => Effect.flatMap(f(done), Cause.done))))))); +const concurrencyIsSequential = concurrency => concurrency === undefined || concurrency !== "unbounded" && concurrency <= 1; +/** + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * const processedChannel = Channel.mapEffect( + * numbersChannel, + * (n) => Effect.succeed(n * n) + * ) + * await Effect.runPromise(Channel.runCollect(processedChannel)) // => [1, 4, 9, 16, 25] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const mapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? mapEffectSequential(self, f) : mapEffectConcurrent(self, f, options)); +const mapEffectSequential = (self, f) => fromTransform((upstream, scope) => { + let i = 0; + return _Effect_js__rspack_import_3/* .map */.TjK(toTransform(self)(upstream, scope), _Effect_js__rspack_import_3/* .flatMap */.qIB(o => f(o, i++))); +}); +const mapEffectConcurrent = (self, f, options) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope, forkedScope) { + let i = 0; + const pull = yield* toTransform(self)(upstream, scope); + const concurrencyN = options.concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : options.concurrency; + const queue = yield* _Queue_js__rspack_import_9/* .bounded */.Mm(0); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_9/* .shutdown */.n_(queue)); + const runFork = _Effect_js__rspack_import_3/* .runForkWith */.eJC(yield* _Effect_js__rspack_import_3/* .context */._OA()); + const trackFiber = _Fiber_js__rspack_import_10/* .runIn */.VO(forkedScope); + if (options.unordered) { + const semaphore = _Semaphore_js__rspack_import_11/* .makeUnsafe */.LZ(concurrencyN); + const release = (0,_Function_js__rspack_import_1/* .constant */.dY)(semaphore.release(1)); + const handle = _Effect_js__rspack_import_3/* .matchCauseEffect */.khu({ + onFailure: cause => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Queue_js__rspack_import_9/* .failCause */.AT(queue, cause), release), + onSuccess: value => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Queue_js__rspack_import_9/* .offer */.x(queue, value), release) + }); + yield* semaphore.take(1).pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(() => pull), _Effect_js__rspack_import_3/* .flatMap */.qIB(value => { + trackFiber(runFork(handle(f(value, i++)))); + return _Effect_js__rspack_import_3/* ["void"] */.rIH; + }), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => semaphore.withPermits(concurrencyN - 1)(_Queue_js__rspack_import_9/* .failCause */.AT(queue, cause))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + } else { + // capacity is n - 2 because + // - 1 for the offer *after* starting a fiber + // - 1 for the current processing fiber + const effects = yield* _Queue_js__rspack_import_9/* .bounded */.Mm(concurrencyN - 2); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_9/* .shutdown */.n_(effects)); + yield* _Queue_js__rspack_import_9/* .take */.s(effects).pipe(_Effect_js__rspack_import_3/* .flatten */.Bqz, _Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_9/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause)), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + let errorCause; + const onExit = exit => { + if (exit._tag === "Success") return; + errorCause = exit.cause; + _Queue_js__rspack_import_9/* .failCauseUnsafe */._1(queue, exit.cause); + }; + yield* pull.pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(value => { + if (errorCause) return _Effect_js__rspack_import_3/* .failCause */.ATB(errorCause); + const fiber = runFork(f(value, i++)); + trackFiber(fiber); + fiber.addObserver(onExit); + return _Queue_js__rspack_import_9/* .offer */.x(effects, _Fiber_js__rspack_import_10/* .join */.fj(fiber)); + }), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => _Queue_js__rspack_import_9/* .offer */.x(effects, _Exit_js__rspack_import_12/* .failCause */.AT(cause)).pipe(_Effect_js__rspack_import_3/* .andThen */.hgn(_Queue_js__rspack_import_9/* .failCause */.AT(effects, cause)))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + } + return _Queue_js__rspack_import_9/* .take */.s(queue); +})); +/** + * Returns a new channel which is the same as this one but applies the given + * function to the input channel’s input elements. + * + * @category sequencing + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.flatMap(upstream, el => f(el)), scope))))); +/** + * Returns a new channel which is the same as this one but applies the given + * function to the input errors. + * + * @category sequencing + * @since 2.0.0 + */ +const mapInputError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => toTransform(self)(Effect.catch(upstream, err => { + if (Cause.isDone(err)) return Effect.fail(err); + return Effect.flatMap(f(err), Effect.fail); +}), scope))))); +/** + * Applies a side effect function to each output element of the channel, + * returning a new channel that emits the same elements. + * + * **Details** + * + * The `tap` function allows you to perform side effects (like logging or + * debugging) on each element emitted by a channel without modifying the + * elements themselves. + * + * **Example** (Tapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class LogError extends Data.TaggedError("LogError")<{ + * readonly message: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // Tap into each output element to perform side effects + * const processed: Array = [] + * const tappedChannel = Channel.tap( + * numberChannel, + * (n) => Effect.sync(() => processed.push(n)) + * ) + * + * const observed = [await Effect.runPromise(Channel.runCollect(tappedChannel)), processed] // => [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, f, options) => mapEffect(self, a => Effect.as(f(a), a), options)))); +/** + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (Flat mapping channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ProcessError extends Data.TaggedError("ProcessError")<{ + * readonly cause: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // FlatMap each number to create new channels + * const flatMappedChannel = Channel.flatMap( + * numberChannel, + * (n) => + * Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`)) + * ) + * + * Effect.runSync(Channel.runCollect(flatMappedChannel)) // => ["item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]), (self, f, options) => concurrencyIsSequential(options?.concurrency) ? flatMapSequential(self, f) : flatMapConcurrent(self, f, options)); +const flatMapSequential = (self, f) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .map */.TjK(toTransform(self)(upstream, scope), pull => { + let childPull; + let childScope; + const makePull = _Effect_js__rspack_import_3/* .flatMap */.qIB(pull, value => { + childScope ??= _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(scope); + return _Effect_js__rspack_import_3/* .flatMapEager */.Ab9(toTransform(f(value))(upstream, childScope), pull => { + childPull = catchHalt(pull); + return childPull; + }); + }); + const catchHalt = _Pull_js__rspack_import_5/* .catchDone */.m8(_ => { + childPull = undefined; + // we can reuse the scope if the only finalizer is the "fork" one + if (childScope.state._tag === "Open" && (0,_internal_effect_js__rspack_import_13/* .scopeFinalizerCountUnsafe */.q7)(childScope) === 1) { + return makePull; + } + const close = _Scope_js__rspack_import_4/* .close */.VN(childScope, _Exit_js__rspack_import_12/* ["void"] */.rI); + childScope = undefined; + return _Effect_js__rspack_import_3/* .flatMap */.qIB(close, () => makePull); + }); + return _Effect_js__rspack_import_3/* .suspend */.DYE(() => childPull ?? makePull); +})); +const flatMapConcurrent = (self, f, options) => self.pipe(map(f), mergeAll(options)); +/** + * Concatenates this channel with another channel created from the terminal value + * of this channel. The new channel is created using the provided function. + * + * **Example** (Concatenating with completion values) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ConcatError extends Data.TaggedError("ConcatError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel that outputs numbers and terminates with sum + * const numberChannel = Channel.fromIterable([1, 2, 3]).pipe( + * Channel.concatWith((sum: void) => Channel.succeed(`Completed processing`)) + * ) + * + * Effect.runSync(Channel.runCollect(numberChannel)) // => [1, 2, 3, "Completed processing"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concatWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { + let currentPull; + const forkedScope = Scope.forkUnsafe(scope); + const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => { + currentPull = Pull.catchDone(pull, leftover => { + return Scope.close(forkedScope, Exit.void).pipe(Effect.flatMap(() => toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => { + currentPull = pull; + return pull; + })); + }); + return currentPull; + }); + return Effect.suspend(() => currentPull ?? makePull); +}))))); +/** + * Concatenates this channel with another channel, so that the second channel + * starts emitting values after the first channel has completed. + * + * **Example** (Concatenating channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ConcatError extends Data.TaggedError("ConcatError")<{ + * readonly reason: string + * }> {} + * + * // Create two channels + * const firstChannel = Channel.fromIterable([1, 2, 3]) + * const secondChannel = Channel.fromIterable(["a", "b", "c"]) + * + * // Concatenate them + * const concatenatedChannel = Channel.concat(firstChannel, secondChannel) + * + * Effect.runSync(Channel.runCollect(concatenatedChannel)) // => [1, 2, 3, "a", "b", "c"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => concatWith(self, _ => that)))); +/** + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. + * + * @category sequencing + * @since 4.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const leftPull = yield* toTransform(self)(upstream, scope); + const rightPull = yield* toTransform(that)(upstream, scope); + let state = s(); + return Effect.suspend(() => { + const combinedPull = f(state, leftPull, rightPull); + return Effect.map(combinedPull, ([a, s1]) => { + state = s1; + return a; + }); + }); +}))))); +/** + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * + * @category sequencing + * @since 4.0.0 + */ +const orElseIfEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.sync(() => { + let currentPull; + const forkedScope = Scope.forkUnsafe(scope); + const makePull = Effect.flatMap(toTransform(self)(upstream, forkedScope), pull => { + const next = pull.pipe(Effect.tap(() => { + currentPull = pull; + return Effect.void; + }), Pull.catchDone(leftover => Scope.close(forkedScope, Exit.succeed(leftover)).pipe(Effect.andThen(toTransform(f(leftover))(upstream, scope)), Effect.flatMap(pull => { + currentPull = pull; + return pull; + })))); + currentPull = next; + return next; + }); + return Effect.suspend(() => currentPull ?? makePull); +}))))); +/** + * Flattens a channel of channels. + * + * **Example** (Flattening nested channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FlattenError extends Data.TaggedError("FlattenError")<{ + * readonly cause: string + * }> {} + * + * // Create a channel that outputs channels + * const nestedChannels = Channel.fromIterable([ + * Channel.fromIterable([1, 2]), + * Channel.fromIterable([3, 4]), + * Channel.fromIterable([5, 6]) + * ]) + * + * // Flatten the nested channels + * const flattenedChannel = Channel.flatten(nestedChannels) + * + * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const flatten = channels => flatMap(channels, identity_); +/** + * Flattens a channel that outputs arrays into a channel that outputs individual elements. + * + * **Example** (Flattening arrays of channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FlattenError extends Data.TaggedError("FlattenError")<{ + * readonly message: string + * }> {} + * + * // Create a channel that outputs arrays + * const arrayChannel = Channel.fromIterable([ + * [1, 2, 3], + * [4, 5], + * [6, 7, 8, 9] + * ]) + * + * // Flatten the arrays into individual elements + * const flattenedChannel = Channel.flattenArray(arrayChannel) + * + * Effect.runSync(Channel.runCollect(flattenedChannel)) // => [1, 2, 3, 4, 5, 6, 7, 8, 9] + * ``` + * + * @category transforming + * @since 4.0.0 + */ +const flattenArray = self => transformPull(self, pull => { + let array; + let index = 0; + const pump = _Effect_js__rspack_import_3/* .suspend */.DYE(function loop() { + if (array === undefined) { + return _Effect_js__rspack_import_3/* .flatMap */.qIB(pull, array_ => { + switch (array_.length) { + case 0: + return loop(); + case 1: + return _Effect_js__rspack_import_3/* .succeed */.PyW(array_[0]); + default: + { + array = array_; + return _Effect_js__rspack_import_3/* .succeed */.PyW(array_[index++]); + } + } + }); + } + const next = array[index++]; + if (index >= array.length) { + array = undefined; + index = 0; + } + return _Effect_js__rspack_import_3/* .succeed */.PyW(next); + }); + return _Effect_js__rspack_import_3/* .succeed */.PyW(pump); +}); +/** + * Flattens a channel that emits `Take` values into a channel that emits the + * `Take` outputs directly. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the returned channel. Done `Take` values complete the returned channel. + * + * @category transforming + * @since 4.0.0 + */ +const flattenTake = self => mapEffectSequential(self, Take.toPull); +/** + * Creates a new channel that consumes all output from the source channel + * but emits nothing, preserving only the completion value. + * + * **Example** (Draining channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel that outputs values + * const sourceChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Drain all output, keeping only the completion + * const drainedChannel = Channel.drain(sourceChannel) + * + * Effect.runSync(Channel.runCollect(drainedChannel)) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const drain = self => transformPull(self, pull => Effect.succeed(Effect.forever(pull, { + disableYield: true +}))); +/** + * Repeats this channel according to the provided schedule. + * + * @category repetition + * @since 4.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => Schedule.toStepWithMetadata(typeof schedule === "function" ? schedule(identity_) : schedule).pipe(Effect.map(step => { + let meta = Schedule.CurrentMetadata.defaultValue(); + const loop = concatWith(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), done => step(done).pipe(Effect.map(meta_ => { + meta = meta_; + return loop; + }), Pull.catchDone(() => Effect.succeed(end(done))), unwrap)); + return loop; +}), unwrap)))); +/** + * Repeats this channel forever. + * + * @category repetition + * @since 4.0.0 + */ +const forever = self => concatWith(self, () => forever(self)); +/** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing + * @since 4.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => transformPull(self, (pull, _scope) => Effect.map(Schedule.toStepWithSleep(schedule), step => { + const pullWithStep = Effect.tap(pull, step); + return pullWithStep; +}))))); +/** + * Filters the output elements of a channel using a predicate function. + * Elements that don't match the predicate are discarded. + * + * **Example** (Filtering channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with mixed numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5, 6, 7, 8]) + * + * // Filter to keep only even numbers + * const evenChannel = Channel.filter(numbersChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(evenChannel)) // => [2, 4, 6, 8] + * + * // Filter with type refinement + * const mixedChannel = Channel.fromIterable([1, "hello", 2, "world", 3]) + * const numbersOnlyChannel = Channel.filter( + * mixedChannel, + * (value): value is number => typeof value === "number" + * ) + * Effect.runSync(Channel.runCollect(numbersOnlyChannel)) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return predicate(elem) ? Effect.succeed(elem) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering + * @since 4.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + const result = filter(elem); + return Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success); +})))))); +/** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return Effect.flatMap(predicate(elem), passes => passes ? Effect.succeed(elem) : Effect.flatMap(pull, loop)); +})))))); +/** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering + * @since 4.0.0 + */ +const filterMapEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => Effect.flatMap(pull, function loop(elem) { + return Effect.flatMap(filter(elem), result => Result.isFailure(result) ? Effect.flatMap(pull, loop) : Effect.succeed(result.success)); +})))))); +/** + * Filters arrays of elements emitted by a channel, applying the filter + * to each element within the arrays and only emitting non-empty filtered arrays. + * + * **Example** (Filtering array output) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect } from "effect" + * + * const nonEmptyArrayPredicate = Array.isReadonlyArrayNonEmpty + * + * // Create a channel that outputs arrays of mixed data + * const arrayChannel = Channel.fromIterable([ + * Array.make(1, 2, 3, 4, 5), + * Array.make(6, 7, 8, 9, 10), + * Array.make(11, 12, 13, 14, 15) + * ]).pipe(Channel.filter(nonEmptyArrayPredicate)) + * + * // Filter arrays to keep only even numbers + * const evenArraysChannel = Channel.filterArray(arrayChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(evenArraysChannel)) // => [[2, 4], [6, 8, 10], [12, 14]] + * // Note: Only non-empty filtered arrays are emitted + * + * // Arrays that would become empty after filtering are discarded entirely + * const oddChannel = Channel.fromIterable([ + * Array.make(1, 3, 5), + * Array.make(2, 4), + * Array.make(7, 9) + * ]).pipe(Channel.filter(nonEmptyArrayPredicate)) + * const filteredOddChannel = Channel.filterArray(oddChannel, (n) => n % 2 === 0) + * Effect.runSync(Channel.runCollect(filteredOddChannel)) // => [[2, 4]] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const filterArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + const passes = []; + for (let i = 0; i < arr.length; i++) { + if (predicate(arr[i])) { + passes.push(arr[i]); + } + } + return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering + * @since 4.0.0 + */ +const filterMapArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + const passes = []; + for (let i = 0; i < arr.length; i++) { + const result = filter(arr[i]); + if (Result.isSuccess(result)) { + passes.push(result.success); + } + } + return Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop); +})))))); +/** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, pull => { + const f = Effect.flatMap(pull, arr => Effect.filter(arr, predicate)); + return Effect.succeed(Effect.flatMap(f, function loop(arr) { + return Arr.isReadonlyArrayNonEmpty(arr) ? Effect.succeed(arr) : Effect.flatMap(f, loop); + })); +})))); +/** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering + * @since 4.0.0 + */ +const filterMapArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, pull => Effect.succeed(Effect.flatMap(pull, function loop(arr) { + return Effect.flatMap(Effect.filterMapEffect(arr, filter), passes => Arr.isReadonlyArrayNonEmpty(passes) ? Effect.succeed(passes) : Effect.flatMap(pull, loop)); +})))))); +/** + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4]) + * + * // Use mapAccum to create running sums and emit both current and sum + * const runningSum = Channel.mapAccum( + * numbersChannel, + * () => 0, // initial accumulator state + * (sum, current) => { + * const newSum = sum + current + * // Return [newState, outputValues] + * return [newSum, [current, newSum]] as const + * } + * ) + * // Using with Effect for async processing + * const asyncMapAccum = Channel.mapAccum( + * numbersChannel, + * () => "", + * (acc, value) => + * Effect.gen(function*() { + * const newAcc = acc + value.toString() + * return [newAcc, [`${value}-processed`, newAcc]] as const + * }) + * ) + * Effect.runSync(Channel.runCollect(runningSum)) // => [1, 1, 2, 3, 3, 6, 4, 10] + * Effect.runSync(Channel.runCollect(asyncMapAccum)) // => ["1-processed", "1", "2-processed", "12", "3-processed", "123", "4-processed", "1234"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, initial, f, options) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { + let state = initial(); + let current; + let index = 0; + let cause; + const pullNext = Effect.matchCauseEffect(pull, { + onFailure(cause_) { + cause = cause_; + const b = options?.onHalt && options.onHalt(state); + return b && b.length > 0 ? Effect.succeed([state, b]) : Effect.failCause(cause_); + }, + onSuccess(a) { + const b = f(state, a); + return Arr.isArray(b) ? Effect.succeed(b) : b; + } + }); + const pump = Effect.suspend(function loop() { + if (current === undefined) { + if (cause) return Effect.failCause(cause); + return Effect.flatMap(pullNext, ([newState, values]) => { + state = newState; + if (values.length === 0) { + return loop(); + } else if (values.length === 1) { + return Effect.succeed(values[0]); + } + current = values; + return loop(); + }); + } + const next = current[index++]; + if (index >= current.length) { + current = undefined; + index = 0; + } + return Effect.succeed(next); + }); + return pump; +}))))); +/** + * Transforms a channel statefully by scanning over its output with an accumulator function. + * Emits the intermediate results of the scan operation. + * + * **Example** (Scanning channel output) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Scan to create running sum + * const runningSumChannel = Channel.scan(numbersChannel, 0, (sum, n) => sum + n) + * Effect.runSync(Channel.runCollect(runningSumChannel)) // => [0, 1, 3, 6, 10, 15] + * // Note: emits the initial value and each intermediate result + * + * // Scan with string concatenation + * const wordsChannel = Channel.fromIterable(["hello", "world", "from", "effect"]) + * const sentenceChannel = Channel.scan( + * wordsChannel, + * "", + * (sentence, word) => sentence === "" ? word : `${sentence} ${word}` + * ) + * Effect.runSync(Channel.runCollect(sentenceChannel)) // => ["", "hello", "hello world", "hello world from", "hello world from effect"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a)))))); +/** + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. + * Emits the intermediate results of the scan operation. + * + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ScanError extends Data.TaggedError("ScanError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4]) + * + * // Effectful scan with async operations + * const asyncScanChannel = Channel.scanEffect( + * numbersChannel, + * "", + * (acc, value) => + * Effect.gen(function*() { + * return acc + value.toString() + * }) + * ) + * await Effect.runPromise(Channel.runCollect(asyncScanChannel)) // => ["", "1", "12", "123", "1234"] + * + * // Scan with error handling + * const errorHandlingScan = Channel.scanEffect( + * numbersChannel, + * 0, + * (sum, n) => { + * if (n < 0) { + * return Effect.fail(new ScanError({ reason: "negative number" })) + * } + * return Effect.succeed(sum + n) + * } + * ) + * await Effect.runPromise(Channel.runCollect(errorHandlingScan)) // => [0, 1, 3, 6, 10] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const scanEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => fromTransform((upstream, scope) => Effect.map(toTransform(self)(upstream, scope), pull => { + let state = initial; + let isFirst = true; + return Effect.suspend(() => { + if (isFirst) { + isFirst = false; + return Effect.succeed(state); + } + return Effect.map(Effect.flatMap(pull, a => f(state, a)), newState => { + state = newState; + return state; + }); + }); +}))))); +/** + * Catches any cause of failure from the channel and allows recovery by + * creating a new channel based on the caught cause. + * + * **Example** (Recovering from failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Data, Effect } from "effect" + * + * class ProcessError extends Data.TaggedError("ProcessError")<{ + * readonly reason: string + * }> {} + * + * class RecoveryError extends Data.TaggedError("RecoveryError")<{ + * readonly message: string + * }> {} + * + * // Create a failing channel + * const failingChannel = Channel.fail( + * new ProcessError({ reason: "network error" }) + * ) + * + * // Catch the cause and provide recovery + * const recoveredChannel = Channel.catchCause(failingChannel, (cause) => { + * if (Cause.hasFails(cause)) { + * return Channel.succeed("Recovered from failure") + * } + * return Channel.succeed("Recovered from interruption") + * }) + * + * Effect.runSync(Channel.runCollect(recoveredChannel)) // => ["Recovered from failure"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => { + let forkedScope = Scope.forkUnsafe(scope); + return Effect.map(toTransform(self)(upstream, forkedScope), pull => { + let currentPull = pull.pipe(Effect.catchCause(cause => { + if (Pull.isDoneCause(cause)) { + return Effect.failCause(cause); + } + const toClose = forkedScope; + forkedScope = Scope.forkUnsafe(scope); + return Scope.close(toClose, Exit.failCause(cause)).pipe(Effect.andThen(toTransform(f(cause))(upstream, forkedScope)), Effect.flatMap(childPull => { + currentPull = childPull; + return childPull; + })); + })); + return Effect.suspend(() => currentPull); + }); +})))); +/** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling + * @since 4.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catchCause(self, cause => fromEffectDrain(Effect.flatMap(f(cause), _ => Effect.failCause(cause))))))); +/** + * Catches causes of failure that match a specific filter, allowing + * conditional error recovery based on the type of failure. + * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, f) => catchCause(self, cause => { + return predicate(cause) ? f(cause) : failCause(cause); +})))); +/** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, filter, f) => catchCause(self, cause => { + const result = filter(cause); + return Result.isFailure(result) ? failCause(result.failure) : f(result.success, cause); +})))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catchCauseFilter(self, Cause.findError, e => f(e))))); + +/** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling + * @since 4.0.0 + */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => transformPull(self, pull => _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .tapError */.sFT(pull, err => _Cause_js__rspack_import_6/* .isDone */.$L(err) ? _Effect_js__rspack_import_3/* ["void"] */.rIH : _Effect_js__rspack_import_3/* .asVoid */.NLW(f(err)))))); +/** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling + * @since 4.0.0 + */ +const catchIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, predicate, f, orElse) => catch_(self, err => { + return predicate(err) ? f(err) : orElse ? orElse(err) : fail(err); +})))); +/** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, filter, f, orElse) => catch_(self, err => { + const result = filter(err); + return Result.isFailure(result) ? orElse ? orElse(result.failure) : fail(result.failure) : f(result.success); +})))); +/** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling + * @since 4.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); + return catchIf(self, pred, f, orElse); +}))); +/** + * Catches a specific reason within a tagged error. + * + * **Example** (Recovering from nested reasons) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const reason = new RateLimitError({ retryAfter: 60 }) + * const channel = Channel.fail(new AiError({ reason })) + * + * const recovered = channel.pipe( + * Channel.catchReason("AiError", "RateLimitError", (reason) => + * Channel.succeed(`retry: ${reason.retryAfter}`) + * ) + * ) + * Effect.runSync(Channel.runCollect(recovered)) // => ["retry: 60"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, errorTag, reasonTag, f, orElse) => catch_(self, error => { + if (isTagged(error, errorTag) && hasProperty(error, "reason")) { + const reason = error.reason; + if (isTagged(reason, reasonTag)) { + return f(reason, error); + } + return orElse ? orElse(reason, error) : fail(error); + } + return fail(error); +})))); +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, errorTag, cases, orElse) => { + let keys; + return catch_(self, error => { + if (isTagged(error, errorTag) && hasProperty(error, "reason") && hasProperty(error.reason, "_tag") && String.isString(error.reason._tag)) { + const reason = error.reason; + keys ??= new Set(Object.keys(cases)); + if (keys.has(reason._tag)) { + return cases[reason._tag](reason, error); + } + return orElse ? orElse(reason, error) : fail(error); + } + return fail(error); + }); +}))); +/** + * Promotes nested reason errors into the channel error, replacing the parent error. + * + * **Example** (Promoting nested reasons) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const reason = new RateLimitError({ retryAfter: 60 }) + * const channel = Channel.fail(new AiError({ reason })) + * + * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) + * Effect.runSync(Effect.exit(Channel.runCollect(unwrapped))) // => Exit.fail(reason) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const unwrapReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, errorTag) => catchFilter(self, error => isTagged(error, errorTag) && hasProperty(error, "reason") ? Result.succeed(error.reason) : Result.fail(error), fail)))); +/** + * Returns a new channel, which is the same as this one, except the failure + * value of the returned channel is created by applying the specified function + * to the failure value of this channel. + * + * @category error handling + * @since 2.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catch_(self, err => fail(f(err)))))); +/** + * Converts all errors in the channel to defects (unrecoverable failures). + * This is useful when you want to treat errors as programming errors. + * + * **Example** (Converting failures to defects) + * + * ```ts import.meta.vitest + * import { Cause, Channel, Data, Effect, Exit } from "effect" + * + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * readonly field: string + * }> {} + * + * // Create a channel that might fail + * const error = new ValidationError({ field: "email" }) + * const failingChannel = Channel.fail(error) + * + * // Convert failures to defects + * const fatalChannel = Channel.orDie(failingChannel) + * + * Effect.runSync(Effect.exit(Channel.runCollect(fatalChannel))) // => Exit.failCause(Cause.die(error)) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => catch_(self, die); +/** + * Ignores all errors in the channel, converting them to an empty channel. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the channel fails. + * + * @category error handling + * @since 4.0.0 + */ +const ignore = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, options) => { + if (!options?.log) { + return catch_(self, () => empty); + } + const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log); + return catch_(tapCause(self, cause => Cause.hasFails(cause) ? logEffect(cause) : Effect.void), () => empty); +}))); +const ignoreCause_ = self => catchCause(self, () => empty); +/** + * Ignores all errors in the channel including defects, converting them to an empty channel. + * + * **When to use** + * + * Use when a channel should become best-effort and all failure causes, including + * defects and interruptions, can be converted to empty output. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the channel fails. + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, options) => { + if (!options?.log) return ignoreCause_(self); + const logEffect = Effect.logWithLevel(options.log === true ? undefined : options.log); + return ignoreCause_(tapCause(self, cause => logEffect(cause))); +}))); +/** + * Returns a new channel that retries this channel according to the specified + * schedule whenever it fails. + * + * @category error handling + * @since 4.0.0 + */ +const retry = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => suspend(() => { + let step = undefined; + let meta = Schedule.CurrentMetadata.defaultValue(); + const selfWithMeta = provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)); + const withReset = onFirst(selfWithMeta, () => { + step = undefined; + return Effect.void; + }); + const resolvedSchedule = typeof schedule === "function" ? schedule(identity_) : schedule; + const loop = catch_(withReset, Effect.fnUntraced(function* (error) { + if (!step) { + step = yield* Schedule.toStepWithMetadata(resolvedSchedule); + } + meta = yield* step(error); + return loop; + }, (effect, error) => Pull.catchDone(effect, () => Effect.succeed(fail(error))), unwrap)); + return loop; +})))); +/** + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class SwitchError extends Data.TaggedError("SwitchError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel that outputs numbers + * const numberChannel = Channel.fromIterable([1, 2, 3]) + * + * // Switch to new channels based on each value + * const switchedChannel = Channel.switchMap( + * numberChannel, + * (n) => Channel.fromIterable([`value-${n}`]) + * ) + * + * await Effect.runPromise(Channel.runCollect(switchedChannel)) // => ["value-3"] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const switchMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, f, options) => self.pipe(map(f), mergeAll({ + ...options, + concurrency: options?.concurrency ?? 1, + switch: true +}))))); +/** + * Merges multiple channels with specified concurrency and buffering options. + * + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class MergeAllError extends Data.TaggedError("MergeAllError")<{ + * readonly reason: string + * }> {} + * + * // Create channels that output other channels + * const nestedChannels = Channel.fromIterable([ + * Channel.fromIterable([1, 2]), + * Channel.fromIterable([3, 4]), + * Channel.fromIterable([5, 6]) + * ]) + * + * // Merge all channels with bounded concurrency + * const mergedChannel = Channel.mergeAll({ + * concurrency: 1, + * bufferSize: 16 + * })(nestedChannels) + * + * await Effect.runPromise(Channel.runCollect(mergedChannel)) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const mergeAll = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (channels, { + bufferSize = 16, + concurrency, + switch: switch_ = false +}) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, scope, forkedScope) { + const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : Math.max(1, concurrency); + const semaphore = switch_ ? undefined : _Semaphore_js__rspack_import_11/* .makeUnsafe */.LZ(concurrencyN); + const doneLatch = yield* _Latch_js__rspack_import_14/* .make */.L8(true); + const fibers = new Set(); + const queue = yield* _Queue_js__rspack_import_9/* .bounded */.Mm(bufferSize); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_9/* .shutdown */.n_(queue)); + const pull = yield* toTransform(channels)(upstream, scope); + yield* _Effect_js__rspack_import_3/* .gen */.JkU(function* () { + while (true) { + let pullFiber; + if (semaphore) { + if (fibers.size < concurrencyN) { + yield* semaphore.take(1); + } else { + pullFiber = yield* _Effect_js__rspack_import_3/* .forkChild */.zhn(pull); + yield* _Effect_js__rspack_import_3/* .raceFirst */.KT6(semaphore.take(1), _Effect_js__rspack_import_3/* .andThen */.hgn(_Fiber_js__rspack_import_10/* .join */.fj(pullFiber), _Effect_js__rspack_import_3/* .never */.ZmZ)); + } + } + const channel = pullFiber === undefined ? yield* pull : yield* _Fiber_js__rspack_import_10/* .join */.fj(pullFiber); + const childScope = _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope); + const childPull = yield* toTransform(channel)(upstream, childScope); + while (fibers.size >= concurrencyN) { + const fiber = _Iterable_js__rspack_import_15/* .headUnsafe */.BK(fibers); + fibers.delete(fiber); + if (fibers.size === 0) yield* doneLatch.open; + yield* _Fiber_js__rspack_import_10/* .interrupt */.G(fiber); + } + const fiber = yield* childPull.pipe(_Effect_js__rspack_import_3/* .tap */.Mim(() => _Effect_js__rspack_import_3/* .yieldNow */.m9E), _Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_9/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r({ + disableYield: true + }), _Effect_js__rspack_import_3/* .onError */.S5A(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (cause) { + const halt = _Pull_js__rspack_import_5/* .filterDone */.Dc(cause); + yield* _Effect_js__rspack_import_3/* .exit */.NS5(_Scope_js__rspack_import_4/* .close */.VN(childScope, !_Result_js__rspack_import_16/* .isFailure */.N6(halt) ? _Exit_js__rspack_import_12/* .succeed */.Py(halt.success.value) : _Exit_js__rspack_import_12/* .failCause */.AT(halt.failure))); + if (!fibers.has(fiber)) return; + fibers.delete(fiber); + if (semaphore) yield* semaphore.release(1); + if (fibers.size === 0) yield* doneLatch.open; + if (_Result_js__rspack_import_16/* .isSuccess */.oJ(halt)) return; + return yield* _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause); + })), _Effect_js__rspack_import_3/* .forkChild */.zhn); + doneLatch.closeUnsafe(); + fibers.add(fiber); + } + }).pipe(_Effect_js__rspack_import_3/* .catchCause */.Tyx(cause => { + const halt = _Pull_js__rspack_import_5/* .filterDone */.Dc(cause); + if (_Result_js__rspack_import_16/* .isSuccess */.oJ(halt)) { + return doneLatch.whenOpen(_Queue_js__rspack_import_9/* .failCause */.AT(queue, cause)); + } + return _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause); + }), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + return _Queue_js__rspack_import_9/* .take */.s(queue); +}))); +/** + * Returns a new channel, which is the merge of this channel and the specified + * channel. + * + * **Example** (Merging channels) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create two channels + * const leftChannel = Channel.fromIterable([1, 2, 3]) + * const rightChannel = Channel.fromIterable(["a", "b", "c"]) + * + * // The default "both" strategy waits for both channels to complete + * const mergedChannel = Channel.merge(leftChannel, rightChannel) + * + * const values = await Effect.runPromise(Channel.runCollect(mergedChannel)) + * values.map(String).sort() // => ["1", "2", "3", "a", "b", "c"] + * ``` + * + * @category combining + * @since 4.0.0 + */ +const merge = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(args => isChannel(args[0]) && isChannel(args[1]), (left, right, options) => fromTransformBracket(_Effect_js__rspack_import_3/* .fnUntraced */.D9k(function* (upstream, _scope, forkedScope) { + const strategy = options?.haltStrategy ?? "both"; + const queue = yield* _Queue_js__rspack_import_9/* .bounded */.Mm(0); + yield* _Scope_js__rspack_import_4/* .addFinalizer */.U9(forkedScope, _Queue_js__rspack_import_9/* .shutdown */.n_(queue)); + let done = 0; + function onExit(side, cause) { + done++; + if (!_Pull_js__rspack_import_5/* .isDoneCause */.Og(cause)) { + return _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause); + } + switch (strategy) { + case "both": + { + return done === 2 ? _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause) : _Effect_js__rspack_import_3/* ["void"] */.rIH; + } + case "left": + case "right": + { + return side === strategy ? _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause) : _Effect_js__rspack_import_3/* ["void"] */.rIH; + } + case "either": + { + return _Queue_js__rspack_import_9/* .failCause */.AT(queue, cause); + } + } + } + const runSide = (side, channel, scope) => toTransform(channel)(upstream, scope).pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(pull => pull.pipe(_Effect_js__rspack_import_3/* .flatMap */.qIB(value => _Queue_js__rspack_import_9/* .offer */.x(queue, value)), _Effect_js__rspack_import_3/* .forever */.i4r)), _Effect_js__rspack_import_3/* .onError */.S5A(cause => _Effect_js__rspack_import_3/* .andThen */.hgn(_Scope_js__rspack_import_4/* .close */.VN(scope, _Pull_js__rspack_import_5/* .doneExitFromCause */.aU(cause)), onExit(side, cause))), _Effect_js__rspack_import_3/* .forkIn */.ar0(forkedScope)); + yield* runSide("left", left, _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope)); + yield* runSide("right", right, _Scope_js__rspack_import_4/* .forkUnsafe */.Fp(forkedScope)); + return _Queue_js__rspack_import_9/* .take */.s(queue); +}))); +/** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining + * @since 4.0.0 + */ +const mergeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => merge(self, fromEffectDrain(effect), { + haltStrategy: "left" +})))); +/** + * Splits upstream string chunks into lines, recognizing `\n`, `\r\n`, and + * standalone `\r` as line terminators. The behavior matches + * `String.linesIterator` regardless of how the input is chunked. + * + * **Details** + * + * A line terminator at the very end of the stream does **not** produce a + * trailing empty line (consistent with `String.linesIterator`). Conversely, + * if the stream ends without a terminator the final partial line is still + * emitted. + * + * **Example** (Splitting string chunks into lines) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const result = await Effect.runPromise(Stream.runCollect( + * Stream.splitLines(Stream.make("hel", "lo\r\nwor", "ld\n")) + * )) + * result // => ["hello", "world"] + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const splitLines = () => fromTransform((upstream, _scope) => Effect.sync(() => { + // Accumulates text that has not yet been terminated by a line break. + // Content is carried across chunks until a terminator is found. + let stringBuilder = ""; + // Set when a chunk ends with \r so the next chunk can check whether + // the following character is \n (completing a \r\n pair) or not + // (standalone \r, which is itself a line terminator). + let midCRLF = false; + // Remembers the upstream Done value after the first time the upstream + // signals completion, so subsequent pulls return Done immediately + // without pulling upstream again. + let done = Option.none(); + function splitLinesArray(chunk) { + const chunkBuilder = []; + function pushLine(segment) { + if (stringBuilder.length === 0) { + chunkBuilder.push(segment); + } else { + chunkBuilder.push(stringBuilder + segment); + stringBuilder = ""; + } + } + for (let i = 0; i < chunk.length; i++) { + const str = chunk[i]; + if (str.length !== 0) { + let from = 0; + let indexOfCR = str.indexOf("\r"); + let indexOfLF = str.indexOf("\n"); + if (midCRLF) { + if (indexOfLF === 0) { + pushLine(""); + from = 1; + indexOfLF = str.indexOf("\n", from); + } else { + pushLine(""); + } + midCRLF = false; + } + while (indexOfCR !== -1 || indexOfLF !== -1) { + if (indexOfCR === -1 || indexOfLF !== -1 && indexOfLF < indexOfCR) { + pushLine(str.substring(from, indexOfLF)); + from = indexOfLF + 1; + indexOfLF = str.indexOf("\n", from); + } else { + if (str.length === indexOfCR + 1) { + midCRLF = true; + indexOfCR = -1; + } else { + pushLine(str.substring(from, indexOfCR)); + from = indexOfCR + (indexOfLF === indexOfCR + 1 ? 2 : 1); + indexOfCR = str.indexOf("\r", from); + indexOfLF = str.indexOf("\n", from); + } + } + } + stringBuilder = stringBuilder + str.substring(from, str.length - (midCRLF ? 1 : 0)); + } + } + return Arr.isReadonlyArrayNonEmpty(chunkBuilder) ? chunkBuilder : null; + } + const pullOrFlush = Effect.suspend(() => { + if (done._tag === "Some") { + return Cause.done(done.value); + } + return Pull.matchEffect(upstream, { + onSuccess: loop, + onFailure: Effect.failCause, + onDone: leftover => { + done = Option.some(leftover); + if (stringBuilder.length > 0 || midCRLF) { + const last = stringBuilder; + stringBuilder = ""; + midCRLF = false; + return Effect.succeed([last]); + } + return Cause.done(leftover); + } + }); + }); + function loop(chunk) { + const lines = splitLinesArray(chunk); + return lines !== null ? Effect.succeed(lines) : pullOrFlush; + } + return pullOrFlush; +})); +/** + * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`. + * + * **Details** + * + * Input chunks are decoded with streaming enabled so multi-byte characters may + * span `Uint8Array` boundaries. The optional `encoding` and `options` are + * passed to `TextDecoder`. + * + * @category decoding + * @since 4.0.0 + */ +const decodeText = (encoding, options) => fromTransform((upstream, _scope) => Effect.sync(() => { + const decoder = new TextDecoder(encoding, options); + const streamOptions = { + stream: true + }; + return Effect.map(upstream, Arr.map(line => decoder.decode(line, streamOptions))); +})); +/** + * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`. + * + * **Details** + * + * Each string inside an emitted array is encoded independently. + * + * @category encoding + * @since 4.0.0 + */ +const encodeText = () => fromTransform((upstream, _scope) => Effect.sync(() => { + const encoder = new TextEncoder(); + return Effect.map(upstream, Arr.map(line => encoder.encode(line))); +})); +/** + * Returns a new channel that pipes the output of this channel into the + * specified channel. The returned channel has the input type of this channel, + * and the output type of the specified channel, terminating with the value of + * the specified channel. + * + * **Example** (Piping one channel into another) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class PipeError extends Data.TaggedError("PipeError")<{ + * readonly stage: string + * }> {} + * + * // Create source and transform channels + * const sourceChannel = Channel.fromIterable([1, 2, 3]) + * const transformChannel = Channel.map(sourceChannel, (n: number) => n * 2) + * + * // Pipe the source into the transform + * const pipedChannel = Channel.pipeTo(sourceChannel, transformChannel) + * + * Effect.runSync(Channel.runCollect(pipedChannel)) // => [2, 4, 6] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => toTransform(that)(upstream, scope)))))); +/** + * Returns a new channel that pipes the output of this channel into the + * specified channel and preserves this channel's failures without providing + * them to the other channel for observation. + * + * **Example** (Piping while preserving failures) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class SourceError extends Data.TaggedError("SourceError")<{ + * readonly code: number + * }> {} + * + * // Create a failing source channel + * const error = new SourceError({ code: 404 }) + * const failingSource = Channel.fail(error) + * const safeTransform = Channel.identity() + * + * // Pipe while preserving source failures + * const safePipedChannel = Channel.pipeToOrFail(failingSource, safeTransform) + * + * Effect.runSync(Effect.exit(Channel.runCollect(safePipedChannel))) // => Exit.fail(error) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeToOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromTransform((upstream, scope) => Effect.flatMap(toTransform(self)(upstream, scope), upstream => { + const upstreamPull = Effect.catchCause(upstream, cause => Pull.isDoneCause(cause) ? Effect.failCause(cause) : Effect.die(Cause.Done(cause))); + return Effect.map(toTransform(that)(upstreamPull, scope), pull => Effect.catchDefect(pull, defect => Cause.isDone(defect) ? Effect.failCause(defect.value) : Effect.die(defect))); +}))))); +/** + * Constructs a `Channel` from a scoped effect that will result in a + * `Channel` if successful. + * + * **Example** (Unwrapping channel effects) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class UnwrapError extends Data.TaggedError("UnwrapError")<{ + * readonly reason: string + * }> {} + * + * // Create an effect that produces a channel + * const channelEffect = Effect.succeed( + * Channel.fromIterable([1, 2, 3]) + * ) + * + * // Unwrap the effect to get the channel + * const unwrappedChannel = Channel.unwrap(channelEffect) + * + * Effect.runSync(Channel.runCollect(unwrappedChannel)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unwrap = channel => fromTransform((upstream, scope) => { + let pull; + return _Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (pull) return pull; + return channel.pipe(_Scope_js__rspack_import_4/* .provide */.Gt(scope), _Effect_js__rspack_import_3/* .flatMap */.qIB(channel => toTransform(channel)(upstream, scope)), _Effect_js__rspack_import_3/* .flatMap */.qIB(pull_ => pull = pull_)); + })); +}); +/** + * Runs a channel with a scope provided for the duration of the channel + * execution, removing the channel's `Scope` requirement. + * + * @category resource management + * @since 2.0.0 + */ +const scoped = self => fromTransformBracket((upstream, scope, forkedScope) => Effect.map(Scope.provide(toTransform(self)(upstream, scope), forkedScope), Scope.provide(forkedScope))); +/** + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. + * + * **Details** + * + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * // Create a base channel + * const baseChannel = Channel.fromIterable([1, 2, 3]) + * + * // Drain the embedded input while the base channel runs + * const embeddedChannel = Channel.embedInput( + * baseChannel, + * (upstream) => + * upstream.pipe( + * Effect.forever, + * Effect.ignore + * ) + * ) + * await Effect.runPromise(Channel.runCollect(embeddedChannel)) // => [1, 2, 3] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const embedInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, input) => fromTransformBracket((upstream, scope, forkedScope) => Effect.andThen(Effect.forkIn(input(upstream), forkedScope), toTransform(self)(Cause.done(), scope)))))); +/** + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs + * + * @category buffering + * @since 2.0.0 + */ +const buffer = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pull = yield* toTransform(self)(upstream, scope); + const queue = yield* Queue.make({ + capacity: options.capacity === "unbounded" ? undefined : options.capacity, + strategy: options.capacity === "unbounded" ? undefined : options.strategy + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* pull.pipe(Effect.flatMap(value => Queue.offer(queue, value)), Effect.forever({ + disableYield: true + }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope)); + return Queue.take(queue); +}))))); +/** + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays + * + * @category buffering + * @since 4.0.0 + */ +const bufferArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pull = yield* toTransform(self)(upstream, scope); + const queue = yield* Queue.make({ + capacity: options.capacity === "unbounded" ? undefined : options.capacity, + strategy: options.capacity === "unbounded" ? undefined : options.strategy + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* pull.pipe(Effect.flatMap(value => Queue.offerAll(queue, value)), Effect.forever({ + disableYield: true + }), Effect.onError(cause => Queue.failCause(queue, cause)), Effect.forkIn(scope)); + return Queue.takeAll(queue); +}))))); +/** + * Interrupts a channel when another effect completes. + * + * **When to use** + * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption + * @since 2.0.0 + */ +const interruptWhen = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, effect) => merge(self, fromPull(_Effect_js__rspack_import_3/* .succeed */.PyW(_Effect_js__rspack_import_3/* .flatMap */.qIB(effect, _Cause_js__rspack_import_6/* .done */.Vw))), { + haltStrategy: "either" +})); +/** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption + * @since 4.0.0 + */ +const haltWhen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => fromTransformBracket(Effect.fnUntraced(function* (upstream, scope, forkedScope) { + const pull = yield* toTransform(self)(upstream, scope); + const fiber = yield* Effect.forkIn(effect, forkedScope, { + startImmediately: true + }); + return Effect.suspend(() => { + const exit = fiber.pollUnsafe(); + return exit === undefined ? pull : Exit.match(exit, { + onFailure: Effect.failCause, + onSuccess: Cause.done + }); + }); +}))))); +/** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling + * @since 4.0.0 + */ +const onError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => onExit(self, exit => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void)))); +/** + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Exit } from "effect" + * + * class ExitError extends Data.TaggedError("ExitError")<{ + * readonly stage: string + * }> {} + * + * // Create a channel + * const dataChannel = Channel.fromIterable([1, 2, 3]) + * + * // Attach exit handler + * const exits: Array> = [] + * const channelWithExit = Channel.onExit(dataChannel, (exit) => { + * exits.push(exit) + * return Effect.void + * }) + * const observed = [await Effect.runPromise(Channel.runCollect(channelWithExit)), exits] // => [[1, 2, 3], [Exit.void]] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, finalizer) => fromTransformBracket((upstream, scope, forkedScope) => _Scope_js__rspack_import_4/* .addFinalizerExit */.a6(forkedScope, finalizer).pipe(_Effect_js__rspack_import_3/* .andThen */.hgn(toTransform(self)(upstream, scope))))); +/** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks + * @since 4.0.0 + */ +const onStart = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onStart) => unwrap(Effect.as(onStart, self))))); +/** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks + * @since 4.0.0 + */ +const onFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFirst) => transformPull(self, pull => Effect.sync(() => { + let isFirst = true; + const pullFirst = Effect.tap(pull, element => { + isFirst = false; + return onFirst(element); + }); + return Effect.suspend(() => isFirst ? pullFirst : pull); +}))))); +/** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks + * @since 4.0.0 + */ +const onEnd = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onEnd) => transformPull(self, pull => Effect.succeed(Pull.catchDone(pull, leftover => Effect.flatMap(onEnd, () => Cause.done(leftover)))))))); +/** + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class EnsureError extends Data.TaggedError("EnsureError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel + * const dataChannel = Channel.fromIterable([1, 2, 3]) + * + * // Ensure cleanup always runs + * const events: Array = [] + * const channelWithCleanup = Channel.ensuring( + * dataChannel, + * Effect.sync(() => events.push("cleanup")) + * ) + * const observed = [await Effect.runPromise(Channel.runCollect(channelWithCleanup)), events] // => [[1, 2, 3], ["cleanup"]] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => onExit(self, _ => finalizer)))); +const runWith = (self, f, onHalt) => _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + const scope = _Scope_js__rspack_import_4/* .makeUnsafe */.LZ(); + const makePull = toTransform(self)(_Cause_js__rspack_import_6/* .done */.Vw(), scope); + return _Pull_js__rspack_import_5/* .catchDone */.m8(_Effect_js__rspack_import_3/* .flatMap */.qIB(makePull, f), onHalt ? onHalt : _Effect_js__rspack_import_3/* .succeed */.PyW).pipe(_Effect_js__rspack_import_3/* .onExit */.cfM(exit => _Scope_js__rspack_import_4/* .close */.VN(scope, exit))); +}); +/** + * Creates a channel from the specified services. + * + * @category accessors + * @since 2.0.0 + */ +const contextWith = f => fromTransform((upstream, scope) => Effect.contextWith(context => toTransform(f(context))(upstream, scope))); +/** + * Provides a `Context` to the channel, removing the corresponding service + * requirements from the returned channel. + * + * @category providing services + * @since 2.0.0 + */ +const provideContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => fromTransform((upstream, scope) => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context)))))); +/** + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category providing services + * @since 2.0.0 + */ +const provideService = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, key, service) => fromTransform((upstream, scope) => _Effect_js__rspack_import_3/* .map */.TjK(_Effect_js__rspack_import_3/* .provideService */.PfK(toTransform(self)(upstream, scope), key, service), _Effect_js__rspack_import_3/* .provideService */.PfK(key, service)))); +/** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category providing services + * @since 4.0.0 + */ +const provideServiceEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => fromTransform((upstream, scope) => Effect.flatMap(service, s => toTransform(provideService(self, key, s))(upstream, scope)))))); +/** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category providing services + * @since 4.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, layer, options) => Context.isContext(layer) ? provideContext(self, layer) : fromTransform((upstream, scope) => Effect.flatMap(options?.local ? Layer.buildWithMemoMap(layer, Layer.makeMemoMapUnsafe(), scope) : Layer.buildWithScope(layer, scope), context => Effect.map(Effect.provideContext(toTransform(self)(upstream, scope), context), Effect.provideContext(context))))))); +/** + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromTransform((upstream, scope) => Effect.contextWith(context => { + const toProvide = f(context); + return toTransform(provideContext(self, toProvide))(upstream, scope); +}))))); +/** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category providing services + * @since 2.0.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service))))))); +/** + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = isChannel(arguments[0]); + const name = dataFirst ? arguments[1] : arguments[0]; + const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return withSpanImpl(self, name, options); + } + return self => withSpanImpl(self, name, options); +}; +const withSpanImpl = (self, name, options) => acquireUseRelease(Effect.makeSpan(name, options), span => provideService(self, ParentSpan, span), (span, exit) => Effect.withFiber(fiber => { + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(TracerTimingEnabled); + return endSpan(span, exit, clock, timingEnabled); +})); +/** + * The starting channel for Do notation, emitting an empty object. + * + * @category constructors + * @since 4.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, name, f) => map(self, elem => ({ + ...elem, + [name]: f(elem) +}))))); + +/** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category sequencing + * @since 4.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, name, f, options) => flatMap(self, elem => map(f(elem), b => ({ + ...elem, + [name]: b +})), options)))); +/** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category mapping + * @since 4.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, name) => map(self, elem => ({ + [name]: elem +}))))); +/** + * Runs a channel and counts the number of elements it outputs. + * + * **Example** (Counting channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class CountError extends Data.TaggedError("CountError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with multiple elements + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Count the elements + * const countEffect = Channel.runCount(numbersChannel) + * + * Effect.runSync(countEffect) // => 5 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runCount = self => runFold(self, () => 0, acc => acc + 1); +/** + * Runs a channel and discards all output elements, returning only the final result. + * + * **Example** (Draining channel output at runtime) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class DrainError extends Data.TaggedError("DrainError")<{ + * readonly stage: string + * }> {} + * + * // Create a channel that outputs elements and completes with a result + * const resultChannel = Channel.fromIterable([1, 2, 3]) + * const completedChannel = Channel.concat(resultChannel, Channel.end("completed")) + * + * // Drain all elements and get only the final result + * const drainEffect = Channel.runDrain(completedChannel) + * + * Effect.runSync(drainEffect) // => "completed" + * ``` + * + * @category running + * @since 2.0.0 + */ +const runDrain = self => runWith(self, pull => Effect.forever(pull, { + disableYield: true +})); +/** + * Runs a channel and applies an effect to each output element. + * + * **Example** (Running effects for each output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class ForEachError extends Data.TaggedError("ForEachError")<{ + * readonly element: unknown + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * // Run forEach to process each element + * const processed: Array = [] + * const forEachEffect = Channel.runForEach( + * numbersChannel, + * (n) => Effect.sync(() => processed.push(n)) + * ) + * + * await Effect.runPromise(forEachEffect) + * processed // => [1, 2, 3] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runForEach = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => runWith(self, pull => _Effect_js__rspack_import_3/* .forever */.i4r(_Effect_js__rspack_import_3/* .flatMap */.qIB(pull, f), { + disableYield: true +}))); +/** + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * + * @category running + * @since 4.0.0 + */ +const runForEachWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => runWith(self, pull => pull.pipe(Effect.flatMap(f), Effect.flatMap(cont => cont ? Effect.void : Cause.done()), Effect.forever({ + disableYield: true +})))))); +/** + * Concatenates a channel's `Uint8Array` chunks into a single `Uint8Array`. + * + * **Example** (Joining channel byte chunks) + * + * ```ts import.meta.vitest + * import { Channel, Effect } from "effect" + * + * const channel = Channel.fromArray([ + * [new Uint8Array([1, 2])], + * [new Uint8Array([3, 4])] + * ] as const) + * + * const bytes = Effect.runSync(Channel.mkUint8Array(channel)) + * Array.from(bytes) // => [1, 2, 3, 4] + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source channel must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category running + * @since 4.0.0 + */ +const mkUint8Array = self => Effect.map(runFold(self, () => ({ + bytes: 0, + arrays: [] +}), (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc.bytes += chunk[i].length; + acc.arrays.push(chunk[i]); + } + return acc; +}), ({ + arrays, + bytes +}) => { + const result = new Uint8Array(bytes); + let offset = 0; + for (let i = 0; i < arrays.length; i++) { + const array = arrays[i]; + result.set(array, offset); + offset += array.length; + } + return result; +}); +/** + * Runs a channel and collects all output elements into an array. + * + * **Example** (Collecting channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class CollectError extends Data.TaggedError("CollectError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel with elements + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Collect all elements into an array + * const collectEffect = Channel.runCollect(numbersChannel) + * + * Effect.runSync(collectEffect) // => [1, 2, 3, 4, 5] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runCollect = self => runFold(self, () => [], (acc, o) => { + acc.push(o); + return acc; +}); +/** + * Runs a channel and outputs the done value. + * + * @category running + * @since 4.0.0 + */ +const runDone = self => runWith(self, identity_, Effect.succeed); +/** + * Runs a channel until the first output element is available, returning it in + * an `Option`. + * + * **Details** + * + * Returns `Option.some` with the first output element, or `Option.none` if the + * channel completes without emitting output. + * + * @category running + * @since 4.0.0 + */ +const runHead = self => Effect.suspend(() => { + let head = Option.none(); + return runWith(self, pull => pull.pipe(Effect.asSome, Effect.flatMap(head_ => { + head = head_; + return Cause.done(); + })), () => Effect.succeed(head)); +}); +/** + * Runs a channel to completion and returns the last output element in an + * `Option`. + * + * **Details** + * + * Returns `Option.some` with the last emitted element, or `Option.none` if the + * channel completes without emitting output. + * + * @category running + * @since 4.0.0 + */ +const runLast = self => Effect.suspend(() => { + const absent = Symbol(); // Prevent boxing + let last = absent; + return runWith(self, pull => Effect.forever(Effect.flatMap(pull, item => { + last = item; + return Effect.void; + }), { + disableYield: true + }), () => last === absent ? Effect.succeedNone : Effect.succeedSome(last)); +}); +/** + * Runs a channel and folds over all output elements with an accumulator. + * + * **Example** (Folding channel output) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class FoldError extends Data.TaggedError("FoldError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel with numbers + * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Fold to calculate sum + * const sumEffect = Channel.runFold(numbersChannel, () => 0, (acc, n) => acc + n) + * + * Effect.runSync(sumEffect) // => 15 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runFold = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Effect.suspend(() => { + let state = initial(); + return runWith(self, pull => Effect.whileLoop({ + while: constTrue, + body: () => pull, + step: value => { + state = f(state, value); + } + }), () => Effect.succeed(state)); +})))); +/** + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * + * @category running + * @since 4.0.0 + */ +const runFoldEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Effect.suspend(() => { + let state = initial(); + return runWith(self, pull => Effect.whileLoop({ + while: constTrue, + body: constant(pull.pipe(Effect.flatMap(o => f(state, o)), Effect.map(s => { + state = s; + }))), + step: constVoid + }), () => Effect.succeed(state)); +})))); +/** + * Converts a channel to a scoped `Pull` for low-level consumption. + * + * **Details** + * + * The effect requires a `Scope`. The returned pull should be consumed only + * while that scope remains open. Pulls are serialized so only one pull is + * evaluated at a time. + * + * **Example** (Converting channels to pulls) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect } from "effect" + * + * class PullError extends Data.TaggedError("PullError")<{ + * readonly step: string + * }> {} + * + * // Create a channel + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * const program = Effect.scoped(Effect.gen(function*() { + * const pull = yield* Channel.toPull(numbersChannel) + * return [yield* pull, yield* pull, yield* pull] + * })) + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPull = /*#__PURE__*/(/* unused pure expression or super */ null && (Effect.fnUntraced(function* (self) { + const semaphore = Semaphore.makeUnsafe(1); + const context = yield* Effect.context(); + const scope = Context.get(context, Scope.Scope); + const pull = yield* toTransform(self)(Cause.done(), scope); + return pull.pipe(Effect.provideContext(context), semaphore.withPermits(1)); +}, +/*#__PURE__*/ +// ensure errors are redirected to the pull effect +Effect.catchCause(cause => Effect.succeed(Effect.failCause(cause)))))); +/** + * Converts a channel to a Pull within an existing scope. + * + * **Example** (Converting channels to scoped pulls) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Scope } from "effect" + * + * class ScopedPullError extends Data.TaggedError("ScopedPullError")<{ + * readonly reason: string + * }> {} + * + * // Create a channel + * const numbersChannel = Channel.fromIterable([1, 2, 3]) + * + * // Convert to Pull with explicit scope + * const scopedPullEffect = Effect.gen(function*() { + * const scope = yield* Effect.scope + * const pull = yield* Channel.toPullScoped(numbersChannel, scope) + * return [yield* pull, yield* pull, yield* pull] + * }) + * await Effect.runPromise(Effect.scoped(scopedPullEffect)) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toPullScoped = (self, scope) => toTransform(self)(_Cause_js__rspack_import_6/* .done */.Vw(), scope); +/** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offer(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { + if (Exit.isSuccess(exit)) { + Queue.endUnsafe(queue); + } else { + Queue.failCauseUnsafe(queue, exit.cause); + } + return Effect.void; +})))))); +/** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoQueueArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, queue) => Effect.uninterruptibleMask(restore => runForEach(self, value => Queue.offerAll(queue, value)).pipe(restore, Effect.exit, Effect.flatMap(exit => { + if (Exit.isSuccess(exit)) { + Queue.endUnsafe(queue); + } else { + Queue.failCauseUnsafe(queue, exit.cause); + } + return Effect.void; +})))))); +/** + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) + * + * ```ts import.meta.vitest + * import { Channel, Data, Effect, Queue } from "effect" + * + * class QueueError extends Data.TaggedError("QueueError")<{ + * readonly operation: string + * }> {} + * + * // Create a channel with data + * const dataChannel = Channel.fromIterable([1, 2, 3, 4, 5]) + * + * // Convert to queue for concurrent processing + * const program = Effect.scoped(Effect.gen(function*() { + * const queue = yield* Channel.toQueue(dataChannel, { capacity: 32 }) + * return yield* Queue.takeBetween(queue, 5, 5) + * })) + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const scope = yield* Effect.scope; + const queue = yield* Queue.make({ + capacity: typeof options.capacity === "number" ? options.capacity : undefined, + strategy: typeof options.capacity === "number" ? options.strategy : undefined + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* Effect.forkIn(runIntoQueue(self, queue), scope); + return queue; +})))); +/** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors + * @since 4.0.0 + */ +const toQueueArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const scope = yield* Effect.scope; + const queue = yield* Queue.make({ + capacity: typeof options.capacity === "number" ? options.capacity : undefined, + strategy: typeof options.capacity === "number" ? options.strategy : undefined + }); + yield* Scope.addFinalizer(scope, Queue.shutdown(queue)); + yield* Effect.forkIn(runIntoQueueArray(self, queue), scope); + return queue; +})))); +/** + * Converts a channel to a PubSub for concurrent consumption. + * + * **Details** + * + * `shutdownOnEnd` indicates whether the PubSub should be shut down when the + * channel ends. By default this is `true`. + * + * @category destructors + * @since 2.0.0 + */ +const toPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* Effect.forkScoped(runIntoPubSub(self, pubsub, { + shutdownOnEnd: options.shutdownOnEnd !== false + })); + return pubsub; +})))); +/** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publish(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)))); +const makePubSub = options => Effect.acquireRelease(options.capacity === "unbounded" ? PubSub.unbounded(options) : options.strategy === "dropping" ? PubSub.dropping(options) : options.strategy === "sliding" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown); +/** + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* Effect.forkScoped(runIntoPubSubArray(self, pubsub, { + shutdownOnEnd: options.shutdownOnEnd !== false + })); + return pubsub; +})))); +/** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors + * @since 4.0.0 + */ +const runIntoPubSubArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isChannel(args[0]), (self, pubsub, options) => runForEach(self, value => PubSub.publishAll(pubsub, value)).pipe(options?.shutdownOnEnd === true ? Effect.ensuring(PubSub.shutdown(pubsub)) : identity_)))); +/** + * Converts a channel to a scoped `PubSub` of `Take` values. + * + * **Details** + * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubTake = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + yield* runForEach(self, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped); + return pubsub; +})))); +//# sourceMappingURL=Channel.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Ie: empty, + OB: fromPull, + Pf: provideService, + Py: succeed, + S6: interruptWhen, + Tj: map, + WK: mapEffect, + Z1: fromTransform, + Zm: never, + cf: onExit, + ed: flattenArray, + fp: fromReadableStream, + lB: toPullScoped, + o1: runForEach, + oA: unwrap, + qI: flatMap, + sF: tapError +}); + + +}, +"./node_modules/effect/dist/Clock.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + +/** + * Context reference for the active time service in the environment. + * + * **When to use** + * + * Use when you need to access or provide the full time service, including sleep + * operations, rather than a single timestamp accessor. + * + * **Example** (Accessing the Clock service) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * const program = Effect.gen(function*() { + * const clock = yield* Clock.Clock + * return clock.currentTimeMillisUnsafe() + * }) + * + * await Effect.runPromise(Effect.provideService(program, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link clockWith} for using the current Clock service inside an effect + * @see {@link currentTimeMillis} for reading the current time in milliseconds + * @see {@link currentTimeNanos} for reading the current time in nanoseconds + * + * @category services + * @since 2.0.0 + */ +const Clock = _internal_effect_js__rspack_import_0/* .ClockRef */.a1U; +/** + * Accesses the current Clock service and uses it to run the provided function. + * + * **When to use** + * + * Use when you need the full Clock service interface to perform multiple time + * operations or call unsafe variants within a single effect. + * + * **Example** (Accessing the current Clock service) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * const program = Clock.clockWith((clock) => Effect.sync(() => clock.currentTimeMillisUnsafe())) + * + * await Effect.runPromise(Effect.provideService(program, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link Clock} for the service reference + * @see {@link currentTimeMillis} for convenience accessor that returns milliseconds + * @see {@link currentTimeNanos} for convenience accessor that returns nanoseconds + * @category accessors + * @since 2.0.0 + */ +const clockWith = _internal_effect_js__rspack_import_0/* .clockWith */.RKA; +/** + * Returns an Effect that succeeds with the current Unix time in milliseconds. + * + * **When to use** + * + * Use to create wall-clock timestamps from the active `Clock` service with + * millisecond precision. + * + * **Gotchas** + * + * The value can move backward or forward when the system wall clock is + * corrected, so it is not suitable for measuring elapsed time. + * + * **Example** (Reading milliseconds) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * await Effect.runPromise(Effect.provideService(Clock.currentTimeMillis, Clock.Clock, testClock)) // => 1_000 + * ``` + * + * @see {@link currentTimeNanos} for nanosecond precision + * @see {@link monotonicTimeNanos} for measuring elapsed time + * @see {@link clockWith} for accessing the full Clock service + * + * @category accessors + * @since 2.0.0 + */ +const currentTimeMillis = _internal_effect_js__rspack_import_0/* .currentTimeMillis */.Rud; +/** + * Returns an Effect that succeeds with the current Unix time in nanoseconds. + * + * **When to use** + * + * Use to create wall-clock timestamps from the active `Clock` service with + * nanosecond precision. + * + * **Gotchas** + * + * The value can move backward or forward when the system wall clock is + * corrected, so it is not suitable for measuring elapsed time. + * The live clock allows up to one second of drift from `Date.now()` before + * re-anchoring. + * + * **Example** (Reading nanoseconds) + * + * ```ts import.meta.vitest + * import { Clock, Effect } from "effect" + * + * const testClock: Clock.Clock = { + * currentTimeMillisUnsafe: () => 1_000, + * currentTimeMillis: Effect.succeed(1_000), + * monotonicTimeNanosUnsafe: () => 1_000_000_000n, + * monotonicTimeNanos: Effect.succeed(1_000_000_000n), + * currentTimeNanosUnsafe: () => 1_000_000_000n, + * currentTimeNanos: Effect.succeed(1_000_000_000n), + * sleep: () => Effect.void + * } + * + * await Effect.runPromise(Effect.provideService(Clock.currentTimeNanos, Clock.Clock, testClock)) // => 1_000_000_000n + * ``` + * + * @see {@link monotonicTimeNanos} for measuring elapsed time + * + * @category accessors + * @since 2.0.0 + */ +const currentTimeNanos = _internal_effect_js__rspack_import_0/* .currentTimeNanos */.s0X; +/** + * Returns an Effect that succeeds with the current monotonic time in + * nanoseconds. + * + * **When to use** + * + * Use to measure elapsed time by subtracting two readings. + * + * **Gotchas** + * + * The value has an arbitrary origin and is unsuitable for serialization. Use + * it only to subtract readings produced by the same clock. Whether it advances + * while the host is suspended depends on the runtime. + * + * @see {@link currentTimeNanos} for Unix wall-clock timestamps + * + * @category accessors + * @since 4.0.0 + */ +const monotonicTimeNanos = _internal_effect_js__rspack_import_0/* .monotonicTimeNanos */.T13; +//# sourceMappingURL=Clock.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + zD: Clock +}); + + +}, +"./node_modules/effect/dist/Combiner.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Creates a `Combiner` from a binary function. + * + * **When to use** + * + * Use when you have a custom combining operation that is not covered by + * the built-in constructors (`min`, `max`, `first`, `last`, `constant`). + * + * **Details** + * + * The returned combiner's `combine` method delegates to the provided function. + * Any purity, associativity, or mutation behavior comes from that function. + * + * **Example** (Multiplying numbers) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Product = Combiner.make((self, that) => self * that) + * + * Product.combine(3, 5) // => 15 + * ``` + * + * @see {@link Combiner} – the interface this creates + * @category constructors + * @since 4.0.0 + */ +function make(combine) { + return { + combine + }; +} +/** + * Reverses the argument order of a combiner's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative combiner such as string concatenation. + * + * **Details** + * + * Returns a new `Combiner` where `combine(self, that)` calls the original + * combiner as `combine(that, self)`. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const Prepend = Combiner.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function flip(combiner) { + return make((self, that) => combiner.combine(that, self)); +} +/** + * Creates a `Combiner` that returns the smaller of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the minimum value across a collection or + * build a `Reducer` that tracks the running minimum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the minimum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Min = Combiner.min(Number.Order) + * + * Min.combine(3, 1) // => 1 + * Min.combine(1, 3) // => 1 + * ``` + * + * @see {@link max} + * @category constructors + * @since 4.0.0 + */ +function min(order) { + return make((self, that) => order(self, that) === -1 ? self : that); +} +/** + * Creates a `Combiner` that returns the larger of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the maximum value across a collection or + * build a `Reducer` that tracks the running maximum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the maximum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Max = Combiner.max(Number.Order) + * + * Max.combine(3, 1) // => 3 + * Max.combine(1, 3) // => 3 + * ``` + * + * @see {@link min} + * @category constructors + * @since 4.0.0 + */ +function max(order) { + return make((self, that) => order(self, that) === 1 ? self : that); +} +/** + * Creates a `Combiner` that always returns the first (left) argument. + * + * **When to use** + * + * Use when you want "first write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `self` and ignores `that`. + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const First = Combiner.first() + * + * First.combine(1, 2) // => 1 + * ``` + * + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function first() { + return make((self, _) => self); +} +/** + * Creates a `Combiner` that always returns the last (right) argument. + * + * **When to use** + * + * Use when you want "last write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `that` and ignores `self`. + * + * **Example** (Keeping the last value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Last = Combiner.last() + * + * Last.combine(1, 2) // => 2 + * ``` + * + * @see {@link first} + * @category constructors + * @since 4.0.0 + */ +function last() { + return make((_, that) => that); +} +/** + * Creates a `Combiner` that ignores both arguments and always returns the + * given constant value. + * + * **When to use** + * + * Use when you need a combiner that always returns a fixed value, including + * when a generic API requires a combiner but the result is predetermined. + * + * **Details** + * + * `combine(self, that)` returns the constant `a` and ignores both arguments. + * + * **Example** (Always returning zero) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Zero = Combiner.constant(0) + * + * Zero.combine(42, 99) // => 0 + * ``` + * + * @see {@link first} + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function constant(a) { + return make(() => a); +} +/** + * Wraps a `Combiner` so that a separator value is inserted between every + * pair of combined elements. + * + * **When to use** + * + * Use when you need to inject a fixed separator between accumulated values, + * such as when building delimited strings, paths, or CSV-like output by + * repeated combination. + * + * **Details** + * + * `intercalate(middle)(combiner).combine(self, that)` is equivalent to + * `combiner.combine(self, combiner.combine(middle, that))`. This function is + * curried: first provide the separator, then the base combiner. + * + * **Example** (Joining strings with a separator) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const commaSep = Combiner.intercalate(",")(String.ReducerConcat) + * + * commaSep.combine("a", "b") // => "a,b" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function intercalate(middle) { + return combiner => make((self, that) => combiner.combine(self, combiner.combine(middle, that))); +} +//# sourceMappingURL=Combiner.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make) +}); + + +}, +"./node_modules/effect/dist/Context.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Effectable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Effectable.js"); +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _Option_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); + + + + + + + +/** + * Runtime type identifier attached to `Context` service keys and used by + * `isKey` to recognize them. + * + * @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 + * + * @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__*/_Effectable_js__rspack_import_0/* .Prototype */.b({ + label: "Service", + evaluate(fiber) { + return (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => f(get(fiber.context, this))); + }, + useSync(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId = "~effect/Context"; +const MaxDepth = 8; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = undefined; + self.baseHits = 0; + 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 makeUnsafe(map); +}; +// A private symbol so user code cannot forge a value that reads as absent +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); + // Misses must not advance the counter: reference-default lookups miss the + // base on every fiber cache refresh, which would flatten every short-lived + // request context and reintroduce the O(services) per-request cost + if (value === undefined && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = undefined; + 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. + * + * **Gotchas** + * + * 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 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = mapUnsafe => makeImpl(undefined, mapUnsafe, undefined, 0); +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ..._internal_core_js__rspack_import_1/* .PipeInspectableProto */.fU, + [TypeId]: { + _Services: _ => _ + }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](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) || !_Equal_js__rspack_import_2/* .equals */.aI(value, other.get(key))) return false; + } + return true; + }, + [_Hash_js__rspack_import_3/* .symbol */.HR]() { + return _Hash_js__rspack_import_3/* .number */.ai(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 + * + * @category guards + * @since 2.0.0 + */ +const isContext = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether the provided argument is a `Key`. + * + * **Example** (Checking for keys) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * Context.isKey(Context.Service("Service")) // => true + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isKey = u => hasProperty(u, ServiceTypeId); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => emptyContext; +const emptyContext = /*#__PURE__*/makeUnsafe(/*#__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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = (key, service) => makeUnsafe(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` + * + * @category combining + * @since 2.0.0 + */ +const add = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** + * Adds a service by key to a given `Context` using a string key. + * + * @category combining + * @since 4.0.0 + */ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? undefined : impl.cacheRoot; + if (impl.depth >= MaxDepth) { + // Rebase the overlay chain into a flat map, keeping the cacheRoot so a + // rebase on an ordinary key does not invalidate fiber caches + const map = new Map(impl.mapUnsafe); + map.set(key, service); + return makeImpl(cacheRoot, map, undefined, 0); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1); +}; +/** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts import.meta.vitest + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * Context.getOption(withPort, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(withoutPort, Port) // => Option.none() + * ``` + * + * @see {@link add} for always storing a service value + * + * @category combining + * @since 4.0.0 + */ +const addOrOmit = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => service._tag === "None" ? omit(key)(self) : add(self, key, service.value)))); +/** + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * + * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") + * const Database = Context.Service<{ query: (sql: string) => string }>( + * "Database" + * ) + * + * const context = Context.make(Logger, { log: (_msg: string) => {} }) + * + * const logger = Context.getOrElse(context, Logger, () => ({ log: () => {} })) + * const database = Context.getOrElse( + * context, + * Database, + * () => ({ query: () => "fallback" }) + * ) + * + * logger === Context.get(context, Logger) // => true + * database.query("SELECT 1") // => "fallback" + * ``` + * + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, orElse) => { + const value = lookup(self, key.key); + if (value !== notFound) return value; + return isReference(key) ? getDefaultValue(key) : orElse(); +}))); +/** + * 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 + * + * @category getters + * @since 4.0.0 + */ +const getOrUndefined = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? undefined : 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 + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @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 = 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 + * + * @category getters + * @since 2.0.0 + */ +const getOption = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, service) => { + const value = lookup(self, service.key); + if (value !== notFound) return _Option_js__rspack_import_6.some(value); + return isReference(service) ? _Option_js__rspack_import_6.some(getDefaultValue(service)) : _Option_js__rspack_import_6.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 + * + * @category combining + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @category combining + * @since 3.12.0 + */ +const mergeAll = (...ctxs) => { + const map = new Map(); + for (let i = 0; i < ctxs.length; i++) { + ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + } + return makeUnsafe(map); +}; +/** + * Returns a new `Context` that contains only the specified services. + * + * **When to use** + * + * Use when you want to keep an allowlist of services in a `Context`. + * + * **Example** (Picking services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.pick(Port)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link omit} for removing selected services + * + * @category filtering + * @since 2.0.0 + */ +const pick = (...services) => self => { + const keep = new Set(services.map(key => key.key)); + return withFlat(self, map => map.forEach((_, key) => { + if (!keep.has(key)) map.delete(key); + })); +}; +/** + * Returns a new `Context` with the specified service keys removed. + * + * **When to use** + * + * Use when you want to remove a denylist of services from a `Context`. + * + * **Example** (Omitting services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.omit(Timeout)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link pick} for keeping selected services + * + * @category filtering + * @since 2.0.0 + */ +const omit = (...keys) => self => withFlat(self, map => { + for (let i = 0; i < keys.length; i++) { + map.delete(keys[i].key); + } +}); +/** + * 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 + * + * @category services + * @since 3.11.0 + */ +const Reference = Service; +//# sourceMappingURL=Context.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Ie: empty, + Jt: get, + L8: make, + LZ: makeUnsafe, + Or: Reference, + Pf: hasSameCache, + Ub: getOrUndefinedUnsafe, + Um: mergeAll, + WQ: add, + Y6: getOrUndefined, + aE: isContext, + fp: getUnsafe, + h1: merge, + kl: Service, + om: getOption +}); + + +}, +"./node_modules/effect/dist/Deferred.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); + + + + + + +const TypeId = "~effect/Deferred"; +/** + * Checks whether a value is a `Deferred`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Deferred` values. + * + * @category guards + * @since 4.0.0 + */ +const isDeferred = u => hasProperty(u, TypeId); +const DeferredProto = { + [TypeId]: { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const makeUnsafe = () => { + const self = Object.create(DeferredProto); + self.resumes = undefined; + self.effect = undefined; + return self; +}; +/** + * Creates a new `Deferred`. + * + * **When to use** + * + * Use to allocate an empty `Deferred` inside an `Effect` workflow. + * + * **Example** (Creating a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = () => _internal_effect_js__rspack_import_2/* .sync */.OH5(() => makeUnsafe()); +const _await = self => _internal_effect_js__rspack_import_2/* .callback */.E2r(resume => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return _internal_effect_js__rspack_import_2/* .sync */.OH5(() => { + // Completion resumes all waiters and clears `resumes`, so a cleanup + // running after completion has nothing to unregister. + const resumes = self.resumes; + if (resumes === undefined) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); + +/** + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. + * + * **When to use** + * + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.complete(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.suspend(() => self.effect ? internalEffect.succeed(false) : into(effect, self))))); +/** + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.completeWith(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion + * @since 2.0.0 + */ +const completeWith = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, effect) => _internal_effect_js__rspack_import_2/* .sync */.OH5(() => doneUnsafe(self, effect))); +/** + * Completes the `Deferred` with the specified `Exit` value, which will be + * propagated to all fibers waiting on the value of the `Deferred`. + * + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.done(deferred, Exit.succeed(42)) + * return yield* Effect.exit(Deferred.await(deferred)) + * }) + * + * await Effect.runPromise(program) // => Exit.succeed(42) + * ``` + * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion + * @since 2.0.0 + */ +const done = completeWith; +/** + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.fail(deferred, "Operation failed") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Operation failed")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, error) => done(self, _internal_core_js__rspack_import_3/* .exitFail */.Rk(error))); +/** + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failSync(deferred, () => "Lazy error") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Lazy error")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => fail(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCause(deferred, Cause.fail("Operation failed")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Operation failed"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => done(self, core.exitFailCause(cause))))); +/** + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCauseSync(deferred, () => Cause.fail("Lazy error")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Lazy error"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCauseSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => failCause(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Something went wrong") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.die(deferred, defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const die = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, defect) => done(self, core.exitDie(defect))))); +/** + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Lazy error") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.dieSync(deferred, () => defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const dieSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => die(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with interruption by the current fiber. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by the current fiber. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with the current fiber id + * only if this call completes it. The returned effect succeeds with `true` + * when this call completed the `Deferred`, or `false` if it was already + * completed. + * + * **Example** (Interrupting a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interrupt(deferred) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] as const + * }) + * + * const [success, exit] = await Effect.runPromise(program) + * success // => true + * Exit.hasInterrupts(exit) // => true + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interrupt = self => core.withFiber(fiber => interruptWith(self, fiber.id)); +/** + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interruptWith(deferred, 42) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.interrupt(42)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interruptWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, fiberId) => failCause(self, internalEffect.causeInterrupt(fiberId))))); +/** + * Returns `true` if this `Deferred` has already been completed with a value or + * an error, `false` otherwise. + * + * **When to use** + * + * Use to check completion status inside an `Effect` workflow. + * + * **Example** (Checking Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.isDone(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.isDone(deferred) + * return [beforeCompletion, afterCompletion] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isDone = self => internalEffect.sync(() => isDoneUnsafe(self)); +/** + * Returns whether this `Deferred` has already been completed synchronously. + * + * **When to use** + * + * Use to check `Deferred` completion synchronously in code that cannot return + * an `Effect`, such as low-level integration code. + * + * @see {@link isDone} for checking completion inside `Effect` + * @see {@link poll} for reading the completed effect when available + * + * @category predicates + * @since 4.0.0 + */ +const isDoneUnsafe = self => self.effect !== undefined; +/** + * Returns the current completion effect as an `Option`. This returns + * `Option.some(effect)` when the `Deferred` is completed, `Option.none()` + * otherwise. + * + * **When to use** + * + * Use to inspect whether a `Deferred` is already completed and retrieve its + * stored completion effect when available. + * + * **Example** (Polling Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Option } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.poll(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.poll(deferred) + * const afterValue = yield* Effect.transposeOption(afterCompletion) + * return [beforeCompletion, afterValue] + * }) + * + * await Effect.runPromise(program) // => [Option.none(), Option.some(42)] + * ``` + * + * @category getters + * @since 2.0.0 + */ +function poll(self) { + return internalEffect.sync(() => Option.fromUndefinedOr(self.effect)); +} +/** + * Attempts to complete the `Deferred` with the specified value. + * + * **When to use** + * + * Use to complete a `Deferred` with a successful value. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, value) => done(self, _internal_core_js__rspack_import_3/* .exitSucceed */.xt(value))); +/** + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.sync(deferred, () => 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const sync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => succeed(self, evaluate()))))); +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + // Clear `resumes` before resuming: a waiter resumed with an interrupt + // cause dies synchronously inside `resume`, and its await cleanup would + // otherwise splice this array mid-iteration and skip the next waiter. + const resumes = self.resumes; + self.resumes = undefined; + for (let i = 0; i < resumes.length; i++) { + resumes[i](effect); + } + } + return true; +}; +/** + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. + * + * **Details** + * + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const successEffect = Effect.succeed(42) + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const isCompleted = yield* Deferred.into(successEffect, deferred) + * const value = yield* Deferred.await(deferred) + * return [isCompleted, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const into = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, deferred) => internalEffect.uninterruptibleMask(restore => internalEffect.flatMap(internalEffect.exit(restore(self)), exit => done(deferred, exit)))))); +//# sourceMappingURL=Deferred.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L8: make, + LZ: makeUnsafe, + Py: succeed, + Tx: _await, + Vw: done, + fJ: fail +}); + + +}, +"./node_modules/effect/dist/Duration.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Represents immutable spans of time. + * + * A `Duration` can be finite, positive infinity, or negative infinity. It is + * the standard representation for delays, timeouts, intervals, and + * time-to-live values across Effect APIs. This module includes constructors + * from common input shapes, unit conversions, comparisons, arithmetic, + * formatting, and reusable reducer or combiner helpers. + * + * @since 2.0.0 + */ + + + + + + + + + + +const TypeId = "~effect/time/Duration"; +const bigint0 = /*#__PURE__*/BigInt(0); +const bigint1 = /*#__PURE__*/BigInt(1); +const bigint2 = /*#__PURE__*/BigInt(2); +const bigint10 = /*#__PURE__*/BigInt(10); +const bigint24 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(24))); +const bigint60 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(60))); +const bigint1e3 = /*#__PURE__*/BigInt(1_000); +const bigint1e6 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000))); +const bigint1e9 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000_000))); +const roundTiesAwayFromZero = input => BigInt(input < 0 ? Math.ceil(input - 0.5) : Math.floor(input + 0.5)); +const roundMillisToNanos = millis => roundTiesAwayFromZero(millis * 1_000_000); +const parseNanos = (input, scale) => { + const decimalIndex = input.indexOf("."); + if (decimalIndex === -1) return BigInt(input) * scale; + const isNegative = input[0] === "-"; + const fractional = input.slice(decimalIndex + 1); + const fractionalScale = bigint10 ** BigInt(fractional.length); + const scaled = (BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) * scale; + const rounded = scaled / fractionalScale + (scaled % fractionalScale * bigint2 >= fractionalScale ? bigint1 : bigint0); + return isNegative ? -rounded : rounded; +}; +const nanosToHrTime = nanos => { + const sign = nanos < bigint0 ? -bigint1 : bigint1; + const absolute = nanos < bigint0 ? -nanos : nanos; + return [Number(sign * (absolute / bigint1e9)), Number(sign * (absolute % bigint1e9))]; +}; +const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; +/** + * Decodes a `Duration.Input` into a `Duration`. + * + * **When to use** + * + * Use when the input has already been validated or comes from a trusted source + * and throwing is acceptable for invalid duration syntax. + * + * **Gotchas** + * + * If the input is not a valid `Duration.Input`, it throws an error. + * + * **Example** (Decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.fromInputUnsafe(1000) // => Duration.millis(1000) + * Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5) + * Duration.fromInputUnsafe("Infinity") // => Duration.infinity + * Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInputUnsafe = input => { + switch (typeof input) { + case "number": + return millis(input); + case "bigint": + return nanos(input); + case "string": + { + if (input === "Infinity") { + return infinity; + } + if (input === "-Infinity") { + return negativeInfinity; + } + const match = DURATION_REGEXP.exec(input); + if (!match) break; + const [_, valueStr, unit] = match; + if (unit === "nano" || unit === "nanos") { + return nanos(parseNanos(valueStr, bigint1)); + } + if (unit === "micro" || unit === "micros") { + return nanos(parseNanos(valueStr, bigint1e3)); + } + const value = Number(valueStr); + switch (unit) { + case "milli": + case "millis": + return millis(value); + case "second": + case "seconds": + return seconds(value); + case "minute": + case "minutes": + return minutes(value); + case "hour": + case "hours": + return hours(value); + case "day": + case "days": + return days(value); + case "week": + case "weeks": + return weeks(value); + } + break; + } + case "object": + { + if (input === null) break; + if (TypeId in input) return input; + if (Array.isArray(input)) { + if (input.length !== 2 || !input.every(_Predicate_js__rspack_import_0/* .isNumber */.Et)) { + return invalid(input); + } + if (Number.isNaN(input[0]) || Number.isNaN(input[1])) { + return zero; + } + if (input[0] === -Infinity || input[1] === -Infinity) { + return negativeInfinity; + } + if (input[0] === Infinity || input[1] === Infinity) { + return infinity; + } + return make(roundTiesAwayFromZero(input[0] * 1_000_000_000 + input[1])); + } + const obj = input; + let millis = 0; + // we can use truthy checks here, because 0 can be ignored + if (obj.weeks) millis += obj.weeks * 604_800_000; + if (obj.days) millis += obj.days * 86_400_000; + if (obj.hours) millis += obj.hours * 3_600_000; + if (obj.minutes) millis += obj.minutes * 60_000; + if (obj.seconds) millis += obj.seconds * 1_000; + if (obj.milliseconds) millis += obj.milliseconds; + if (!obj.microseconds && !obj.nanoseconds) return make(millis); + return make(roundTiesAwayFromZero(millis * 1_000_000 + (obj.microseconds ?? 0) * 1_000 + (obj.nanoseconds ?? 0))); + } + } + return invalid(input); +}; +const invalid = input => { + throw new Error(`Invalid Input: ${input}`); +}; +/** + * Decodes a `Input` value into a `Duration` safely, returning + * `Option.none()` if decoding fails. + * + * **Example** (Safely decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.fromInput(1000) // => Option.some(Duration.seconds(1)) + * Duration.fromInput("invalid" as any) // => Option.none() + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInput = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(fromInputUnsafe))); +const zeroDurationValue = { + _tag: "Millis", + millis: 0 +}; +const infinityDurationValue = { + _tag: "Infinity" +}; +const negativeInfinityDurationValue = { + _tag: "NegativeInfinity" +}; +const DurationProto = { + [TypeId]: TypeId, + [_Hash_js__rspack_import_1/* .symbol */.HR]() { + // Hash equal finite durations using the same canonical nanoseconds + // representation used by `equals`. + switch (this.value._tag) { + case "Millis": + { + const nanos = this.value.millis * 1_000_000; + return Number.isFinite(nanos) ? _Hash_js__rspack_import_1/* .hash */.tW(roundTiesAwayFromZero(nanos)) : _Hash_js__rspack_import_1/* .number */.ai(this.value.millis); + } + case "Nanos": + return _Hash_js__rspack_import_1/* .hash */.tW(this.value.nanos); + default: + return _Hash_js__rspack_import_1/* .structure */.QK(this.value); + } + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](that) { + return isDuration(that) && equals(this, that); + }, + toString() { + switch (this.value._tag) { + case "Infinity": + return "Infinity"; + case "NegativeInfinity": + return "-Infinity"; + case "Nanos": + return `${this.value.nanos} nanos`; + case "Millis": + return `${this.value.millis} millis`; + } + }, + toJSON() { + switch (this.value._tag) { + case "Millis": + return { + _id: "Duration", + _tag: "Millis", + millis: this.value.millis + }; + case "Nanos": + return { + _id: "Duration", + _tag: "Nanos", + nanos: String(this.value.nanos) + }; + case "Infinity": + return { + _id: "Duration", + _tag: "Infinity" + }; + case "NegativeInfinity": + return { + _id: "Duration", + _tag: "NegativeInfinity" + }; + } + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + }, + pipe() { + return (0,_Pipeable_js__rspack_import_4/* .pipeArguments */.tT)(this, arguments); + } +}; +const make = input => { + const duration = Object.create(DurationProto); + if (typeof input === "number") { + if (isNaN(input) || input === 0 || Object.is(input, -0)) { + duration.value = zeroDurationValue; + } else if (!Number.isFinite(input)) { + duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue; + } else if (!Number.isInteger(input)) { + duration.value = { + _tag: "Nanos", + nanos: roundMillisToNanos(input) + }; + } else { + duration.value = { + _tag: "Millis", + millis: input + }; + } + } else if (input === bigint0) { + duration.value = zeroDurationValue; + } else { + duration.value = { + _tag: "Nanos", + nanos: input + }; + } + return duration; +}; +/** + * Checks whether a value is a Duration. + * + * **Example** (Checking for durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isDuration(Duration.seconds(1)) // => true + * Duration.isDuration(1000) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isDuration = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether a Duration is finite (not infinite). + * + * **Example** (Checking finite durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isFinite(Duration.seconds(5)) // => true + * Duration.isFinite(Duration.infinity) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFinite = self => self.value._tag !== "Infinity" && self.value._tag !== "NegativeInfinity"; +/** + * Checks whether a Duration is zero. + * + * **Example** (Checking for zero durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isZero(Duration.zero) // => true + * Duration.isZero(Duration.seconds(1)) // => false + * ``` + * + * @category predicates + * @since 3.5.0 + */ +const isZero = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis === 0; + case "Nanos": + return self.value.nanos === bigint0; + case "Infinity": + case "NegativeInfinity": + return false; + } +}; +/** + * Returns `true` if the duration is negative (strictly less than zero). + * + * **Example** (Checking for negative durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isNegative(Duration.seconds(-5)) // => true + * Duration.isNegative(Duration.zero) // => false + * Duration.isNegative(Duration.negativeInfinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isNegative = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis < 0; + case "Nanos": + return self.value.nanos < bigint0; + case "NegativeInfinity": + return true; + case "Infinity": + return false; + } +}; +/** + * Returns `true` if the duration is positive (strictly greater than zero). + * + * **Example** (Checking for positive durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isPositive(Duration.seconds(5)) // => true + * Duration.isPositive(Duration.zero) // => false + * Duration.isPositive(Duration.infinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isPositive = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis > 0; + case "Nanos": + return self.value.nanos > bigint0; + case "Infinity": + return true; + case "NegativeInfinity": + return false; + } +}; +/** + * Returns the absolute value of the duration. + * + * **Example** (Taking absolute duration values) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.abs(Duration.seconds(-5)) // => Duration.seconds(5) + * Duration.abs(Duration.negativeInfinity) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const abs = self => { + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis < 0 ? make(-self.value.millis) : self; + case "Nanos": + return self.value.nanos < bigint0 ? make(-self.value.nanos) : self; + } +}; +/** + * Returns the negated duration. + * + * **Example** (Negating durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.negate(Duration.seconds(5)) // => Duration.seconds(-5) + * Duration.negate(Duration.infinity) // => Duration.negativeInfinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const negate = self => { + switch (self.value._tag) { + case "Infinity": + return negativeInfinity; + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis === 0 ? self : make(-self.value.millis); + case "Nanos": + return self.value.nanos === bigint0 ? self : make(-self.value.nanos); + } +}; +/** + * A Duration representing zero time. + * + * **Example** (Referencing the zero duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.zero) // => 0 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const zero = /*#__PURE__*/make(0); +/** + * A Duration representing infinite time. + * + * **Example** (Referencing infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.infinity) // => Infinity + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const infinity = /*#__PURE__*/make(Infinity); +/** + * A Duration representing negative infinite time. + * + * **Example** (Referencing negative infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.negativeInfinity) // => -Infinity + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const negativeInfinity = /*#__PURE__*/make(-Infinity); +/** + * Creates a Duration from nanoseconds. + * + * **Example** (Creating durations from nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const nanos = nanos => make(nanos); +/** + * Creates a Duration from microseconds. + * + * **Example** (Creating durations from microseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.micros(500_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const micros = micros => make(micros * bigint1e3); +/** + * Creates a Duration from milliseconds. + * + * **Example** (Creating durations from milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.millis(1000)) // => 1000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const millis = millis => make(millis); +/** + * Creates a Duration from seconds. + * + * **Example** (Creating durations from seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(30)) // => 30_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const seconds = seconds => make(seconds * 1000); +/** + * Creates a Duration from minutes. + * + * **Example** (Creating durations from minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.minutes(5)) // => 300_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const minutes = minutes => make(minutes * 60_000); +/** + * Creates a Duration from hours. + * + * **Example** (Creating durations from hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.hours(2)) // => 7_200_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const hours = hours => make(hours * 3_600_000); +/** + * Creates a Duration from days. + * + * **Example** (Creating durations from days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.days(1)) // => 86_400_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const days = days => make(days * 86_400_000); +/** + * Creates a Duration from weeks. + * + * **Example** (Creating durations from weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.weeks(1)) // => 604_800_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const weeks = weeks => make(weeks * 604_800_000); +/** + * Converts a Duration to milliseconds. + * + * **Example** (Converting durations to milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(5)) // => 5000 + * Duration.toMillis(Duration.minutes(2)) // => 120_000 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toMillis = self => match(fromInputUnsafe(self), { + onMillis: _Function_js__rspack_import_5/* .identity */.D_, + onNanos: nanos => Number(nanos) / 1_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to seconds. + * + * **Example** (Converting durations to seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toSeconds(Duration.millis(5000)) // => 5 + * Duration.toSeconds(Duration.minutes(2)) // => 120 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toSeconds = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 1_000, + onNanos: nanos => Number(nanos) / 1_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to minutes. + * + * **Example** (Converting durations to minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMinutes(Duration.seconds(120)) // => 2 + * Duration.toMinutes(Duration.hours(1)) // => 60 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toMinutes = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 60_000, + onNanos: nanos => Number(nanos) / 60_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to hours. + * + * **Example** (Converting durations to hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHours(Duration.minutes(120)) // => 2 + * Duration.toHours(Duration.days(1)) // => 24 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toHours = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 3_600_000, + onNanos: nanos => Number(nanos) / 3_600_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to days. + * + * **Example** (Converting durations to days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toDays(Duration.hours(48)) // => 2 + * Duration.toDays(Duration.weeks(1)) // => 7 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toDays = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 86_400_000, + onNanos: nanos => Number(nanos) / 86_400_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to weeks. + * + * **Example** (Converting durations to weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toWeeks(Duration.days(14)) // => 2 + * Duration.toWeeks(Duration.days(7)) // => 1 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toWeeks = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 604_800_000, + onNanos: nanos => Number(nanos) / 604_800_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Gets the duration in nanoseconds as a bigint. + * + * **When to use** + * + * Use when the duration is known to be finite and you need the nanosecond value + * as a `bigint`. + * + * **Details** + * + * Millisecond-backed fractional durations are rounded to the nearest + * nanosecond, with ties away from zero. + * + * **Gotchas** + * + * If the duration is infinite, it throws an error. + * + * **Example** (Reading nanoseconds unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n + * + * // Duration.toNanosUnsafe(Duration.infinity) + * // throws Error: "Cannot convert infinite duration to nanos" + * ``` + * + * @category getters + * @since 4.0.0 + */ +const toNanosUnsafe = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + throw new Error("Cannot convert infinite duration to nanos"); + case "Nanos": + return self.value.nanos; + case "Millis": + return roundMillisToNanos(self.value.millis); + } +}; +/** + * Gets the duration in nanoseconds safely as an `Option`. + * + * **Details** + * + * If the duration is infinite, returns `Option.none()`. + * + * **Example** (Safely reading nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.toNanos(Duration.seconds(1)) // => Option.some(1_000_000_000n) + * Duration.toNanos(Duration.infinity) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toNanos = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(toNanosUnsafe))); +/** + * Converts a Duration to high-resolution time format [seconds, nanoseconds]. + * + * **Example** (Converting durations to high-resolution time) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHrTime(Duration.millis(1500)) // => [1, 500_000_000] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toHrTime = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + return [Infinity, 0]; + case "NegativeInfinity": + return [-Infinity, 0]; + case "Nanos": + return nanosToHrTime(self.value.nanos); + case "Millis": + return nanosToHrTime(roundMillisToNanos(self.value.millis)); + } +}; +/** + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.match(Duration.seconds(5), { + * onMillis: (millis) => `${millis} milliseconds`, + * onNanos: (nanos) => `${nanos} nanoseconds`, + * onInfinity: () => "infinite" + * }) // => "5000 milliseconds" + * ``` + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, options) => { + switch (self.value._tag) { + case "Millis": + return options.onMillis(self.value.millis); + case "Nanos": + return options.onNanos(self.value.nanos); + case "Infinity": + return options.onInfinity(); + case "NegativeInfinity": + return (options.onNegativeInfinity ?? options.onInfinity)(); + } +}); +/** + * Pattern matches on two `Duration`s, providing handlers that receive both values. + * + * **Example** (Pattern matching on duration pairs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.matchPair(Duration.seconds(3), Duration.seconds(2), { + * onMillis: (a, b) => a + b, + * onNanos: (a, b) => Number(a + b), + * onInfinity: () => Infinity + * }) // => 5000 + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchPair = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, that, options) => { + if (self.value._tag === "Infinity" || self.value._tag === "NegativeInfinity" || that.value._tag === "Infinity" || that.value._tag === "NegativeInfinity") return options.onInfinity(self, that); + if (self.value._tag === "Millis") { + return that.value._tag === "Millis" ? options.onMillis(self.value.millis, that.value.millis) : options.onNanos(toNanosUnsafe(self), that.value.nanos); + } else { + return options.onNanos(self.value.nanos, toNanosUnsafe(that)); + } +}); +/** + * Provides an `Order` instance for comparing `Duration` values. + * + * **Details** + * + * `NegativeInfinity` < any finite value < `Infinity`. + * + * **Example** (Sorting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * const durations = [ + * Duration.seconds(3), + * Duration.seconds(1), + * Duration.seconds(2) + * ] + * durations.sort((a, b) => Duration.Order(a, b)).map(Duration.toSeconds) // => [1, 2, 3] + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Order = /*#__PURE__*/(/* unused pure expression or super */ null && (order.make((self, that) => matchPair(self, that, { + onMillis: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onNanos: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onInfinity: (self, that) => { + if (self.value._tag === that.value._tag) return 0; + if (self.value._tag === "Infinity") return 1; + if (self.value._tag === "NegativeInfinity") return -1; + // self is finite + if (that.value._tag === "Infinity") return -1; + // that is NegativeInfinity + return 1; + } +})))); +/** + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.between(Duration.seconds(3), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => true + * ``` + * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * + * @category predicates + * @since 2.0.0 + */ +const between = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isBetween(Order))); +/** + * Provides an `Equivalence` instance for comparing `Duration` values. + * + * **Example** (Comparing durations for equivalence) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Equivalence = (self, that) => matchPair(self, that, { + onMillis: (self, that) => self === that, + onNanos: (self, that) => self === that, + onInfinity: (self, that) => self.value._tag === that.value._tag +}); +/** + * Returns the smaller of two Durations. + * + * **Example** (Selecting the shorter duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.min(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(3) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (order.min(Order))); +/** + * Returns the larger of two Durations. + * + * **Example** (Selecting the longer duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.max(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (order.max(Order))); +/** + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.clamp(Duration.seconds(10), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const clamp = /*#__PURE__*/(/* unused pure expression or super */ null && (order.clamp(Order))); +/** + * Divides a `Duration` by a finite, non-zero number safely. + * + * **Details** + * + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.divide(Duration.seconds(10), 2) // => Option.some(Duration.seconds(5)) + * Duration.divide(Duration.seconds(10), 0) // => Option.none() + * ``` + * + * @category math + * @since 2.4.19 + */ +const divide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return Option.none(); + if (by === 0 || Object.is(by, -0)) return Option.none(); + return match(self, { + onMillis: millis => Option.some(make(millis / by)), + onNanos: nanos => { + try { + return Option.some(make(nanos / BigInt(by))); + } catch { + return Option.none(); + } + }, + onInfinity: () => Option.some(by > 0 ? infinity : negativeInfinity), + onNegativeInfinity: () => Option.some(by > 0 ? negativeInfinity : infinity) + }); +}))); +/** + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.divideUnsafe(Duration.seconds(10), 2) // => Duration.seconds(5) + * Duration.divideUnsafe(Duration.seconds(10), 0) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const divideUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return zero; + return match(self, { + onMillis: millis => make(millis / by), + onNanos: nanos => { + if (Object.is(by, 0) || Object.is(by, -0)) { + if (nanos === bigint0) return zero; + // match IEEE 754: same sign → +infinity, different sign → -infinity + const positiveNanos = nanos > bigint0; + const positiveZero = Object.is(by, 0); + return positiveNanos === positiveZero ? infinity : negativeInfinity; + } + try { + return make(nanos / BigInt(by)); + } catch { + return zero; + } + }, + onInfinity: () => by > 0 ? infinity : by < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => by > 0 ? negativeInfinity : by < 0 ? infinity : zero + }); +}))); +/** + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.times(Duration.seconds(5), 2) // => Duration.seconds(10) + * ``` + * + * @category math + * @since 2.0.0 + */ +const times = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, times) => match(self, { + onMillis: millis => make(millis * times), + onNanos: nanos => make(nanos * BigInt(times)), + onInfinity: () => times > 0 ? infinity : times < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => times > 0 ? negativeInfinity : times < 0 ? infinity : zero +})))); +/** + * Subtracts one Duration from another. The result can be negative. + * + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.subtract(Duration.seconds(10), Duration.seconds(3)) // => Duration.seconds(7) + * ``` + * + * @category math + * @since 2.0.0 + */ +const subtract = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self - that), + onNanos: (self, that) => make(self - that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity") return t === "Infinity" ? zero : infinity; + if (s === "NegativeInfinity") return t === "NegativeInfinity" ? zero : negativeInfinity; + return t === "Infinity" ? negativeInfinity : infinity; + } +})))); +/** + * Adds two Durations together. + * + * **Details** + * + * Infinity addition follows these rules: + * + * - infinity + infinity = infinity + * - infinity + negativeInfinity = zero + * - infinity + finite = infinity + * - negativeInfinity + negativeInfinity = negativeInfinity + * - negativeInfinity + finite = negativeInfinity + * + * **Example** (Adding durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.sum(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(8) + * ``` + * + * @category math + * @since 2.0.0 + */ +const sum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self + that), + onNanos: (self, that) => make(self + that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity" && t === "NegativeInfinity") return zero; + if (s === "NegativeInfinity" && t === "Infinity") return zero; + if (s === "Infinity" || t === "Infinity") return infinity; + if (s === "NegativeInfinity" || t === "NegativeInfinity") return negativeInfinity; + // unreachable, but satisfy TS + return zero; + } +})))); +/** + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThan(Duration.seconds(3), Duration.seconds(5)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThan(Order))); +/** + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThanOrEqualTo(Order))); +/** + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThan(Duration.seconds(5), Duration.seconds(3)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThan(Order))); +/** + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThanOrEqualTo(Order))); +/** + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const equals = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, that) => Equivalence(self, that)); +/** + * Decomposes a `Duration` into normalized signed components. + * + * **Details** + * + * Finite durations are returned as `{ days, hours, minutes, seconds, millis, + * nanos }`. Infinite durations return every component as `Infinity` or + * `-Infinity`. + * + * **Example** (Decomposing durations into parts) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * // Create a complex duration by adding multiple parts + * const duration = Duration.sum( + * Duration.sum( + * Duration.sum(Duration.days(1), Duration.hours(2)), + * Duration.sum(Duration.minutes(30), Duration.seconds(45)) + * ), + * Duration.millis(123) + * ) + * Duration.parts(duration) // => ({ days: 1, hours: 2, minutes: 30, seconds: 45, millis: 123, nanos: 0 }) + * + * const complex = Duration.sum(Duration.hours(25), Duration.minutes(90)) + * Duration.parts(complex) // => ({ days: 1, hours: 2, minutes: 30, seconds: 0, millis: 0, nanos: 0 }) + * ``` + * + * @category converting + * @since 3.8.0 + */ +const parts = self => { + if (self.value._tag === "Infinity") { + return { + days: Infinity, + hours: Infinity, + minutes: Infinity, + seconds: Infinity, + millis: Infinity, + nanos: Infinity + }; + } + if (self.value._tag === "NegativeInfinity") { + return { + days: -Infinity, + hours: -Infinity, + minutes: -Infinity, + seconds: -Infinity, + millis: -Infinity, + nanos: -Infinity + }; + } + const n = toNanosUnsafe(self); + const neg = n < bigint0; + const a = neg ? -n : n; + const ms = a / bigint1e6; + const sec = ms / bigint1e3; + const min = sec / bigint60; + const hr = min / bigint60; + const d = hr / bigint24; + const sign = neg ? -1 : 1; + return { + days: sign * Number(d), + hours: sign * Number(hr % bigint24), + minutes: sign * Number(min % bigint60), + seconds: sign * Number(sec % bigint60), + millis: sign * Number(ms % bigint1e3), + nanos: sign * Number(a % bigint1e6) + }; +}; +/** + * Converts a `Duration` to a human readable string. + * + * **Example** (Formatting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.format(Duration.millis(1000)) // => "1s" + * Duration.format(Duration.millis(1001)) // => "1s 1ms" + * ``` + * + * @category converting + * @since 2.0.0 + */ +const format = self => { + if (self.value._tag === "Infinity") { + return "Infinity"; + } + if (self.value._tag === "NegativeInfinity") { + return "-Infinity"; + } + if (isZero(self)) { + return "0"; + } + if (isNegative(self)) { + return "-" + format(abs(self)); + } + const fragments = parts(self); + const pieces = []; + if (fragments.days !== 0) { + pieces.push(`${fragments.days}d`); + } + if (fragments.hours !== 0) { + pieces.push(`${fragments.hours}h`); + } + if (fragments.minutes !== 0) { + pieces.push(`${fragments.minutes}m`); + } + if (fragments.seconds !== 0) { + pieces.push(`${fragments.seconds}s`); + } + if (fragments.millis !== 0) { + pieces.push(`${fragments.millis}ms`); + } + if (fragments.nanos !== 0) { + pieces.push(`${fragments.nanos}ns`); + } + return pieces.join(" "); +}; +/** + * Reducer for summing `Duration`s. + * + * **When to use** + * + * Use to sum many `Duration` values through APIs that consume a `Reducer`. + * + * **Details** + * + * `ReducerSum` uses `sum` and starts from `zero`, so `combineAll([])` returns + * `zero`. + * + * @see {@link sum} for adding two duration values directly + * @see {@link CombinerMax} for keeping the longest duration instead of summing + * @see {@link CombinerMin} for keeping the shortest duration instead of summing + * + * @category math + * @since 4.0.0 + */ +const ReducerSum = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make(sum, zero))); +/** + * Combiner that returns the maximum `Duration`. + * + * **When to use** + * + * Use to keep the longest `Duration` when an API consumes a `Combiner`. + * + * @see {@link CombinerMin} for keeping the shortest `Duration` + * @see {@link max} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMax = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.max(Order))); +/** + * Combiner that returns the minimum `Duration`. + * + * **When to use** + * + * Use to keep the shortest `Duration` through APIs that consume a `Combiner`. + * + * @see {@link CombinerMax} for keeping the longest `Duration` + * @see {@link min} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMin = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.min(Order))); +//# sourceMappingURL=Duration.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Tn: infinity, + bN: fromInputUnsafe, + cF: nanos, + kE: toMillis, + ne: millis, + v_: zero +}); + + +}, +"./node_modules/effect/dist/Effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _internal_executionPlan_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/executionPlan.js"); +/* import */ var _internal_layer_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/layer.js"); +/* import */ var _internal_request_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/request.js"); +/* import */ var _internal_schedule_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/schedule.js"); + + + + + + + + + + + + + + +/** + * Runtime identifier used to recognize `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .EffectTypeId */.$n; +/** + * Checks whether a value is an `Effect`. + * + * **Example** (Checking whether a value is an Effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * Effect.isEffect(Effect.succeed(1)) // => true + * Effect.isEffect("hello") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEffect = _internal_core_js__rspack_import_0/* .isEffect */.yw; +/** + * 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. + * @category combining + * @since 2.0.0 + */ +const all = _internal_effect_js__rspack_import_1/* .all */.Q7R; +/** + * Applies an effectful function to each element and partitions failures and + * successes. + * + * **Details** + * + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. + * + * This function runs every effect and never fails. Use `concurrency` to control + * parallelism. + * + * **Example** (Separating successes and failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.partition([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromise(program) // => [['0 is even', '2 is even'], [1, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = _internal_effect_js__rspack_import_1/* .partition */.jBG; +/** + * Reduces elements from left to right with an effectful accumulator function. + * + * **When to use** + * + * Use when each accumulation step is effectful and must run sequentially in + * iteration order. + * + * **Details** + * + * The accumulator function receives the current accumulator, the current + * element, and its zero-based index. The `zero` function is evaluated each + * time the effect runs. An empty iterable succeeds with its result. If a step + * fails, remaining elements are not processed. + * + * **Example** (Summing values sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.reduce( + * [1, 2, 3], + * () => 0, + * (total, value, index) => + * Effect.sync(() => { output.push(`Adding ${value} at index ${index}`) }).pipe( + * Effect.as(total + value) + * ) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Adding 1 at index 0", "Adding 2 at index 1", "Adding 3 at index 2", 6] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = _internal_effect_js__rspack_import_1/* .reduce */.TSs; +/** + * Applies an effectful function to each element and accumulates all failures. + * + * **Details** + * + * This function always evaluates every element. If at least one effect fails, + * all failures are returned as a non-empty array and successes are discarded. + * If all effects succeed, it returns all collected successes. + * + * Use `discard: true` to ignore successful values while still validating all + * elements. + * + * **Example** (Validating every element) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const program = Effect.validate([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromiseExit(program) // => Exit.fail(["0 is even", "2 is even"]) + * ``` + * + * @category validation + * @since 2.0.0 + */ +const validate = _internal_effect_js__rspack_import_1/* .validate */.tfT; +/** + * Returns the first element that satisfies an effectful predicate. + * + * **Details** + * + * The predicate receives the element and its index. Evaluation short-circuits + * as soon as an element matches. + * + * **Example** (Finding the first successful match) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.findFirst([1, 2, 3, 4], (n) => Effect.succeed(n > 2)) + * + * await Effect.runPromise(program) // => Option.some(3) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _internal_effect_js__rspack_import_1/* .findFirst */.i8i; +/** + * Returns the first value that passes an effectful `FilterEffect`. + * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * + * The filter receives the element and index. Evaluation short-circuits on the + * first `Result.succeed` and returns the transformed value in `Option.some`. + * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category searching + * @since 4.0.0 + */ +const findFirstFilter = _internal_effect_js__rspack_import_1/* .findFirstFilter */.kAe; +/** + * Executes an effectful operation for each element in an `Iterable`. + * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * + * **Details** + * + * The `forEach` function applies a provided operation to each element in the + * iterable, producing a new effect that returns an array of results. + * + * If any effect fails, the iteration stops immediately (short-circuiting), and + * the error is propagated. + * + * Concurrency: + * + * The `concurrency` option controls how many operations are performed + * concurrently. By default, the operations are performed sequentially. + * + * Discarding Results: + * + * If the `discard` option is set to `true`, the intermediate results are not + * collected, and the final result of the operation is `void`. + * + * **Example** (Mapping over an iterable with effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)) + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", [2, 4, 6, 8, 10]] + * ``` + * + * **Example** (Running effects without collecting results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Apply effects but discard the results + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)), + * { discard: true } + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", undefined] + * ``` + * + * @see {@link all} for combining multiple effects into one. + * @category sequencing + * @since 2.0.0 + */ +const forEach = _internal_effect_js__rspack_import_1/* .forEach */.jJl; +/** + * Returns the first element of the iterable produced by an effect, or fails + * with `NoSuchElementError` if the iterable is empty. + * + * **When to use** + * + * Use when an effect produces a collection that must contain at least one + * element and absence should be represented in the typed error channel. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const first = await Effect.runPromise(Effect.head(Effect.succeed([1, 2, 3]))) + * first // => 1 + * + * const empty = Effect.head(Effect.succeed([] as Array)).pipe(Effect.catchNoSuchElement) + * await Effect.runPromise(empty) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = _internal_effect_js__rspack_import_1/* .head */.d5f; +/** + * Executes a body effect repeatedly while a condition holds true. + * + * **Example** (Repeating an effectful loop) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let counter = 0 + * + * const program = Effect.whileLoop({ + * while: () => counter < 5, + * body: () => Effect.sync(() => ++counter), + * step: (n) => void output.push(`Current count: ${n}`) + * }) + * + * await Effect.runPromise(program) + * output // => ["Current count: 1", "Current count: 2", "Current count: 3", "Current count: 4", "Current count: 5"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const whileLoop = _internal_effect_js__rspack_import_1/* .whileLoop */.iMI; +// ----------------------------------------------------------------------------- +// Creating Effects +// ----------------------------------------------------------------------------- +/** + * Creates an `Effect` that represents an asynchronous computation guaranteed to + * succeed. + * + * **When to use** + * + * Use to convert a `Promise` into an `Effect` when the async operation is + * guaranteed to succeed and will not reject. + * + * **Details** + * + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. + * + * **Gotchas** + * + * The `Promise` must not reject. If it rejects, the rejection is treated as a + * defect, not as a typed failure. Use `tryPromise` when rejection is expected. + * + * Interruption aborts the provided `AbortSignal`, but the underlying + * asynchronous operation only stops if it observes that signal. + * + * **Example** (Wrapping a non-rejecting Promise) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const succeedAsync = (message: string) => + * Effect.promise(() => Promise.resolve(message)) + * + * // ┌─── Effect + * // ▼ + * const program = succeedAsync("Async operation completed successfully!") + * await Effect.runPromise(program) // => "Async operation completed successfully!" + * ``` + * + * @see {@link tryPromise} for a version that can handle failures. + * @category constructors + * @since 2.0.0 + */ +const promise = _internal_effect_js__rspack_import_1/* .promise */.ivC; +/** + * Creates an `Effect` from an asynchronous computation that may throw or + * reject, mapping failures into the error channel. + * + * **When to use** + * + * Use when you need to perform asynchronous operations that might fail, such + * as fetching data from an API, and want thrown exceptions or rejected promises + * captured as Effect errors. + * + * **Details** + * + * The promise thunk is evaluated when the effect runs. If it returns a promise + * that resolves, the resolved value becomes the success value. If the thunk + * throws before returning a promise, or if the returned promise rejects, the + * thrown or rejected value is mapped into the error channel. + * + * Passing the thunk directly maps failures to {@link Cause.UnknownError}. + * Passing `{ try, catch }` uses `catch` to map failures to an error of type + * `E`. + * + * The thunk receives an `AbortSignal` that is aborted if the effect is + * interrupted. The underlying asynchronous operation only stops if it observes + * that signal. + * + * **Gotchas** + * + * If `catch` throws while mapping the error, that thrown value is treated as a + * defect. Return the error value you want in the error channel instead of + * throwing it. + * + * **Example** (Wrapping a fetch request that may fail) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const getTodo = (id: number) => + * Effect.tryPromise(() => Promise.resolve({ id, completed: false })) + * + * // ┌─── Effect<{ id: number; completed: boolean }, UnknownError, never> + * // ▼ + * const program = getTodo(1) + * await Effect.runPromise(program) // => { id: 1, completed: false } + * ``` + * + * **Example** (Mapping Promise rejections to a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TodoFetchError extends Data.TaggedError("TodoFetchError")<{ readonly cause: unknown }> {} + * + * const getTodo = (id: number) => + * Effect.tryPromise({ + * try: () => Promise.reject(`Todo ${id} is unavailable`), + * // remap the error + * catch: (cause) => new TodoFetchError({ cause }) + * }) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.flip(getTodo(1)) + * const error = await Effect.runPromise(program) + * error._tag // => "TodoFetchError" + * ``` + * + * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. + * @category constructors + * @since 2.0.0 + */ +const tryPromise = _internal_effect_js__rspack_import_1/* .tryPromise */.$mh; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_effect_js__rspack_import_1/* .succeed */.PyW; +/** + * Returns an effect which succeeds with `None`. + * + * **Example** (Succeeding with Option.none) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedNone + * + * Effect.runSync(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedNone = _internal_effect_js__rspack_import_1/* .succeedNone */.lwU; +/** + * Returns an effect which succeeds with the value wrapped in a `Some`. + * + * **Example** (Succeeding with Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedSome(42) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedSome = _internal_effect_js__rspack_import_1/* .succeedSome */.nGE; +/** + * Creates an `Effect` lazily, delaying construction until it is needed. + * + * **When to use** + * + * Use when you need to defer the evaluation of an effect until it is required. + * + * **Details** + * + * `suspend` takes a thunk that represents an effect and delays creating it + * until the suspended effect is evaluated. This is useful for optimizing + * expensive computations, managing circular dependencies such as recursive + * functions, and helping TypeScript unify return types when branches construct + * different effects. Any side effects or scoped captures inside the thunk are + * re-executed on each invocation. + * + * **Example** (Lazily evaluating side effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * let i = 0 + * + * const bad = Effect.succeed(i++) + * + * const good = Effect.suspend(() => Effect.succeed(i++)) + * + * Effect.runSync(bad) // => 0 + * Effect.runSync(bad) // => 0 + * + * Effect.runSync(good) // => 1 + * Effect.runSync(good) // => 2 + * ``` + * + * **Example** (Suspending recursive Fibonacci evaluation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const blowsUp = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b) + * + * // console.log(Effect.runSync(blowsUp(32))) + * // crash: JavaScript heap out of memory + * + * const allGood = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith( + * Effect.suspend(() => allGood(n - 1)), + * Effect.suspend(() => allGood(n - 2)), + * (a, b) => a + b + * ) + * + * Effect.runSync(allGood(16)) // => 1597 + * ``` + * + * **Example** (Helping TypeScript infer recursive effect types) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Without suspend, TypeScript may struggle with type inference. + * // Inferred type: + * // (a: number, b: number) => + * // Effect | Effect + * const withoutSuspend = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * + * // Using suspend to unify return types. + * // Inferred type: + * // (a: number, b: number) => Effect + * const withSuspend = (a: number, b: number) => + * Effect.suspend(() => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * ) + * + * Effect.runSync(withSuspend(6, 2)) // => 3 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = _internal_effect_js__rspack_import_1/* .suspend */.DYE; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const sync = _internal_effect_js__rspack_import_1/* .sync */.OH5; +const void_ = _internal_effect_js__rspack_import_1/* ["void"] */.rIH; + +const undefined_ = _internal_effect_js__rspack_import_1/* .undefined */.Vxk; + +/** + * Creates an `Effect` from a callback-based asynchronous API. + * + * **When to use** + * + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. + * + * **Details** + * + * The registration function receives a `resume` callback and, when requested, + * an `AbortSignal`. Call `resume` at most once with the effect that should + * complete the fiber; later calls are ignored. Return an optional cleanup + * effect from the registration function to run if the fiber is interrupted. + * + * **Example** (Integrating callback APIs) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fromCallback = (message: string) => + * Effect.callback((resume) => { + * queueMicrotask(() => { + * void output.push(message) + * resume(Effect.void) + * }) + * }) + * + * await Effect.runPromise(fromCallback("callback completed")) + * output // => ["callback completed"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = _internal_effect_js__rspack_import_1/* .callback */.E2r; +/** + * Returns an effect that will never produce anything. The moral equivalent of + * `while(true) {}`, only without the wasted CPU cycles. + * + * **Example** (Creating a never-ending effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.timeoutOption(Effect.never, 0) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = _internal_effect_js__rspack_import_1/* .never */.ZmZ; +/** + * Effect that succeeds with an empty record `{}`, used as the starting point + * for do notation chains. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * const program = pipe( + * Effect.Do, + * Effect.bind("x", () => Effect.succeed(2)), + * Effect.bind("y", ({ x }) => Effect.succeed(x + 1)), + * Effect.let("sum", ({ x, y }) => x + y) + * ) + * + * Effect.runSync(program) // => { x: 2, y: 3, sum: 5 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Do = _internal_effect_js__rspack_import_1.Do; +/** + * Gives a name to the success value of an `Effect`, creating a single-key + * record used in do notation pipelines. + * + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = _internal_effect_js__rspack_import_1/* .bindTo */.JrD; +const let_ = _internal_effect_js__rspack_import_1/* ["let"] */.uVU; + +/** + * Adds an `Effect` value to the do notation record under a given name. + * + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category sequencing + * @since 2.0.0 + */ +const bind = _internal_effect_js__rspack_import_1/* .bind */.oIE; +/** + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const gen = _internal_effect_js__rspack_import_1/* .gen */.JkU; +/** + * Creates an `Effect` that represents a recoverable error. + * + * **When to use** + * + * Use to explicitly signal a recoverable error in an `Effect`. + * + * **Details** + * + * The error keeps propagating unless it is handled. You can handle tagged + * errors with functions like {@link catchTag} or {@link catchTags}. + * + * **Example** (Creating a failed effect) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {} + * + * // ┌─── Effect + * // ▼ + * const failure = Effect.fail( + * new OperationFailedError() + * ) + * Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError" + * ``` + * + * @see {@link succeed} to create an effect that represents a successful value. + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_effect_js__rspack_import_1/* .fail */.fJG; +/** + * Creates an `Effect` that represents a recoverable error using a lazy evaluation. + * + * **When to use** + * + * Use to defer computing a recoverable error value until the effect is run. + * + * **Details** + * + * The error-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating failures) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ProgramError extends Data.TaggedError("ProgramError")<{ readonly operation: string }> {} + * + * const program = Effect.failSync(() => new ProgramError({ operation: "sync" })) + * + * Effect.runSync(Effect.flip(program)).operation // => "sync" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = _internal_effect_js__rspack_import_1/* .failSync */.gOk; +/** + * Creates an `Effect` that represents a failure with a specific `Cause`. + * + * **When to use** + * + * Use when you already have a full `Cause` and need to preserve defects, + * interruptions, annotations, or combined failures in the effect's failure + * channel. + * + * **Details** + * + * This function allows you to create effects that fail with complex error + * structures, including multiple errors, defects, interruptions, and more. + * + * **Example** (Failing with a full Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCause( + * Cause.fail("Network error") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Network error" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_effect_js__rspack_import_1/* .failCause */.ATB; +/** + * Creates an `Effect` that represents a failure with a `Cause` computed lazily. + * + * **When to use** + * + * Use to defer computing a full `Cause` until the effect is run. + * + * **Details** + * + * The cause-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCauseSync(() => + * Cause.fail("Error computed at runtime") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Error computed at runtime" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = _internal_effect_js__rspack_import_1/* .failCauseSync */.pVV; +/** + * Creates an effect that terminates a fiber with a specified error. + * + * **When to use** + * + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. + * + * **Details** + * + * The `die` function is used to signal a defect, which represents a critical + * and unexpected error in the code. When invoked, it produces an effect that + * does not handle the error and instead terminates the fiber. + * + * The error channel of the resulting effect is of type `never`, indicating that + * it cannot recover from this failure. + * + * **Example** (Failing on division by zero) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const defect = new Error("Cannot divide by zero") + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.die(defect) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = divide(1, 0) + * + * Effect.runSyncExit(program) // => Exit.die(defect) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_effect_js__rspack_import_1/* .die */.F_Q; +const try_ = _internal_effect_js__rspack_import_1/* ["try"] */.SvU; + +/** + * Yields control back to the Effect runtime, allowing other fibers to execute. + * + * **Example** (Yielding to other fibers) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("Before yield") + * yield* Effect.yieldNow + * void output.push("After yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["Before yield", "After yield"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const yieldNow = _internal_effect_js__rspack_import_1/* .yieldNow */.m9E; +/** + * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute. + * + * **Example** (Yielding with priority) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("High priority task") + * yield* Effect.yieldNowWith(10) // Higher priority + * void output.push("Continued after yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["High priority task", "Continued after yield"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const yieldNowWith = _internal_effect_js__rspack_import_1/* .yieldNowWith */.KN3; +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const withFiber = _internal_core_js__rspack_import_0/* .withFiber */.R6; +// ----------------------------------------------------------------------------- +// Conversions +// ----------------------------------------------------------------------------- +/** + * Converts a `Result` to an `Effect`. + * + * **Example** (Converting a Result into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * const output: Array = [] + * + * const success = Result.succeed(42) + * const failure = Result.fail("Something went wrong") + * + * const effect1 = Effect.fromResult(success) + * const effect2 = Effect.fromResult(failure) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))) + * output // => [42, "Something went wrong"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromResult = _internal_effect_js__rspack_import_1/* .fromResult */.yUA; +/** + * Converts an `Option` into an `Effect`. + * + * **When to use** + * + * Use when absence should become a typed `NoSuchElementError` in the effect error + * channel. + * + * **Details** + * + * `Option.some` becomes a successful effect with the contained value, while + * `Option.none` becomes a failed effect. By default the failure is a + * `NoSuchElementError`, but you can provide an `onNone` callback to customize + * the error value. + * + * **Example** (Converting an Option into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Option.some(42) + * const none = Option.none() + * + * const effect1 = Effect.fromOption(some) + * const effect2 = Effect.fromOption(none) + * const effect3 = Effect.fromOption(none, () => new Error("missing")) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))._tag) + * void output.push(Effect.runSync(Effect.flip(effect3)).message) + * output // => [42, "NoSuchElementError", "missing"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromOption = _internal_effect_js__rspack_import_1/* .fromOption */.sVm; +/** + * Converts an `Option` of an `Effect` into an `Effect` of an `Option`. + * + * **When to use** + * + * Use when an effect should run only when an optional value is present, while + * preserving absence as a successful `None`. + * + * **Details** + * + * - `None` becomes an effect that succeeds with `None` + * - `Some(effect)` runs the inner effect and wraps its success value in `Some` + * - Inner failures are preserved in the resulting effect + * + * **Example** (Transposing an Option of an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const some = Option.some(Effect.succeed(42)) + * + * // ┌─── Effect, never, never> + * // ▼ + * const program = Effect.transposeOption(some) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category converting + * @since 3.13.0 + */ +const transposeOption = _internal_effect_js__rspack_import_1/* .transposeOption */.pkL; +/** + * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` + * when the value is `null` or `undefined`. + * + * **Example** (Failing on nullish values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.fn(function*(input: string | null) { + * const value = yield* Effect.fromNullishOr(input) + * yield* Effect.sync(() => { output.push(value) }) + * }, + * Effect.catch(() => Effect.sync(() => { output.push("missing") })) + * ) + * + * await Effect.runPromise(program(null)) + * await Effect.runPromise(program("hello")) + * output // => ["missing", "hello"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = _internal_effect_js__rspack_import_1/* .fromNullishOr */.bJ; +// ----------------------------------------------------------------------------- +// Mapping +// ----------------------------------------------------------------------------- +/** + * Chains effects to produce new `Effect` instances, useful for combining + * operations that depend on previous results. + * + * **When to use** + * + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. + * + * **Details** + * + * `flatMap` lets you sequence effects so that the result of one effect can be + * used in the next step. It is similar to `flatMap` used with arrays but works + * specifically with `Effect` instances, allowing you to avoid deeply nested + * effect structures. + * + * Since effects are immutable, `flatMap` always returns a new effect instead of + * changing the original one. + * + * **Example** (Choosing flatMap syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * + * void output.push(Effect.runSync(Effect.all([ + * flatMappedWithPipe, + * flatMappedWithDataFirst, + * flatMappedWithMethod + * ]))) + * output // => [[2, 2, 2]] + * ``` + * + * **Example** (Sequencing dependent effects) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Chaining the fetch and discount application using `flatMap` + * const finalAmount = pipe( + * fetchTransactionAmount, + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(finalAmount) // => 95 + * ``` + * + * @see {@link tap} for a version that ignores the result of the effect. + * @category sequencing + * @since 2.0.0 + */ +const flatMap = _internal_effect_js__rspack_import_1/* .flatMap */.qIB; +/** + * Flattens an `Effect` that produces another `Effect` into a single effect. + * + * **Example** (Flattening nested effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const nested = Effect.succeed(Effect.succeed("hello")) + * + * const program = Effect.gen(function*() { + * const value = yield* Effect.flatten(nested) + * yield* Effect.sync(() => { output.push(value) }) + * }) + * + * Effect.runSync(program) + * output // => ["hello"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = _internal_effect_js__rspack_import_1/* .flatten */.Bqz; +/** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. + * + * **When to use** + * + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. + * + * **Details** + * + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. + * + * **Example** (Choosing andThen syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") + * + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * + * void output.push(Effect.runSync(Effect.all([ + * transformedWithPipe, + * transformedWithDataFirst, + * transformedWithMethod + * ]))) + * output // => [['done', 'done', 'done']] + * ``` + * + * **Example** (Sequencing a discount calculation after fetching a total) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Using Effect.map and Effect.flatMap + * const result1 = pipe( + * fetchTransactionAmount, + * Effect.map((amount) => amount * 2), + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result1) // => 190 + * + * // Using Effect.andThen + * const result2 = pipe( + * fetchTransactionAmount, + * Effect.andThen((amount) => Effect.succeed(amount * 2)), + * Effect.andThen((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result2) // => 190 + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = _internal_effect_js__rspack_import_1/* .andThen */.hgn; +/** + * 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] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tap = _internal_effect_js__rspack_import_1/* .tap */.Mim; +/** + * Converts both success and failure of an `Effect` into a `Result` type. + * + * **When to use** + * + * Use when you want an `Effect`'s typed failures to be handled as `Result` + * data while preserving the original error value. + * + * **Details** + * + * This function converts an effect that may fail into an effect that always + * succeeds, wrapping the outcome in a `Result` type. The result will be + * `Result.Failure` if the effect fails, containing the recoverable error, or + * `Result.Success` if it succeeds, containing the result. + * + * Using this function, you can handle recoverable errors explicitly without + * causing the effect to fail. This is particularly useful in scenarios where + * you want to chain effects and manage both success and failure in the same + * logical flow. + * + * The resulting effect cannot fail directly because all recoverable failures + * are represented inside the `Result` type. + * + * **Gotchas** + * + * `result` only captures typed, recoverable failures. Defects and + * interruptions are not captured inside the `Result` and still fail the + * effect. + * + * **Example** (Capturing success or failure as Result) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.result(success) + * const program2 = Effect.result(failure) + * + * Effect.runSync(program1) // => Result.succeed(42) + * + * Effect.runSync(program2) // => Result.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 4.0.0 + */ +const result = _internal_effect_js__rspack_import_1/* .result */.Ket; +/** + * Converts success to `Option.some` and failure to `Option.none`. + * + * **When to use** + * + * Use when you only care whether an effect succeeds and want recoverable + * failures represented as `Option.none`. + * + * **Details** + * + * Success values become `Option.some`, recoverable failures become + * `Option.none`, and defects still fail the effect. + * + * **Gotchas** + * + * `option` only captures typed, recoverable failures as `Option.none`. + * Defects and interruptions are not captured inside the `Option` and still + * fail the effect. + * + * `option` also discards typed failure values. Use `result` if the failure + * value matters. + * + * **Example** (Capturing success or failure as Option) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.all([ + * Effect.option(Effect.succeed(1)), + * Effect.option(Effect.fail("missing")) + * ]) + * + * Effect.runSync(program) // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link result} for a version that uses `Result` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 2.0.0 + */ +const option = _internal_effect_js__rspack_import_1/* .option */.uKv; +/** + * Transforms an effect to encapsulate both failure and success using the `Exit` + * data type. + * + * **When to use** + * + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. + * + * **Details** + * + * `exit` wraps an effect's success or failure inside an `Exit` type, allowing + * you to handle both cases explicitly. + * + * The resulting effect cannot fail because the failure is encapsulated within + * the `Exit.Failure` type. The error type is set to `never`, indicating that + * the effect is structured to never fail directly. + * + * **Example** (Capturing completion as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.exit(success) + * const program2 = Effect.exit(failure) + * + * Effect.runSync(program1) // => Exit.succeed(42) + * + * Effect.runSync(program2) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link result} for a version that uses `Result` instead. + * + * @category error handling + * @since 2.0.0 + */ +const exit = _internal_effect_js__rspack_import_1/* .exit */.NS5; +/** + * 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. + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .map */.TjK; +/** + * Replaces the value inside an effect with a constant value. + * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * + * `as` allows you to ignore the original value inside an effect and + * replace it with a new constant value. + * + * **Example** (Replacing a success value) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * // Replaces the value 5 with the constant "new value" + * const program = pipe(Effect.succeed(5), Effect.as("new value")) + * + * Effect.runSync(program) // => "new value" + * ``` + * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping + * @since 2.0.0 + */ +const as = _internal_effect_js__rspack_import_1.as; +/** + * Maps the success value of an `Effect` to `Some`, preserving failures. + * + * **Example** (Wrapping success in Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.asSome(Effect.succeed(42)) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asSome = _internal_effect_js__rspack_import_1/* .asSome */.Xx$; +/** + * Maps the success value of an `Effect` to `void`, preserving failures. + * + * **Example** (Discarding success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.asVoid(Effect.succeed(42)) + * + * Effect.runSync(program) // => undefined + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .asVoid */.NLW; +/** + * Swaps an effect's success and failure channels. + * + * **When to use** + * + * Use to swap an `Effect`'s success and failure channels. + * + * **Details** + * + * For an `Effect`, the returned effect has type `Effect`. + * + * **Example** (Swapping success and failure channels) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const program = Effect.fail("Oh uh!").pipe(Effect.as(2)) + * + * // ┌─── Effect + * // ▼ + * const flipped = Effect.flip(program) + * Effect.runSync(flipped) // => "Oh uh!" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flip = _internal_effect_js__rspack_import_1/* .flip */.UUz; +// ----------------------------------------------------------------------------- +// Zipping +// ----------------------------------------------------------------------------- +/** + * Combines two effects into a single effect, producing a tuple with the results of both effects. + * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * + * The `zip` function executes the first effect (left) and then the second effect (right). + * Once both effects succeed, their results are combined into a tuple. + * + * Concurrency: + * + * By default, `zip` processes the effects sequentially. To execute the effects concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two effects sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Combine the two effects together + * // + * // ┌─── Effect<[number, string], never, never> + * // ▼ + * const program = Effect.zip(task1, task2) + * + * Effect.runSync(program) // => [1, 'hello'] + * ``` + * + * **Example** (Combining two effects concurrently) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Run both effects concurrently using the concurrent option + * const program = Effect.zip(task1, task2, { concurrent: true }) + * + * await Effect.runPromise(program) // => [1, 'hello'] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. + * + * @category zipping + * @since 2.0.0 + */ +const zip = _internal_effect_js__rspack_import_1/* .zip */.yU6; +/** + * Combines two effects sequentially and applies a function to their results to + * produce a single value. + * + * **When to use** + * + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. + * + * **Details** + * + * Concurrency: + * + * By default, the effects are run sequentially. To execute them concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two success values with a function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * const task3 = Effect.zipWith( + * task1, + * task2, + * // Combines results into a single value + * (number, string) => number + string.length + * ) + * + * Effect.runSync(task3) // => 6 + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = _internal_effect_js__rspack_import_1/* .zipWith */.OYO; +// ----------------------------------------------------------------------------- +// Error handling +// ----------------------------------------------------------------------------- +const catch_ = _internal_effect_js__rspack_import_1/* .catch_ */.h_t; + +/** + * Catches and handles specific errors by their `_tag` field, which is used as a + * discriminator. + * + * **When to use** + * + * Use when you need to recover from one specific tagged error in an effect + * error channel. + * + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class NetworkError { + * readonly _tag = "NetworkError" + * constructor(readonly message: string) {} + * } + * + * class ValidationError { + * readonly _tag = "ValidationError" + * constructor(readonly message: string) {} + * } + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError("offline")) + * + * const program = Effect.catchTag( + * task, + * "NetworkError", + * (error) => Effect.succeed(`Recovered from network error: ${error.message}`) + * ) + * + * Effect.runSync(program) // => "Recovered from network error: offline" + * ``` + * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling + * @since 2.0.0 + */ +const catchTag = _internal_effect_js__rspack_import_1/* .catchTag */.KuX; +/** + * Handles multiple errors in a single block of code using their `_tag` field. + * + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** + * + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. + * + * The error type must have a readonly `_tag` field to use `catchTags`. This + * field is used to identify and match errors. + * + * **Example** (Handling multiple tagged errors) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * // Define tagged error types + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * message: string + * }> {} + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * // An effect that might fail with multiple error types + * const program: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 503 })) + * + * // Handle multiple error types at once + * const handled = Effect.catchTags(program, { + * ValidationError: (error) => + * Effect.succeed(`Validation failed: ${error.message}`), + * NetworkError: (error) => Effect.succeed(`Network error: ${error.statusCode}`) + * }) + * + * Effect.runSync(handled) // => "Network error: 503" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTags = _internal_effect_js__rspack_import_1/* .catchTags */.loE; +/** + * Catches a specific reason within a tagged error. + * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * + * Use this to handle nested error causes without removing the parent error + * from the error channel. The handler receives the unwrapped reason. + * + * **Example** (Handling an error reason) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Handle rate limits specifically + * const handled = program.pipe( + * Effect.catchReason("AiError", "RateLimitError", (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`) + * ) + * ) + * + * Effect.runSync(handled) // => "Retry after 30s" + * ``` + * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = _internal_effect_js__rspack_import_1/* .catchReason */.AXC; +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * **Example** (Handling multiple error reasons) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new QuotaExceededError({ limit: 100 }) }) + * ) + * + * const handled = program.pipe( + * Effect.catchReasons("AiError", { + * RateLimitError: (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`), + * QuotaExceededError: (reason) => + * Effect.succeed(`Quota exceeded: ${reason.limit}`) + * }) + * ) + * + * Effect.runSync(handled) // => "Quota exceeded: 100" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = _internal_effect_js__rspack_import_1/* .catchReasons */.zt4; +/** + * Promotes nested reason errors into the Effect error channel, replacing + * the parent error. + * + * **Example** (Extracting the reason from a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Before: Effect + * // After: Effect + * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) + * Effect.runSync(Effect.flip(unwrapped))._tag // => "RateLimitError" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const unwrapReason = _internal_effect_js__rspack_import_1/* .unwrapReason */.scW; +/** + * Handles both recoverable and unrecoverable errors by providing a recovery + * effect. + * + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. + * + * **Details** + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically shouldn't be recovered from, as + * they often indicate serious issues. However, in some cases, such as + * dynamically loaded plugins, controlled recovery might be needed. + * + * **Example** (Recovering from full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * // An effect that might fail in different ways + * const program = Effect.die("Something went wrong") + * + * // Recover from any cause (including defects) + * const recovered = Effect.catchCause(program, (cause) => { + * if (Cause.hasDies(cause)) { + * return Effect.sync(() => { output.push("Caught defect") }).pipe( + * Effect.as("Recovered from defect") + * ) + * } + * return Effect.succeed("Unknown error") + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = _internal_effect_js__rspack_import_1/* .catchCause */.Tyx; +/** + * Recovers from defects using a provided recovery function. + * + * **When to use** + * + * Use when you need to report or translate defects at integration boundaries. + * + * **Details** + * + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. + * + * **Example** (Recovering from defects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // An effect that might throw an unexpected error (defect) + * const program = Effect.sync(() => { + * throw new Error("Unexpected error") + * }) + * + * // Recover from defects only + * const recovered = Effect.catchDefect(program, (defect) => { + * return Effect.sync(() => { output.push(`Caught defect: ${(defect as Error).message}`) }).pipe( + * Effect.as("Recovered from defect") + * ) + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect: Unexpected error", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchDefect = _internal_effect_js__rspack_import_1/* .catchDefect */.Fig; +/** + * Recovers from specific errors using a `Predicate` or `Refinement`. + * + * **When to use** + * + * Use when you need to recover from errors that match a condition. + * + * **Details** + * + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. + * + * **Example** (Recovering when a predicate matches) + * + * ```ts import.meta.vitest + * import { Data, Effect, Filter } from "effect" + * + * class NotFound extends Data.TaggedError("NotFound")<{ id: string }> {} + * + * const program = Effect.fail(new NotFound({ id: "user-1" })) + * + * // With a refinement + * const recovered = program.pipe( + * Effect.catchIf( + * (error): error is NotFound => error._tag === "NotFound", + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * // With a Filter + * const recovered2 = program.pipe( + * Effect.catchFilter( + * Filter.tagged("NotFound"), + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * Effect.runSync(Effect.all([recovered, recovered2])) // => ['missing:user-1', 'missing:user-1'] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchIf = _internal_effect_js__rspack_import_1/* .catchIf */.XWm; +/** + * Recovers from specific errors using a `Filter`. + * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = _internal_effect_js__rspack_import_1/* .catchFilter */.osR; +/** + * Catches `NoSuchElementError` failures and converts them to `Option.none`. + * + * **When to use** + * + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. + * + * **Details** + * + * Success values become `Option.some`, `NoSuchElementError` becomes + * `Option.none`, and all other errors are preserved. + * + * **Example** (Recovering from missing Option values) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Effect.fromNullishOr(1).pipe(Effect.catchNoSuchElement) + * const none = Effect.fromNullishOr(null).pipe(Effect.catchNoSuchElement) + * + * void output.push(Effect.runSync(some)) + * void output.push(Effect.runSync(none)) + * output // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError` + * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError` + * @see {@link option} for converting any failure into `Option.none` + * + * @category error handling + * @since 4.0.0 + */ +const catchNoSuchElement = _internal_effect_js__rspack_import_1/* .catchNoSuchElement */.U9Y; +/** + * Recovers from specific failures based on a predicate. + * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * + * This function allows you to conditionally catch and recover from failures + * that match a specific predicate. This is useful when you want to handle + * only certain types of errors while letting others propagate. + * + * **Example** (Recovering from selected causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * const httpRequest = Effect.fail("Network Error") + * + * // Only catch network-related failures + * const program = Effect.catchCauseIf( + * httpRequest, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Caught network error: ${Cause.squash(cause)}`) }) + * return "Fallback response" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Caught network error: Network Error", "Fallback response"] + * ``` + * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = _internal_effect_js__rspack_import_1/* .catchCauseIf */.sJf; +/** + * Recovers from specific failures based on a `Filter`. + * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk; +/** + * Transforms the failure value of an effect without changing its success value. + * + * **When to use** + * + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const mapped = Effect.mapError( + * simulatedTask, + * (message) => new TaskError({ message }) + * ) + * Effect.runSync(Effect.flip(mapped)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .mapError */.xm_; +/** + * Applies transformations to both the success and error channels of an effect. + * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * + * **Details** + * + * This function takes two map functions as arguments: one for the error channel + * and one for the success channel. You can use it when you want to modify both + * the error and the success values without altering the overall success or + * failure status of the effect. + * + * **Example** (Transforming success and failure channels) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const modified = Effect.mapBoth(simulatedTask, { + * onFailure: (message) => new TaskError({ message }), + * onSuccess: (n) => n > 0 + * }) + * Effect.runSync(Effect.flip(modified)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapError} for a version that operates on the error channel. + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .mapBoth */.UcN; +/** + * Converts typed failures from the error channel into defects, removing the + * error type from the returned effect. + * + * **When to use** + * + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. + * + * **Example** (Converting typed failures into defects) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * + * class DivideByZeroError extends Data.TaggedError("DivideByZeroError")<{}> {} + * + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new DivideByZeroError()) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.orDie(divide(1, 0)) + * + * Effect.runSyncExit(program) // => Exit.die(new DivideByZeroError()) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = _internal_effect_js__rspack_import_1/* .orDie */.QgK; +/** + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. + * + * **Example** (Running effects on failure) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a task that fails with an error + * const task: Effect.Effect = Effect.fail("NetworkError") + * + * // Use tapError to log the error message when the task fails + * const tapping = Effect.tapError( + * task, + * (error) => Effect.sync(() => { output.push(`expected error: ${error}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping)) + * output // => ["expected error: NetworkError", Exit.fail("NetworkError")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = _internal_effect_js__rspack_import_1/* .tapError */.sFT; +/** + * Runs an effectful handler when a failure's `_tag` matches. + * + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * field: string + * }> {} + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 504 })) + * + * const program = Effect.tapErrorTag(task, "NetworkError", (error) => + * Effect.sync(() => { output.push(`expected error: ${error.statusCode}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["expected error: 504", Exit.fail(new NetworkError({ statusCode: 504 }))] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapErrorTag = _internal_effect_js__rspack_import_1/* .tapErrorTag */.k$L; +/** + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** + * + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. + * + * **Details** + * + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. + * + * **Example** (Observing full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.tapCause( + * task, + * (cause) => Effect.sync(() => { output.push(`Logging cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging cause: Something went wrong", Exit.fail("Something went wrong")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = _internal_effect_js__rspack_import_1/* .tapCause */.dGm; +/** + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** + * + * This function allows you to tap into the cause of an effect's failure only when + * the cause matches a specific predicate. This is useful for conditional logging, + * monitoring, or other side effects based on the type of failure. + * + * **Example** (Observing selected failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Network timeout") + * + * // Only log causes that contain failures (not interrupts or defects) + * const program = Effect.tapCauseIf( + * task, + * Cause.hasFails, + * (cause) => Effect.sync(() => { output.push(`Logging failure cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging failure cause: Network timeout", Exit.fail("Network timeout")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseIf = _internal_effect_js__rspack_import_1/* .tapCauseIf */.cA6; +/** + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. + * + * **Details** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseFilter = _internal_effect_js__rspack_import_1/* .tapCauseFilter */.bKC; +/** + * Runs an effectful operation when the source effect dies with a defect. + * + * **Details** + * + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. + * + * **Example** (Observing defects) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a severe failure in the system + * const task2: Effect.Effect = Effect.die( + * "Something went wrong" + * ) + * + * // Log the defect using tapDefect + * const tapping2 = Effect.tapDefect( + * task2, + * (defect) => Effect.sync(() => { output.push(`defect: ${defect}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping2)) + * output // => ["defect: Something went wrong", Exit.die("Something went wrong")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapDefect = _internal_effect_js__rspack_import_1/* .tapDefect */.nAi; +/** + * Retries an effect until it succeeds, discarding failures. + * + * **Details** + * + * Yields between attempts so other fibers can run. + * + * **Example** (Retrying until success) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let attempts = 0 + * + * const flaky = Effect.gen(function*() { + * attempts++ + * yield* Effect.sync(() => { output.push(`Attempt ${attempts}`) }) + * if (attempts < 3) { + * return yield* Effect.fail("Not ready") + * } + * return "Ready" + * }) + * + * const program = Effect.eventually(flaky) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Attempt 1", "Attempt 2", "Attempt 3", "Ready"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const eventually = _internal_effect_js__rspack_import_1/* .eventually */.u4Y; +/** + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. + * + * **Details** + * + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. + * + * **Gotchas** + * + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. + * + * Defects and interruptions are not retried. + * + * **Example** (Retrying with a schedule) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * + * class AttemptError extends Data.TaggedError("AttemptError")<{ readonly attempt: number }> {} + * + * let attempt = 0 + * const task = Effect.callback((resume) => { + * attempt++ + * if (attempt <= 2) { + * resume(Effect.fail(new AttemptError({ attempt }))) + * } else { + * resume(Effect.succeed("Success!")) + * } + * }) + * + * const policy = Schedule.recurs(5) + * const program = Effect.retry(task, policy) + * + * await Effect.runPromise(program) // => "Success!" + * ``` + * + * @see {@link retryOrElse} for a version that allows you to run a fallback. + * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. + * @category error handling + * @since 2.0.0 + */ +const retry = _internal_schedule_js__rspack_import_2/* .retry */.L5; +/** + * Retries a failing effect and runs a fallback effect if retries are exhausted. + * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * + * **Details** + * + * The `Effect.retryOrElse` function attempts to retry a failing effect multiple + * times according to a defined {@link Schedule} policy. + * + * If the retries are exhausted and the effect still fails, it runs a fallback + * effect instead. + * + * **Example** (Falling back after retries are exhausted) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * const output: Array = [] + * + * class NetworkTimeoutError extends Data.TaggedError("NetworkTimeoutError")<{}> {} + * + * let attempt = 0 + * const networkRequest = Effect.gen(function*() { + * attempt++ + * yield* Effect.sync(() => { output.push(`Network attempt ${attempt}`) }) + * if (attempt < 3) { + * return yield* Effect.fail(new NetworkTimeoutError()) + * } + * return "Network data" + * }) + * + * // Retry up to 2 times, then fall back to cached data + * const program = Effect.retryOrElse( + * networkRequest, + * Schedule.recurs(2), + * (error, retryCount) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`All ${retryCount} retries failed, using cache`) }) + * return "Cached data" + * }) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Network attempt 1", "Network attempt 2", "Network attempt 3", "Network data"] + * ``` + * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling + * @since 2.0.0 + */ +const retryOrElse = _internal_schedule_js__rspack_import_2/* .retryOrElse */.$L; +/** + * Exposes an effect's full failure cause in the error channel as `Cause`. + * + * **Details** + * + * Use `sandbox` when downstream error handling needs to distinguish typed + * failures, defects, and interruptions. Use `unsandbox` to restore the original + * typed error channel after cause-level handling. + * + * **Example** (Exposing failures as causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * // Sandbox exposes the full cause as the error type + * const program = Effect.gen(function*() { + * const result = yield* Effect.flip(Effect.sandbox(task)) + * return `Caught cause: ${Cause.squash(result)}` + * }) + * + * Effect.runSync(program) // => "Caught cause: Something went wrong" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const sandbox = _internal_effect_js__rspack_import_1/* .sandbox */._Sg; +/** + * Discards both the success and failure values of an effect. + * + * **When to use** + * + * Use when an effect should run for its side effects while both success and + * failure values are discarded. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Discarding success and failure values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const task = Effect.fail("Uh oh!").pipe(Effect.as(5)) + * + * // ┌─── Effect + * // ▼ + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * **Example** (Logging failures while ignoring results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("Uh oh!") + * + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const ignore = _internal_effect_js__rspack_import_1/* .ignore */.XeO; +/** + * Ignores the effect's failure cause, including defects and interruptions. + * + * **When to use** + * + * Use when a best-effort effect should never fail, even from defects or + * interruption, and optional cause logging is enough. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Ignoring failures and logging causes) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("boom") + * + * const program = task.pipe(Effect.ignoreCause) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = _internal_effect_js__rspack_import_1/* .ignoreCause */.GrF; +/** + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources + * until it succeeds or the plan is exhausted. + * + * **Details** + * + * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), + * and retry timing is derived per step (the first attempt uses the remaining + * attempts schedule; later retries apply the step schedule at least once). + * + * Attempts can be observed from outside the effect by passing + * `options.onEvent`, which receives an `ExecutionPlan.Event` before each + * attempt and after it settles. The handler is awaited inline before and after + * every attempt, so events are strictly ordered; keep it cheap. It cannot + * fail, which keeps observation from changing the plan's outcome, and its + * requirements are added to the resulting effect. Terminal events run like + * finalizers, so they are emitted even when the attempt is interrupted. + * + * **Example** (Retrying with an execution plan) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }), attempts: 2 }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const program = Effect.withExecutionPlan(fetchUrl, plan) + * Effect.runSync(program) // => "good" + * ``` + * + * **Example** (Observing execution-plan attempts) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }) }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const events: Array = [] + * const program = Effect.withExecutionPlan(fetchUrl, plan, { + * onEvent: (event) => Effect.sync(() => events.push(`${event._tag}:${event.stepIndex}`)) + * }) + * + * await Effect.runPromise(program) // => "good" + * + * events // => ["AttemptStart:0", "AttemptFailure:0", "AttemptStart:1", "AttemptSuccess:1"] + * ``` + * + * @category error handling + * @since 3.16.0 + */ +const withExecutionPlan = _internal_executionPlan_js__rspack_import_3/* .withExecutionPlan */.OR; +/** + * Runs an effect and reports any errors to the configured `ErrorReporter`s. + * + * **Details** + * + * If the `defectsOnly` option is set to `true`, only defects (unrecoverable + * errors) will be reported, while regular failures will be ignored. + * + * @category error handling + * @since 4.0.0 + */ +const withErrorReporting = _internal_effect_js__rspack_import_1/* .withErrorReporting */.$$g; +// ----------------------------------------------------------------------------- +// Fallback +// ----------------------------------------------------------------------------- +/** + * Recovers from a typed failure by producing a fallback success value. + * + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. + * + * Defects and interruptions are not recovered by this operator. + * + * **Example** (Replacing failures with a value) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const validate = (age: number): Effect.Effect => { + * if (age < 0) { + * return Effect.fail("NegativeAgeError") + * } else if (age < 18) { + * return Effect.fail("IllegalAgeError") + * } else { + * return Effect.succeed(age) + * } + * } + * + * const program = Effect.orElseSucceed(validate(-1), () => 18) + * + * Effect.runSyncExit(program) // => Exit.succeed(18) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSucceed = _internal_effect_js__rspack_import_1/* .orElseSucceed */.DM4; +/** + * Runs a sequence of effects and returns the result of the first successful + * one. + * + * **When to use** + * + * Use when you have prioritized fallback `Effect`s, such as attempting + * multiple APIs, reading configuration from several sources, or trying + * alternative resource locations in order. + * + * **Details** + * + * This function executes the provided effects in sequence, stopping at the + * first success. If an effect succeeds, its result is returned immediately and + * no further effects in the sequence are executed. + * + * If all effects fail, the returned effect fails with the error from the last + * effect. If the collection is empty, the returned effect defects with an + * `Error` whose message is `"Received an empty collection of effects"`. + * + * **Example** (Trying alternatives until one succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const primary = Effect.fail("primary unavailable") + * const secondary = Effect.succeed("secondary result") + * const tertiary = Effect.sync(() => { + * throw new Error("not evaluated") + * }) + * + * const program = Effect.firstSuccessOf([ + * primary, + * secondary, + * tertiary + * ]) + * + * Effect.runSync(program) // => "secondary result" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const firstSuccessOf = _internal_effect_js__rspack_import_1/* .firstSuccessOf */.Dd; +// ----------------------------------------------------------------------------- +// Delays & timeouts +// ----------------------------------------------------------------------------- +/** + * Adds a time limit to an effect, triggering a timeout if the effect exceeds + * the duration. + * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * + * The `timeout` function allows you to specify a time limit for an + * effect's execution. If the effect does not complete within the given time, a + * `TimeoutError` is raised. This can be useful for controlling how long your + * program waits for a task to finish, ensuring that it doesn't hang + * indefinitely if the task takes too long. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const timedEffect = Effect.never.pipe(Effect.timeout(0)) + * const error = await Effect.runPromise(Effect.flip(timedEffect)) + * error._tag // => "TimeoutError" + * ``` + * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timeout = _internal_effect_js__rspack_import_1/* .timeout */.wRz; +/** + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. + * + * **When to use** + * + * Use when a timeout of an `Effect` should be handled as `Option.none`. + * + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const timedOutEffect = Effect.never.pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(timedOutEffect) // => Option.none() + * ``` + * + * @see {@link timeout} for a version that raises a `TimeoutError`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 3.1.0 + */ +const timeoutOption = _internal_effect_js__rspack_import_1/* .timeoutOption */.D52; +/** + * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. + * + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.timeoutOrElse(Effect.never, { + * duration: 0, + * orElse: () => Effect.sync(() => { output.push("Query timed out, using cached data") }).pipe( + * Effect.as("Cached result") + * ) + * }) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Query timed out, using cached data", "Cached result"] + * ``` + * + * @see {@link timeout} for failing with a `TimeoutError`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 + */ +const timeoutOrElse = _internal_effect_js__rspack_import_1/* .timeoutOrElse */.mgX; +/** + * Returns an effect that is delayed from this effect by the specified + * `Duration`. + * + * **Example** (Delaying an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.delay(Effect.sync(() => { output.push("Delayed message") }), 0) + * + * await Effect.runPromise(program) + * output // => ["Delayed message"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const delay = _internal_effect_js__rspack_import_1/* .delay */.cbG; +/** + * Returns an effect that suspends the current fiber for the specified duration + * without blocking a JavaScript thread. + * + * **Example** (Pausing without blocking) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Start") }) + * yield* Effect.sleep(0) + * yield* Effect.sync(() => { output.push("End") }) + * }) + * + * await Effect.runPromise(program) + * output // => ["Start", "End"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const sleep = _internal_effect_js__rspack_import_1/* .sleep */.yy4; +/** + * Returns the runtime duration of an effect together with its result. + * + * **Details** + * + * The original success, failure, or interruption is preserved; only the success + * value is paired with the duration. + * + * **Example** (Measuring execution time) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const [, value] = yield* Effect.timed(Effect.succeed("ok")) + * return value + * }) + * + * Effect.runSync(program) // => "ok" + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timed = _internal_effect_js__rspack_import_1/* .timed */.ayu; +// ----------------------------------------------------------------------------- +// Racing +// ----------------------------------------------------------------------------- +/** + * Runs multiple effects concurrently and returns the first successful result. + * + * **When to use** + * + * Use when early failures should be ignored until a success occurs + * or all effects fail. + * + * **Details** + * + * Early failures do not finish the race; `raceAll` keeps waiting until one + * effect succeeds or every effect has failed. When one effect succeeds, the + * remaining effects are interrupted. If every effect fails, the returned effect + * fails with a cause containing the collected failure reasons. + * + * **Example** (Racing many effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAll([ + * Effect.succeed("Fast"), + * Effect.never + * ]) + * await Effect.runPromise(raced) // => "Fast" + * ``` + * + * @see {@link race} for a version that handles only two effects. + * @category racing + * @since 2.0.0 + */ +const raceAll = _internal_effect_js__rspack_import_1/* .raceAll */.Vdx; +/** + * Runs multiple effects concurrently and completes with the first effect to + * finish, whether it succeeds or fails. + * + * **Details** + * + * After the first effect completes, all remaining effects are interrupted. Use + * `raceAll` when early failures should be ignored until a success occurs or + * all effects fail. + * + * **Example** (Taking the first settled result) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAllFirst([ + * Effect.fail("First failed"), + * Effect.never + * ]) + * await Effect.runPromise(Effect.flip(raced)) // => "First failed" + * ``` + * + * @category racing + * @since 4.0.0 + */ +const raceAllFirst = _internal_effect_js__rspack_import_1/* .raceAllFirst */.FfP; +/** + * Races two effects and returns the first successful result. + * + * **Details** + * + * If one effect succeeds, the other is interrupted and `onWinner` can observe the + * winning fiber. If both fail, the race fails. + * + * **Example** (Racing two effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.succeed("slow-success") + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.race(fastFail, slowSuccess) + * yield* Effect.sync(() => { output.push(`winner: ${result}`) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["winner: slow-success"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const race = _internal_effect_js__rspack_import_1/* .race */.O4F; +/** + * Races two effects and returns the result of the first one to complete, whether + * it succeeds or fails. + * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * + * The losing effect is interrupted, and `onWinner` can observe the winning fiber. + * + * **Example** (Observing the winning fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.never + * + * const program = Effect.gen(function*() { + * const message = yield* Effect.match(Effect.raceFirst(fastFail, slowSuccess), { + * onFailure: (error) => `failed: ${error}`, + * onSuccess: (value) => `succeeded: ${value}` + * }) + * yield* Effect.sync(() => { output.push(message) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["failed: fast-fail"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const raceFirst = _internal_effect_js__rspack_import_1/* .raceFirst */.KT6; +// ----------------------------------------------------------------------------- +// Filtering +// ----------------------------------------------------------------------------- +/** + * Filters elements of an iterable using a predicate, refinement, or effectful + * predicate. + * + * **Example** (Filtering success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Sync predicate + * const evens = Effect.filter([1, 2, 3, 4], (n) => n % 2 === 0) + * + * // Effectful predicate + * const checked = Effect.filter([1, 2, 3], (n) => Effect.succeed(n > 1)) + * + * void output.push(Effect.runSync(evens)) + * void output.push(Effect.runSync(checked)) + * output // => [[2, 4], [2, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = _internal_effect_js__rspack_import_1/* .filter */.pbD; +/** + * Filters and maps elements of an iterable with a `Filter`. + * + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = _internal_effect_js__rspack_import_1/* .filterMap */.x1Q; +/** + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering + * @since 4.0.0 + */ +const filterMapEffect = _internal_effect_js__rspack_import_1/* .filterMapEffect */.E8K; +/** + * Filters an effect, providing an alternative effect if the predicate fails. + * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, it executes the `orElse` effect instead. The + * `orElse` effect can produce an alternative value or perform additional + * computations. + * + * **Example** (Filtering with a fallback effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, provide alternative for odd numbers + * const filtered = Effect.filterOrElse( + * program, + * (n) => n % 2 === 0, + * (n) => Effect.succeed(`Number ${n} is odd`) + * ) + * + * Effect.runSync(filtered) // => "Number 5 is odd" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrElse = _internal_effect_js__rspack_import_1/* .filterOrElse */.Pm0; +/** + * Filters an effect with a `Filter`, providing an alternative effect on failure. + * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrElse = _internal_effect_js__rspack_import_1/* .filterMapOrElse */.VtY; +/** + * Filters an effect, failing with a custom error if the predicate fails. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, the effect fails with either a custom + * error (if `orFailWith` is provided) or a `NoSuchElementError`. + * + * **Example** (Filtering with a custom failure) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, fail for odd numbers + * const filtered = Effect.filterOrFail( + * program, + * (n) => n % 2 === 0, + * (n) => `Expected even number, got ${n}` + * ) + * + * Effect.runSync(Effect.flip(filtered)) // => "Expected even number, got 5" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrFail = _internal_effect_js__rspack_import_1/* .filterOrFail */.W$I; +/** + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrFail = _internal_effect_js__rspack_import_1/* .filterMapOrFail */.ahH; +// ----------------------------------------------------------------------------- +// Conditional Operators +// ----------------------------------------------------------------------------- +/** + * Runs an effect conditionally based on the result of an effectful boolean + * condition. + * + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. + * + * **Details** + * + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. + * + * **Example** (Conditionally running an effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const shouldLog = true + * + * const program = Effect.when( + * Effect.sync(() => { output.push("Condition is true!") }), + * Effect.succeed(shouldLog) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Condition is true!", Option.some(undefined)] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const when = _internal_effect_js__rspack_import_1/* .when */.z7s; +// ----------------------------------------------------------------------------- +// Pattern matching +// ----------------------------------------------------------------------------- +/** + * Handles both success and failure cases of an effect without performing side + * effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * + * **Details** + * + * `match` lets you define custom handlers for both success and failure + * scenarios. You provide separate functions to handle each case, allowing you + * to process the result if the effect succeeds, or handle the error if the + * effect fails. + * + * **Example** (Matching success and failure values) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * + * const program1 = Effect.match(success, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the successful effect + * Effect.runSync(program1) // => "success: 42" + * + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program2 = Effect.match(failure, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the failed effect + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .match */.YWq; +/** + * Handles both success and failure cases of an effect without performing side + * effects, with eager evaluation for resolved effects. + * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * + * **Details** + * + * `matchEager` works like `match` but provides better performance for resolved + * effects (Success or Failure). When the effect is already resolved, it applies + * the handlers immediately without fiber scheduling. For unresolved effects, + * it falls back to the regular `match` behavior. + * + * **Example** (Pattern matching eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.matchEager(Effect.succeed(42), { + * onFailure: (error) => `Failed: ${error}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * void output.push(result) + * }) + * + * Effect.runSync(program) + * output // => ["Success: 42"] + * ``` + * + * @see {@link match} for the non-eager version. + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 4.0.0 + */ +const matchEager = _internal_effect_js__rspack_import_1/* .matchEager */.G$Q; +/** + * Handles failures by matching the cause of failure. + * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * + * **Details** + * + * The `matchCause` function allows you to handle failures with access to the + * full cause of the failure within a fiber. + * + * **Example** (Matching on success or failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.matchCause(task, { + * onFailure: (cause) => `Failed: ${Cause.squash(cause)}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * + * Effect.runSync(program) // => "Failed: Something went wrong" + * ``` + * + * @see {@link matchCauseEffect} if you need to perform side effects in the + * handlers. + * @see {@link match} if you don't need to handle the cause of the failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchCause = _internal_effect_js__rspack_import_1/* .matchCause */.D$$; +/** + * Handles failures by matching the cause of failure with eager evaluation. + * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * + * **Details** + * + * `matchCauseEager` works like `matchCause` but provides better performance for resolved + * effects by immediately applying the matching function instead of deferring it + * through the effect pipeline. + * + * **Example** (Eagerly matching already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const handleResult = Effect.matchCauseEager(Effect.succeed(42), { + * onSuccess: (value) => `Success: ${value}`, + * onFailure: (cause) => `Failed: ${cause}` + * }) + * Effect.runSync(handleResult) // => "Success: 42" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEager = _internal_effect_js__rspack_import_1/* .matchCauseEager */.NZb; +/** + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** + * + * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like + * {@link matchCauseEffect}. + * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEffectEager = _internal_effect_js__rspack_import_1/* .matchCauseEffectEager */.wR5; +/** + * Handles failures with access to the cause and allows performing side effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * + * **Details** + * + * The `matchCauseEffect` function works similarly to {@link matchCause}, but it + * also allows you to perform additional side effects based on the failure + * cause. This function provides access to the complete cause of the failure, + * making it possible to differentiate between various failure types, and allows + * you to respond accordingly while performing side effects (like logging or + * other operations). + * + * **Example** (Effectfully matching on causes) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Result } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const task = Effect.fail(new TaskError({ message: "Task failed" })) + * + * const program = Effect.matchCauseEffect(task, { + * onFailure: (cause) => + * Effect.gen(function*() { + * if (Cause.hasFails(cause)) { + * const error = Cause.findError(cause) + * if (Result.isSuccess(error)) { + * yield* Effect.sync(() => { output.push(`Handling error: ${error.success.message}`) }) + * } + * return "recovered from error" + * } else { + * yield* Effect.sync(() => { output.push("Handling interruption or defect") }) + * return "recovered from interruption/defect" + * } + * }), + * onSuccess: (value) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Success: ${value}`) }) + * return `processed ${value}` + * }) + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Handling error: Task failed", "recovered from error"] + * ``` + * + * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. + * @see {@link matchEffect} if you don't need to handle the cause of the failure. + * + * @category pattern matching + * @since 2.0.0 + */ +const matchCauseEffect = _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu; +/** + * Handles both success and failure by running effectful handlers. + * + * **When to use** + * + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. + * + * **Details** + * + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. + * + * **Example** (Matching success and failure with effectful handlers) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program1 = Effect.matchEffect(success, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program1) // => "success: 42" + * + * const program2 = Effect.matchEffect(failure, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchEffect = _internal_effect_js__rspack_import_1/* .matchEffect */.tvg; +// ----------------------------------------------------------------------------- +// Condition checking +// ----------------------------------------------------------------------------- +/** + * Determines whether an effect fails. + * + * **Details** + * + * Defects are not converted; if the effect dies, the resulting effect dies too. + * + * **Example** (Checking whether an effect fails) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const failed = yield* Effect.isFailure(Effect.fail("Uh oh!")) + * yield* Effect.sync(() => { output.push(failed) }) + * }) + * + * Effect.runSync(program) + * output // => [true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .isFailure */.N6O; +/** + * Returns whether an effect completes successfully. + * + * **Details** + * + * Returns `false` for failures in the error channel, but defects still fail the + * effect. + * + * **Example** (Checking whether an effect succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ok = yield* Effect.isSuccess(Effect.succeed("done")) + * const failed = yield* Effect.isSuccess(Effect.fail("Uh oh")) + * yield* Effect.sync(() => { output.push(`ok: ${ok}`) }) + * yield* Effect.sync(() => { output.push(`failed: ${failed}`) }) + * }) + * + * Effect.runSync(program) + * output // => ["ok: true", "failed: false"] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .isSuccess */.oJd; +// ----------------------------------------------------------------------------- +// Environment +// ----------------------------------------------------------------------------- +/** + * 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 + * + * @category accessors + * @since 2.0.0 + */ +const context = _internal_effect_js__rspack_import_1/* .context */._OA; +/** + * Transforms the current context using the provided function. + * + * **When to use** + * + * Use to derive an effect from the complete `Context`. + * + * **Details** + * + * This function allows you to access the complete context and perform + * computations based on all available services. This is useful when you need + * to conditionally execute logic based on what services are available. + * + * **Example** (Deriving values from the context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Cache = Context.Service<{ + * get: (key: string) => string | null + * }>("Cache") + * + * const program = Effect.contextWith((services: Context.Context>) => { + * const cacheOption = Context.getOption(services, Cache) + * const hasCache = Option.isSome(cacheOption) + * + * if (hasCache) { + * return Effect.gen(function*() { + * const cache = yield* Effect.service(Cache) + * yield* Effect.sync(() => { output.push("Using cached data") }) + * return cache.get("user:123") || "default" + * }) + * } else { + * return Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("No cache available, using fallback") }) + * return "fallback data" + * }) + * } + * }) + * + * const withCache = Effect.provideService(program, Cache, { + * get: () => "cached_value" + * }) + * void output.push(Effect.runSync(withCache)) + * output // => ["Using cached data", "cached_value"] + * ``` + * + * @see {@link context} for reading the complete context as a value + * @see {@link service} for reading one service from the context + * + * @category accessors + * @since 2.0.0 + */ +const contextWith = _internal_effect_js__rspack_import_1/* .contextWith */.sxi; +/** + * Provides dependencies to an effect using layers or a context. Use `options.local` + * to build the layer every time; by default, layers are shared between provide + * calls. + * + * **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" + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provide = _internal_layer_js__rspack_import_4/* .provide */.G; +/** + * Provides a context to an effect, fulfilling its service requirements. + * + * **Details** + * + * This function provides multiple services at once by supplying a context + * that contains all the required services. It removes the provided services + * from the effect's requirements, making them available to the effect. + * + * **Example** (Providing a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define service keys + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Database = Context.Service<{ + * query: (sql: string) => string + * }>("Database") + * + * // Create a context with multiple services + * const context = Context.make(Logger, { log: (message) => { output.push(message) } }) + * .pipe(Context.add(Database, { query: () => "result" })) + * + * // An effect that requires both services + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * const db = yield* Effect.service(Database) + * logger.log("Querying database") + * return db.query("SELECT * FROM users") + * }) + * + * const provided = Effect.provideContext(program, context) + * void output.push(Effect.runSync(provided)) + * output // => ["Querying database", "result"] + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const provideContext = _internal_effect_js__rspack_import_1/* .provideContext */.PpN; +/** + * Runs an effect with the provided context as its complete environment. + * + * **When to use** + * + * Use when you already have a `Context` containing every service required by + * the effect and want the wrapped effect to run with exactly that context. + * + * **Gotchas** + * + * `setContext` replaces the current context for the wrapped effect. Services + * from an outer context are not inherited unless they are also present in the + * context passed to `setContext`. + * + * **Example** (Running with a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const program = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * return `${config.greeting}, World!` + * }) + * + * const context = Context.make(Config, { greeting: "Hello" }) + * + * const runnable = Effect.setContext(program, context) + * + * Effect.runSync(runnable) // => "Hello, World!" + * ``` + * + * @see {@link provideContext} for partially satisfying an effect's context requirements. + * @see {@link updateContext} for deriving the required context from the current one. + * + * @category providing services + * @since 4.0.0 + */ +const setContext = _internal_effect_js__rspack_import_1/* .setContext */.oao; +/** + * Accesses a service from the context. + * + * **Example** (Accessing a required service) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Database { + * readonly query: (sql: string) => Effect.Effect + * } + * + * const Database = Context.Service("Database") + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * const runnable = Effect.provideService(program, Database, { + * query: (sql) => Effect.succeed(`Result for: ${sql}`) + * }) + * Effect.runSync(runnable) // => "Result for: SELECT * FROM users" + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const service = _internal_effect_js__rspack_import_1/* .service */.euC; +/** + * Optionally accesses a service from the environment. + * + * **When to use** + * + * Use to read an optional dependency from the current context without making + * that dependency part of the effect's required environment. + * + * **Details** + * + * This function attempts to access a service from the environment. If the + * service is available, it returns `Some(service)`. If the service is not + * available, it returns `None`. Unlike `service`, this function does not + * require the service to be present in the environment. + * + * **Example** (Accessing an optional service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * // Define a service key + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * // Use serviceOption to optionally access the logger + * const program = Effect.gen(function*() { + * const maybeLogger = yield* Effect.serviceOption(Logger) + * + * if (Option.isSome(maybeLogger)) { + * maybeLogger.value.log("Service is available") + * } else { + * void output.push("Service not available") + * } + * }) + * + * Effect.runSync(program) + * output // => ["Service not available"] + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const serviceOption = _internal_effect_js__rspack_import_1/* .serviceOption */.Nav; +/** + * Provides part of the required context while leaving the rest unchanged. + * + * **Details** + * + * This function allows you to transform the context required by an effect, + * providing part of the context and leaving the rest to be fulfilled later. + * + * **Example** (Updating the context before running) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * // Define services + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Config = Context.Service<{ + * name: string + * }>("Config") + * + * const program = Effect.service(Config).pipe( + * Effect.map((config) => `Hello ${config.name}!`) + * ) + * + * // Transform services by providing Config while keeping Logger requirement + * const configured = program.pipe( + * Effect.updateContext((context: Context.Context>) => + * Context.add(context, Config, { name: "World" }) + * ) + * ) + * + * // The effect now requires only Logger service + * const result = Effect.provideService(configured, Logger, { + * log: () => {} + * }) + * Effect.runSync(result) // => "Hello World!" + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = _internal_effect_js__rspack_import_1/* .updateContext */.r_d; +/** + * 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] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const updateService = _internal_effect_js__rspack_import_1/* .updateService */.bUZ; +/** + * 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 + * + * @category providing services + * @since 4.0.0 + */ +const updateServiceScoped = _internal_effect_js__rspack_import_1/* .updateServiceScoped */.L_I; +/** + * Provides one concrete service implementation to an effect. + * + * **When to use** + * + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a service for configuration + * const Config = Context.Service<{ + * apiUrl: string + * timeout: number + * }>("Config") + * + * const fetchData = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * yield* Effect.sync(() => { output.push(`Fetching from: ${config.apiUrl}`) }) + * yield* Effect.sync(() => { output.push(`Timeout: ${config.timeout}ms`) }) + * return "data" + * }) + * + * // Provide the service implementation + * const program = Effect.provideService(fetchData, Config, { + * apiUrl: "https://api.example.com", + * timeout: 5000 + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Fetching from: https://api.example.com", "Timeout: 5000ms", "data"] + * ``` + * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category providing services + * @since 2.0.0 + */ +const provideService = _internal_effect_js__rspack_import_1/* .provideService */.PfK; +/** + * Provides one service to an effect using an effectful acquisition. + * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a database connection service + * interface DatabaseConnection { + * readonly query: (sql: string) => Effect.Effect + * } + * const Database = Context.Service("Database") + * + * // Effect that creates a database connection + * const createConnection = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Establishing database connection...") }) + * yield* Effect.sync(() => { output.push("Database connected!") }) + * return { + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * // Provide the service through an effect + * const withDatabase = Effect.provideServiceEffect( + * program, + * Database, + * createConnection + * ) + * + * void output.push(await Effect.runPromise(withDatabase)) + * output // => ["Establishing database connection...", "Database connected!", "Result for: SELECT * FROM users"] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideServiceEffect = _internal_effect_js__rspack_import_1/* .provideServiceEffect */.c7E; +// ----------------------------------------------------------------------------- +// Resource management & finalization +// ----------------------------------------------------------------------------- +/** + * Returns the current scope for resource management. + * + * **Example** (Accessing the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const currentScope = yield* Effect.scope + * yield* Effect.sync(() => { output.push("Got scope for resource management") }) + * + * // Use the scope to manually manage resources if needed + * const resource = yield* Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * + * return resource + * }) + * + * void output.push(Effect.runSync(Effect.scoped(program))) + * output // => ["Got scope for resource management", "Acquiring resource", "Releasing resource", "resource"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scope = _internal_effect_js__rspack_import_1/* .scope */.z8E; +/** + * 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"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scoped = _internal_effect_js__rspack_import_1/* .scoped */.P1j; +/** + * Creates a scoped effect by providing access to the scope. + * + * **When to use** + * + * Use when resource acquisition needs direct access to the scope being created, + * for example to register finalizers manually. + * + * **Example** (Working with an explicit scope) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * const output: Array = [] + * + * const program = Effect.scopedWith((scope) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Inside scoped context") }) + * + * // Manually add a finalizer to the scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => { output.push("Manual finalizer") })) + * + * // Create a scoped resource + * const resource = yield* Effect.scoped( + * Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * ) + * + * return resource + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Inside scoped context", "Acquiring resource", "Releasing resource", "Manual finalizer", "resource"] + * ``` + * + * @category resource management + * @since 3.11.0 + */ +const scopedWith = _internal_effect_js__rspack_import_1/* .scopedWith */.Pxi; +/** + * 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 + * + * @category resource management + * @since 2.0.0 + */ +const acquireRelease = _internal_effect_js__rspack_import_1/* .acquireRelease */.Q56; +/** + * Acquires a scoped resource that implements JavaScript disposal protocols. + * + * **When to use** + * + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. + * + * **Details** + * + * The resource is automatically disposed when the surrounding + * {@link Scope} is closed, using {@link Symbol.dispose} for + * synchronous disposables or {@link Symbol.asyncDispose} for asynchronous + * disposables. + * + * This is similar to {@link acquireRelease}, but uses the standard + * JavaScript disposal protocol instead of requiring an explicit release + * function. It works with JavaScript `Disposable` and `AsyncDisposable` + * resources. + * + * **Example** (Acquiring a disposable resource) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * class Resource implements Disposable { + * [Symbol.dispose]() { + * void output.push("disposed") + * } + * } + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.acquireDisposable(Effect.succeed(new Resource())) + * void output.push("acquired") + * }) + * ) + * + * Effect.runSync(program) + * output // => ["acquired", "disposed"] + * ``` + * + * @see {@link acquireRelease} for resources that need an explicit finalizer + * + * @category resource management + * @since 4.0.0 + */ +const acquireDisposable = _internal_effect_js__rspack_import_1/* .acquireDisposable */.N24; +/** + * Runs resource acquisition, usage, and release as one bracketed effect. + * + * **When to use** + * + * Use to bracket acquire, use, and release logic in one effect. + * + * **Details** + * + * `acquireUseRelease` does the following: + * + * 1. Ensures that the `Effect` value that acquires the resource will not be + * interrupted. Note that acquisition may still fail due to internal + * reasons (such as an uncaught exception). + * 2. Ensures that the `release` `Effect` value will not be interrupted, + * and will be executed as long as the acquisition `Effect` value + * successfully acquires the resource. + * + * During the time period between the acquisition and release of the resource, + * the `use` `Effect` value will be executed. + * + * If the `release` `Effect` value fails, then the entire `Effect` value will + * fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior + * is not desired, errors produced by the `release` `Effect` value can be caught + * and ignored. + * + * **Example** (Acquiring resources with cleanup) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * readonly connection: string + * readonly query: (sql: string) => Effect.Effect + * } + * + * const program = Effect.acquireUseRelease( + * // Acquire - connect to database + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Connecting to database...") }) + * return { + * connection: "db://localhost:5432", + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }), + * // Use - perform database operations + * (db) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Connected to ${db.connection}`) }) + * const result = yield* db.query("SELECT * FROM users") + * yield* Effect.sync(() => { output.push(`Query result: ${result}`) }) + * return result + * }), + * // Release - close database connection + * (db, exit) => + * Effect.gen(function*() { + * if (Exit.isSuccess(exit)) { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (success)`) }) + * } else { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (failure)`) }) + * } + * }) + * ) + * + * await Effect.runPromise(program) + * output // => ["Connecting to database...", "Connected to db://localhost:5432", "Query result: Result for: SELECT * FROM users", "Closing connection to db://localhost:5432 (success)"] + * ``` + * + * @see {@link acquireRelease} for scoped resources whose use happens later + * + * @category resource management + * @since 2.0.0 + */ +const acquireUseRelease = _internal_effect_js__rspack_import_1/* .acquireUseRelease */.jGc; +/** + * Adds a finalizer to the current scope. + * + * **When to use** + * + * Use to register low-level cleanup in the current scope. + * + * **Details** + * + * The finalizer runs when the surrounding scope is closed and receives the + * `Exit` value used to close the scope. + * + * **Example** (Registering scope finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * // Add a finalizer that runs when the scope closes + * yield* Effect.addFinalizer((exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? "Cleanup: Operation completed successfully" + * : "Cleanup: Operation failed, cleaning up resources" + * ) }) + * ) + * + * yield* Effect.sync(() => { output.push("Performing main operation...") }) + * + * // This could succeed or fail + * return "operation result" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Performing main operation...", "Cleanup: Operation completed successfully", "operation result"] + * ``` + * + * @see {@link acquireRelease} for resource acquisition with a release finalizer + * @see {@link ensuring} for attaching a finalizer to one effect + * + * @category resource management + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_1/* .addFinalizer */.U9h; +/** + * Returns an effect that, if this effect _starts_ execution, then the + * specified `finalizer` is guaranteed to be executed, whether this effect + * succeeds, fails, or is interrupted. + * + * **Details** + * + * For use cases that need access to the effect's result, see `onExit`. + * + * Finalizers offer very powerful guarantees, but they are low-level, and + * should generally not be used for releasing resources. For higher-level + * logic built on `ensuring`, see the `acquireRelease` family of methods. + * + * **Example** (Always running cleanup) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task started") }) + * yield* Effect.sync(() => { output.push("Task completed") }) + * return 42 + * }) + * + * // Ensure cleanup always runs, regardless of success or failure + * const program = Effect.ensuring( + * task, + * Effect.sync(() => { output.push("Cleanup: This always runs!") }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task started", "Task completed", "Cleanup: This always runs!", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = _internal_effect_js__rspack_import_1/* .ensuring */.yeE; +/** + * Runs the specified effect if this effect fails, providing the error to the + * effect if it exists. The provided effect will not be interrupted. + * + * **Example** (Running cleanup on failure) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const error = new TaskError({ message: "Something went wrong" }) + * const task = Effect.fail(error) + * + * const program = Effect.onError( + * task, + * (cause) => Effect.sync(() => { output.push(`Cleanup on error: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cleanup on error: TaskError: Something went wrong", Exit.fail(error)] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onError = _internal_effect_js__rspack_import_1/* .onError */.S5A; +/** + * Runs the finalizer only when this effect fails and the `Cause` matches the + * provided predicate. + * + * **Example** (Running cleanup for selected failures) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("boom") + * + * const program = Effect.onErrorIf( + * task, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Cause: ${Cause.squash(cause)}`) }) + * }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cause: boom", Exit.fail("boom")] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onErrorIf = _internal_effect_js__rspack_import_1/* .onErrorIf */.BeE; +/** + * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management + * @since 4.0.0 + */ +const onErrorFilter = _internal_effect_js__rspack_import_1/* .onErrorFilter */.iKM; +/** + * Runs an optional finalizer with the effect's `Exit` value when the effect + * completes. + * + * **When to use** + * + * Use when you are building a low-level `Effect` operator that must inspect the + * source effect's `Exit`, may skip finalization by returning `undefined`, or + * must choose whether finalization is forced into an uninterruptible region. + * + * **Details** + * + * This low-level operator preserves the source effect's result unless the + * finalizer fails. If both the source effect and the finalizer fail, the two + * causes are merged. Prefer `onExit` for normal cleanup logic. + * + * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect + * + * @category resource management + * @since 4.0.0 + */ +const onExitPrimitive = _internal_effect_js__rspack_import_1/* .onExitPrimitive */.r7h; +/** + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * If both the effect and the cleanup function fail, the two causes are merged. + * + * **Example** (Observing every exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.succeed(42) + * + * const program = Effect.onExit(task, (exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? `Task succeeded with: ${exit.value}` + * : `Task failed: ${Exit.isFailure(exit) ? exit.cause : "interrupted"}` + * ) })) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onExit = _internal_effect_js__rspack_import_1/* .onExit */.cfM; +/** + * Runs the cleanup effect only when the `Exit` satisfies the provided + * predicate. + * + * **Example** (Observing selected exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.onExitIf( + * Effect.succeed(42), + * Exit.isSuccess, + * (exit) => + * Exit.isSuccess(exit) + * ? Effect.sync(() => { output.push(`Succeeded with: ${exit.value}`) }) + * : Effect.void + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExitIf = _internal_effect_js__rspack_import_1/* .onExitIf */.fGe; +/** + * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management + * @since 4.0.0 + */ +const onExitFilter = _internal_effect_js__rspack_import_1/* .onExitFilter */.uRq; +// ----------------------------------------------------------------------------- +// Caching +// ----------------------------------------------------------------------------- +/** + * Returns an effect that lazily computes a result and caches it for subsequent + * evaluations. + * + * **When to use** + * + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. + * + * **Details** + * + * This function wraps an effect and ensures that its result is computed only + * once. Once the result is computed, it is cached, meaning that subsequent + * evaluations of the same effect will return the cached result without + * re-executing the logic. + * + * **Example** (Memoizing an effect until invalidated) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * void output.push("non-cached version:") + * yield* expensiveTask.pipe(Effect.andThen(record)) + * yield* expensiveTask.pipe(Effect.andThen(record)) + * void output.push("cached version:") + * const cached = yield* Effect.cached(expensiveTask) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * await Effect.runPromise(program) + * output // => ["non-cached version:", "expensive task...", "result 1", "expensive task...", "result 2", "cached version:", "expensive task...", "result 3", "result 3"] + * ``` + * + * @see {@link cachedWithTTL} for a similar function that includes a + * time-to-live duration for the cached value. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cached = _internal_effect_js__rspack_import_1/* .cached */.PO3; +/** + * Returns an effect that caches its result for a specified `Duration`, + * known as "timeToLive" (TTL). + * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * + * **Details** + * + * This function is used to cache the result of an effect for a specified amount + * of time. This means that the first time the effect is evaluated, its result + * is computed and stored. + * + * If the effect is evaluated again within the specified `timeToLive`, the + * cached result will be used, avoiding recomputation. + * + * After the specified duration has passed, the cache expires, and the effect + * will be recomputed upon the next evaluation. + * + * **Example** (Memoizing an effect with TTL) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const cached = yield* Effect.cachedWithTTL(expensiveTask, "1 hour") + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "result 1"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cachedWithTTL = _internal_effect_js__rspack_import_1/* .cachedWithTTL */.Rgn; +/** + * Creates a cached effect result for a specified duration and allows manual + * invalidation before expiration. + * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * + * **Details** + * + * This function behaves similarly to {@link cachedWithTTL} by caching the + * result of an effect for a specified period of time. However, it introduces an + * additional feature: it provides an effect that allows you to manually + * invalidate the cached result before it naturally expires. + * + * This gives you more control over the cache, allowing you to refresh the + * result when needed, even if the original cache has not yet expired. + * + * Once the cache is invalidated, the next time the effect is evaluated, the + * result will be recomputed, and the cache will be refreshed. + * + * **Example** (Memoizing with TTL and invalidation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL( + * expensiveTask, + * "1 hour" + * ) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* invalidate + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "expensive task...", "result 2"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching + * @since 2.0.0 + */ +const cachedInvalidateWithTTL = _internal_effect_js__rspack_import_1/* .cachedInvalidateWithTTL */.CJw; +// ----------------------------------------------------------------------------- +// Interruption +// ----------------------------------------------------------------------------- +/** + * Returns an effect that is immediately interrupted. + * + * **Example** (Creating an interrupted effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * return yield* Effect.interrupt + * yield* Effect.succeed("This won't execute and is unreachable") + * }) + * + * Effect.runSyncExit(program)._tag // => "Failure" + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .interrupt */.GaK; +/** + * Returns a new effect that allows the effect to be interruptible. + * + * **Example** (Allowing interruption) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.interruptible(Effect.never).pipe( + * Effect.timeoutOption(0) + * ) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptible = _internal_effect_js__rspack_import_1/* .interruptible */.Inz; +/** + * Runs the specified finalizer effect if this effect is interrupted. + * + * **Example** (Running cleanup on interruption) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * const task = Effect.forever(Effect.succeed("working...")) + * + * const program = Effect.onInterrupt( + * task, + * () => Effect.sync(() => { output.push("Task was interrupted, cleaning up...") }) + * ) + * + * const fiber = Effect.runFork(program) + * await Effect.runPromise(Fiber.interrupt(fiber)) + * output // => ["Task was interrupted, cleaning up..."] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const onInterrupt = _internal_effect_js__rspack_import_1/* .onInterrupt */.nAr; +/** + * Returns a new effect that disables interruption for the given effect. + * + * **Example** (Preventing interruption) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const criticalTask = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Starting critical section...") }) + * yield* Effect.sync(() => { output.push("Critical section completed") }) + * }) + * + * const program = Effect.uninterruptible(criticalTask) + * + * Effect.runSync(program) + * output // => ["Starting critical section...", "Critical section completed"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptible = _internal_effect_js__rspack_import_1/* .uninterruptible */.rfi; +/** + * Disables interruption and provides a restore function to restore the + * interruptible state within the effect. + * + * **Example** (Restoring interruption in protected regions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.uninterruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * // Restore interruptibility for this part + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to uninterruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Uninterruptible phase...", "Interruptible phase...", "Back to uninterruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptibleMask = _internal_effect_js__rspack_import_1/* .uninterruptibleMask */.FcF; +/** + * Runs an effect in an interruptible region while providing `restore` for + * locally restoring the previous interruptibility. + * + * **Example** (Controlling interruptibility locally) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.interruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * // Make this part uninterruptible + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to interruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Interruptible phase...", "Uninterruptible phase...", "Back to interruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptibleMask = _internal_effect_js__rspack_import_1/* .interruptibleMask */.eMl; +/** + * Creates an AbortSignal that is managed by the provided scope. + * + * **When to use** + * + * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation + * through a signal. + * + * **Details** + * + * Each acquisition creates a fresh `AbortController`. Closing the owning scope + * runs a finalizer that aborts the controller and the effect succeeds with the + * controller's signal. + * + * **Gotchas** + * + * The signal is aborted when its owning scope closes, so avoid keeping it for + * work that outlives that scope. + * + * @see {@link scoped} for binding resource lifetime to a scope + * + * @category interruption + * @since 4.0.0 + */ +const abortSignal = _internal_effect_js__rspack_import_1/* .abortSignal */.dsN; +/** + * Repeats this effect forever (until the first error). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.forever(Effect.never).pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const forever = _internal_effect_js__rspack_import_1/* .forever */.i4r; +/** + * Repeats an effect based on a specified schedule or until the first failure. + * + * **When to use** + * + * Use to rerun an effect after successful executions. + * + * **Details** + * + * This function executes an effect repeatedly according to the given schedule. + * Each repetition occurs after the initial execution of the effect, meaning + * that the schedule determines the number of additional repetitions. For + * example, using `Schedule.once` will result in the effect being executed twice + * (once initially and once as part of the repetition). + * + * If the effect succeeds, it is repeated according to the schedule. If it + * fails, the repetition stops immediately, and the failure is returned. + * + * The schedule can also specify delays between repetitions, making it useful + * for tasks like retrying operations with backoff, periodic execution, or + * performing a series of dependent actions. + * + * You can combine schedules for more advanced repetition logic, such as adding + * delays, limiting recursions, or dynamically adjusting based on the outcome of + * each execution. + * + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * + * ```ts import.meta.vitest + * // Success Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const action = Effect.sync(() => { output.push("success") }) + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push(Effect.runSync(program)) + * output // => ["success", "success", "success", 2] + * ``` + * + * **Example** (Stopping repetition on failure) + * + * ```ts import.meta.vitest + * // Failure Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * let count = 0 + * + * // Define a callback effect that simulates an action with possible failures + * const action = Effect.callback((resume) => { + * if (count > 1) { + * void output.push("failure") + * resume(Effect.fail("Uh oh!")) + * } else { + * count++ + * void output.push("success") + * resume(Effect.succeed("yay!")) + * } + * }) + * + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push((await Effect.runPromiseExit(program))._tag) + * output // => ["success", "success", "failure", "Failure"] + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails + * + * @category repetition + * @since 2.0.0 + */ +const repeat = _internal_schedule_js__rspack_import_2/* .repeat */.ux; +/** + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. + * + * **Details** + * + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. + * + * **Example** (Recovering after repetition stops) + * + * ```ts import.meta.vitest + * import { Effect, Option, Schedule } from "effect" + * const output: Array = [] + * + * let attempt = 0 + * const task = Effect.gen(function*() { + * attempt++ + * if (attempt <= 2) { + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} failed`) }) + * return yield* Effect.fail(`Error ${attempt}`) + * } + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} succeeded`) }) + * return "success" + * }) + * + * const program = Effect.repeatOrElse( + * task, + * Schedule.recurs(3), + * (error, attempts) => + * Effect.sync(() => { output.push( + * `Final failure: ${error}, after ${ + * Option.getOrElse(attempts, () => 0) + * } attempts` + * ) }).pipe(Effect.map(() => 0)) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Attempt 1 failed", "Final failure: Error 1, after 0 attempts", 0] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const repeatOrElse = _internal_schedule_js__rspack_import_2/* .repeatOrElse */.i3; +/** + * Returns an array of `n` identical effects. + * + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category repetition + * @since 2.0.0 + */ +const replicate = _internal_effect_js__rspack_import_1/* .replicate */.aAq; +/** + * Performs this effect `n` times and collects results with `Effect.all` semantics. + * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * + * Use `concurrency` to control parallelism and `discard: true` to ignore results. + * + * **Example** (Replicating an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const results = yield* Effect.replicateEffect(3)(Effect.succeed(1)) + * yield* Effect.sync(() => { output.push(results) }) + * }) + * + * Effect.runSync(program) + * output // => [[1, 1, 1]] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const replicateEffect = _internal_effect_js__rspack_import_1/* .replicateEffect */.Xrv; +/** + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. + * + * **Details** + * + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. + * + * **Example** (Scheduling repeated execution) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task executing...") }) + * return 1 + * }) + * + * const program = Effect.schedule(task, Schedule.recurs(2)) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task executing...", "Task executing...", 2] + * ``` + * + * @see {@link scheduleFrom} for a variant that allows the schedule's decision + * to depend on the result of this effect. + * + * @category repetition + * @since 2.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => scheduleFrom(self, undefined, schedule)))); +/** + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. + * + * **Details** + * + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. + * + * **Example** (Scheduling from an initial value) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = (input: number) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Processing: ${input}`) }) + * return input + 1 + * }) + * + * // Start with 0, repeat 3 times + * const program = Effect.scheduleFrom( + * task(0), + * 0, + * Schedule.recurs(2) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Processing: 0", "Processing: 0", 2] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const scheduleFrom = _internal_schedule_js__rspack_import_2/* .scheduleFrom */.mG; +// ----------------------------------------------------------------------------- +// Tracing +// ----------------------------------------------------------------------------- +/** + * Returns the current tracer from the context. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const currentTracer = yield* Effect.tracer + * return typeof currentTracer.span + * }) + * + * Effect.runSync(program) // => "function" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const tracer = _internal_effect_js__rspack_import_1/* .tracer */.kJM; +/** + * Provides a tracer to an effect. + * + * **Example** (Providing a tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.tracer + * return yield* Effect.withTracer(Effect.succeed("completed"), tracer) + * }) + * + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracer = _internal_effect_js__rspack_import_1/* .withTracer */._o1; +/** + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not be registered with the tracer + * Effect.withTracerEnabled(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerEnabled = _internal_effect_js__rspack_import_1/* .withTracerEnabled */.nDN; +/** + * Enables or disables tracer timing for the given Effect. + * + * **Example** (Enabling or disabling tracing timing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not have timing information + * Effect.withTracerTiming(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerTiming = _internal_effect_js__rspack_import_1/* .withTracerTiming */.MaT; +/** + * Adds an annotation to each span in this effect. + * + * **Example** (Annotating all spans) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed("result") + * + * // Add single annotation + * const annotated1 = Effect.annotateSpans(program, "user", "john") + * + * // Add multiple annotations + * const annotated2 = Effect.annotateSpans(program, { + * operation: "data-processing", + * version: "1.0.0", + * environment: "production" + * }) + * + * Effect.runSync(Effect.all([annotated1, annotated2])) // => ['result', 'result'] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateSpans = _internal_effect_js__rspack_import_1/* .annotateSpans */.Muk; +/** + * Adds an annotation to the current span if available. + * + * **Example** (Annotating the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * yield* Effect.annotateCurrentSpan("userId", "123") + * yield* Effect.annotateCurrentSpan({ + * operation: "user-lookup" + * }) + * return "success" + * }) + * + * const traced = Effect.withSpan(program, "user-operation") + * Effect.runSync(traced) // => "success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateCurrentSpan = _internal_effect_js__rspack_import_1/* .annotateCurrentSpan */.ww9; +/** + * Returns the currently active local tracing span. + * + * **Details** + * + * The effect fails with `NoSuchElementError` when there is no active local + * `Span`. + * + * **Example** (Reading the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.currentSpan + * return span.name + * }) + * + * const traced = Effect.withSpan(program, "my-span") + * Effect.runSync(traced) // => "my-span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentSpan = _internal_effect_js__rspack_import_1/* .currentSpan */._32; +/** + * Returns the current parent span from the effect context. + * + * **Details** + * + * The effect succeeds with either a local span or external span when one is + * present, and fails with `NoSuchElementError` when no parent span is + * available. + * + * **Example** (Reading the parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const childOperation = Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * return parentSpan._tag + * }) + * + * const program = Effect.withSpan(childOperation, "child-span") + * + * const traced = Effect.withSpan(program, "parent-span") + * Effect.runSync(traced) // => "Span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentParentSpan = _internal_effect_js__rspack_import_1/* .currentParentSpan */.Wj8; +/** + * Returns the tracing span annotations currently carried in the effect context. + * + * **Details** + * + * These annotations are applied to spans created inside the context, such as + * spans created by `withSpan`, `useSpan`, or `makeSpan`. + * + * **Example** (Providing span annotations) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const annotations = yield* Effect.spanAnnotations + * return annotations + * }).pipe(Effect.annotateSpans({ userId: "123", operation: "data-processing" })) + * + * Effect.runSync(program) // => { userId: '123', operation: 'data-processing' } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanAnnotations = _internal_effect_js__rspack_import_1/* .spanAnnotations */.Fu6; +/** + * Returns the tracing span links currently carried in the effect context. + * + * **Details** + * + * These links are attached to spans created inside the context. Span links + * connect related spans without making one span the parent of another. + * + * **Example** (Providing span links) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * // Get the current span links + * const links = yield* Effect.spanLinks + * return links + * }) + * + * Effect.runSync(program).length // => 0 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanLinks = _internal_effect_js__rspack_import_1/* .spanLinks */.WbR; +/** + * Adds a link with the provided span to all spans in this effect. + * + * **Details** + * + * This is useful for connecting spans that are related but not in a direct + * parent-child relationship. For example, you might want to link spans from + * parallel operations or connect spans across different traces. + * + * **Example** (Linking one span to another span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.withSpan(Effect.gen(function*() { + * const parentSpan = yield* Effect.currentSpan + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans(parentSpan, { relationship: "follows" }) + * ) + * }), "parent-operation") + * + * Effect.runSync(program).length // => 1 + * ``` + * + * **Example** (Linking multiple spans at once) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span1 = yield* Effect.makeSpan("span-1") + * const span2 = yield* Effect.makeSpan("span-2") + * + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans([span1, span2], { + * type: "dependency", + * source: "multiple-operations" + * }) + * ) + * }) + * + * Effect.runSync(program).length // => 2 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const linkSpans = _internal_effect_js__rspack_import_1/* .linkSpans */.A_r; +/** + * Creates a new tracing span and returns it without managing its lifetime. + * + * **Details** + * + * The span is not added to the current span stack and is not ended + * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span + * should be installed as context or closed automatically. + * + * **Example** (Creating a span manually) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("my-operation") + * return span.name + * }) + * + * Effect.runSync(program) // => "my-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpan = _internal_effect_js__rspack_import_1/* .makeSpan */.Z98; +/** + * Create a new span for tracing, and automatically close it when the Scope + * finalizes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Creating a scoped standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const span = yield* Effect.makeSpanScoped("scoped-operation") + * return span.name + * // Span automatically closes when scope ends + * }) + * ) + * + * Effect.runSync(program) // => "scoped-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpanScoped = _internal_effect_js__rspack_import_1/* .makeSpanScoped */.Rd$; +/** + * Create a new span for tracing, and automatically close it when the effect + * completes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Running an effect with a standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.useSpan( + * "user-operation", + * (span) => Effect.succeed(`${span.name}: success`) + * ) + * Effect.runSync(program) // => "user-operation: success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const useSpan = _internal_effect_js__rspack_import_1/* .useSpan */.gvr; +/** + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.succeed("result") + * + * const traced = Effect.withSpan(task, "my-task", { + * attributes: { version: "1.0" } + * }) + * Effect.runSync(traced) // => "result" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = _internal_effect_js__rspack_import_1/* .withSpan */.fRP; +/** + * Wraps the effect with a scoped child span for tracing. + * + * **Details** + * + * The span is ended when the Scope is finalized. + * + * **Example** (Creating a scoped child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const task = Effect.succeed("working") + * yield* Effect.withSpanScoped(task, "scoped-task") + * return "completed" + * }) + * ) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpanScoped = _internal_effect_js__rspack_import_1/* .withSpanScoped */.zr8; +/** + * Adds the provided span to the current span stack. + * + * **Example** (Setting a parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("parent-span") + * const childTask = Effect.succeed("child operation") + * yield* Effect.withParentSpan(childTask, span) + * return "completed" + * }) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = _internal_effect_js__rspack_import_1/* .withParentSpan */.hq; +// ----------------------------------------------------------------------------- +// Batching +// ----------------------------------------------------------------------------- +/** + * Executes a request using the provided resolver. + * + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Request, RequestResolver } from "effect" + * const output: Array = [] + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: number + * } + * const GetUser = Request.tagged("GetUser") + * + * const resolver = RequestResolver.make( + * Effect.fnUntraced(function*(entries) { + * for (const entry of entries) { + * yield* Request.complete(entry, Exit.succeed(`user-${entry.request.id}`)) + * } + * }) + * ) + * + * const program = Effect.gen(function*() { + * const name = yield* Effect.request(GetUser({ id: 1 }), resolver) + * yield* Effect.sync(() => { output.push(name) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["user-1"] + * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category running + * @since 2.0.0 + */ +const request = _internal_request_js__rspack_import_5/* .request */.E; +/** + * Registers a request with a resolver and delivers the exit value via `onExit`. + * + * **When to use** + * + * Use when you already have a `Context` and need to enqueue a request outside + * an `Effect` while receiving completion through `onExit`. + * + * **Details** + * + * It returns a canceler that removes the pending request entry. + * + * @see {@link request} for the `Effect`-returning API used for normal request execution + * + * @category unsafe + * @since 4.0.0 + */ +const requestUnsafe = _internal_request_js__rspack_import_5/* .requestUnsafe */.m; +// ----------------------------------------------------------------------------- +// Supervision & Fiber's +// ----------------------------------------------------------------------------- +/** + * 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 other higher-level methods, such as `raceWith`, + * `zipPar`, and so forth. + * + * 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" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkChild = _internal_effect_js__rspack_import_1/* .forkChild */.zhn; +/** + * Forks the effect in the specified scope. The fiber will be interrupted + * when the scope is closed. + * + * **Example** (Forking into a supplied scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const scope = yield* Effect.scope + * const fiber = yield* Effect.forkIn(task, scope) + * // Fiber will be interrupted when scope closes + * return "done" + * }) + * ) + * + * await Effect.runPromise(program) // => "done" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkIn = _internal_effect_js__rspack_import_1/* .forkIn */.ar0; +/** + * Forks the fiber in a `Scope`, interrupting it when the scope is closed. + * + * **Example** (Forking into the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const backgroundTask = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* backgroundTask.pipe(Effect.forkScoped) + * + * // Fiber will be interrupted when scope closes + * return "scope completed" + * }) + * ) + * + * await Effect.runPromise(program) // => "scope completed" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkScoped = _internal_effect_js__rspack_import_1/* .forkScoped */.x6Z; +/** + * Forks the effect into a new fiber attached to the global scope. Because the + * new fiber is attached to the global scope, when the fiber executing the + * returned effect terminates, the forked fiber will continue running. + * + * **Example** (Forking a detached fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const daemonTask = Effect.succeed("daemon result") + * + * const program = Effect.gen(function*() { + * const fiber = yield* daemonTask.pipe(Effect.forkDetach) + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "daemon result" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkDetach = _internal_effect_js__rspack_import_1/* .forkDetach */.yxg; +/** + * Waits for all child fibers forked by this effect to complete before this + * effect completes. + * + * **When to use** + * + * Use to let an effect start child work concurrently while still delaying its + * own completion until that child work is done. + * + * **Gotchas** + * + * Child fibers that already exist before the wrapped effect starts are not + * awaited. + * + * @see {@link forkChild} for forking child fibers that are awaited by this operator + * @see {@link forkDetach} for forking fibers outside the child scope + * @see {@link forkIn} for forking into an explicit scope + * @see {@link forkScoped} for forking fibers tied to the current scope + * + * @category sequencing + * @since 2.0.0 + */ +const awaitAllChildren = _internal_effect_js__rspack_import_1/* .awaitAllChildren */.PCg; +/** + * Accesses the fiber currently executing the effect. + * + * **Example** (Accessing the current fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.fiber + * yield* Effect.sync(() => { output.push(typeof fiber.id) }) + * }) + * + * Effect.runSync(program) + * output // => ["number"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const fiber = _internal_effect_js__rspack_import_1/* .fiber */.pEE; +/** + * Accesses the current fiber id executing the effect. + * + * **Example** (Accessing the current fiber id) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.fiberId.pipe(Effect.map((id) => typeof id)) + * Effect.runSync(program) // => "number" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const fiberId = _internal_effect_js__rspack_import_1/* .fiberId */.ABT; +/** + * Runs an effect in the background, returning a fiber that can + * be observed or interrupted. + * + * **When to use** + * + * Use when you need to start an effect in the background and receive a fiber. + * + * **Example** (Running an effect in the background) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * // ┌─── Effect + * // ▼ + * const program = Effect.sync(() => { output.push("running...") }).pipe(Effect.as("done")) + * + * // ┌─── RuntimeFiber + * // ▼ + * const fiber = Effect.runFork(program) + * + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["running...", "done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runFork = _internal_effect_js__rspack_import_1/* .runFork */.MY7; +/** + * Runs an effect in the background with the provided services. + * + * **When to use** + * + * Use when an effect still requires services, you already have a `Context`, and + * you want a background fiber. + * + * **Example** (Running with services in the background) + * + * ```ts import.meta.vitest + * import { Context, Effect, Fiber } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => void + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => void output.push(message) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * logger.log("Hello from service!") + * return "done" + * }) + * + * const fiber = Effect.runForkWith(services)(program) + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["Hello from service!", "done"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runForkWith = _internal_effect_js__rspack_import_1/* .runForkWith */.eJC; +/** + * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor. + * + * **When to use** + * + * Use when embedding an effect into callback-style code with explicit services + * and a synchronous interruptor. + * + * **Details** + * + * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id. + * + * **Example** (Running with services and a callback) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => Effect.Effect + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => Effect.sync(() => { output.push(message) }) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * yield* logger.log("Started") + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallbackWith(services)(program, { + * onExit: (exit) => { + * void output.push(exit._tag) + * resolve() + * } + * }) + * }) + * output // => ["Started", "Success"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runCallbackWith = _internal_effect_js__rspack_import_1/* .runCallbackWith */.lSz; +/** + * Runs an effect asynchronously, registering `onExit` as a fiber observer and + * returning an interruptor. + * + * **Details** + * + * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor + * id. + * + * **Example** (Running with a callback) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("working") }) + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallback(program, { + * onExit: (exit) => { + * Effect.runSync( + * Exit.match(exit, { + * onFailure: () => Effect.sync(() => { output.push("failed") }), + * onSuccess: (value) => Effect.sync(() => { output.push(`success: ${value}`) }) + * }) + * ) + * resolve() + * } + * }) + * }) + * + * output // => ["working", "success: done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runCallback = _internal_effect_js__rspack_import_1/* .runCallback */.bPG; +/** + * 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. + * @category running + * @since 2.0.0 + */ +const runPromise = _internal_effect_js__rspack_import_1/* .runPromise */.pR5; +/** + * Executes an effect as a Promise with the provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that rejects on + * effect failure. + * + * **Example** (Running with services as a promise) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Config { + * apiUrl: string + * } + * + * const Config = Context.Service("Config") + * + * const context = Context.make(Config, { + * apiUrl: "https://api.example.com" + * }) + * + * const program = Effect.gen(function*() { + * const config = yield* Config + * return `Connecting to ${config.apiUrl}` + * }) + * + * await Effect.runPromiseWith(context)(program) // => "Connecting to https://api.example.com" + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseWith = _internal_effect_js__rspack_import_1/* .runPromiseWith */.v2Q; +/** + * Runs an effect and returns a `Promise` that resolves to an `Exit`, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use when you need to determine if an effect succeeded + * or failed, including any defects, and you want to work with a `Promise`. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * **Example** (Observing promise results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * // Execute a successful effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * // Execute a failing effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * @see {@link runPromise} for a version that rejects on failure. + * + * @category running + * @since 2.0.0 + */ +const runPromiseExit = _internal_effect_js__rspack_import_1/* .runPromiseExit */.NpQ; +/** + * Runs an effect and returns a Promise of Exit with provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that preserves + * success and failure as an `Exit`. + * + * **Example** (Running with services as an Exit promise) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * query: (sql: string) => string + * } + * + * const Database = Context.Service("Database") + * + * const services = Context.make(Database, { + * query: (sql) => `Result for: ${sql}` + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Database + * return db.query("SELECT * FROM users") + * }) + * + * const exit = await Effect.runPromiseExitWith(services)(program) + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } + * output // => ["Success: Result for: SELECT * FROM users"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseExitWith = _internal_effect_js__rspack_import_1/* .runPromiseExitWith */.jqV; +/** + * 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, is interrupted, or performs asynchronous work, + * `runSync` throws a `FiberFailure` instead of returning a value. 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. + * @category running + * @since 2.0.0 + */ +const runSync = _internal_effect_js__rspack_import_1/* .runSync */.HZF; +/** + * Executes an effect synchronously with provided services. + * + * **When to use** + * + * Use when you already have a `Context`, the effect is known to complete + * synchronously, and failures should throw. + * + * **Example** (Running synchronously with services) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface MathService { + * add: (a: number, b: number) => number + * } + * + * const MathService = Context.Service("MathService") + * + * const context = Context.make(MathService, { + * add: (a, b) => a + b + * }) + * + * const program = Effect.gen(function*() { + * const math = yield* MathService + * return math.add(2, 3) + * }) + * + * const result = Effect.runSyncWith(context)(program) + * result // => 5 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncWith = _internal_effect_js__rspack_import_1/* .runSyncWith */.lE; +/** + * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use to find out whether an effect succeeded or failed, + * including any defects, without dealing with asynchronous operations. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * If the effect contains asynchronous operations, `runSyncExit` will + * return an `Failure` with a `Die` cause, indicating that the effect cannot be + * resolved synchronously. + * + * **Example** (Observing synchronous results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * **Example** (Capturing async work as a Die cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))) + * const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some( + * (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect) + * ) + * + * isAsyncDie // => true + * ``` + * + * @see {@link runSync} for a version that throws on failure. + * + * @category running + * @since 2.0.0 + */ +const runSyncExit = _internal_effect_js__rspack_import_1/* .runSyncExit */.lKS; +/** + * Runs an effect synchronously with provided services, returning an Exit result safely. + * + * **When to use** + * + * Use when you already have a `Context` and need a synchronous `Exit` instead of + * throwing on failure. + * + * **Example** (Running synchronously with services as Exit) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * // Define a logger service + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * logger.log("Computing result...") + * return 42 + * }) + * + * // Prepare context + * const context = Context.make(Logger, { + * log: (msg) => void output.push(`[LOG] ${msg}`) + * }) + * + * const exit = Effect.runSyncExitWith(context)(program) + * + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } else { + * void output.push(`Failure: ${exit.cause}`) + * } + * output // => ["[LOG] Computing result...", "Success: 42"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncExitWith = _internal_effect_js__rspack_import_1/* .runSyncExitWith */.rfH; +/** + * 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. 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" + * ``` + * + * @category constructors + * @since 3.12.0 + */ +const fnUntraced = _internal_effect_js__rspack_import_1/* .fnUntraced */.D9k; +/** + * Creates a reusable traced function from an Effect body. + * + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, and you want + * tracing spans or stack-frame capture. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the + * generator body instead of allocating a fresh generator closure around the + * arguments on every call. Call `Effect.fn(body, ...)` for a generic + * stack-frame boundary without creating a span. Call + * `Effect.fn("operationName", options?)(body, ...)` when that boundary should + * have a readable operation name and the returned `Effect` should create a + * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata + * such as attributes, links, parent or root selection, kind, sampling, and log + * level. Additional arguments after the generator body act like `pipe` + * transforms: each transform receives the previous result and the original + * function arguments. When those transforms return an `Effect`, the returned + * effect includes stack-frame metadata and, for the named form, a tracing span. + * Generator bodies may declare a `this` parameter; pass `{ self }` before the + * body to bind `this` when the function is created. + * + * **Example** (Defining traced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(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.fn("formatLength")( + * 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** (Binding this) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class Counter { + * count = 0 + * + * increment = Effect.fn("Counter.increment")( + * { self: this }, + * function*(this: Counter, by: number) { + * this.count += by + * return yield* Effect.succeed(this.count) + * } + * ) + * } + * + * const counter = new Counter() + * + * // ┌─── Effect.Effect + * // ▼ + * const program = counter.increment(1) + * Effect.runSync(program) // => 1 + * ``` + * + * **Example** (Annotating a traced non-parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => 5 + * ``` + * + * **Example** (Annotating a traced parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("succeed")(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => "hello" + * ``` + * + * @category constructors + * @since 3.11.0 + */ +const fn = _internal_effect_js__rspack_import_1.fn; +// ======================================================================== +// Clock +// ======================================================================== +/** + * Retrieves the `Clock` service from the context and provides it to the + * specified effectful function. + * + * **Example** (Accessing the Clock service) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.clockWith((clock) => + * clock.currentTimeMillis.pipe( + * Effect.map(() => "Clock is available") + * ) + * ) + * + * Effect.runSync(program) // => "Clock is available" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const clockWith = _internal_effect_js__rspack_import_1/* .clockWith */.RKA; +// ======================================================================== +// Logging +// ======================================================================== +/** + * Creates a logger function that logs at the specified level. + * + * **Details** + * + * If no level is provided, the logger uses the fiber's current log level and + * extracts any `Cause` values from the message list. + * + * **Example** (Logging at a dynamic level) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const logWarn = Effect.logWithLevel("Warn") + * + * const program = Effect.gen(function*() { + * yield* logWarn("Cache miss") + * }) + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Warn: Cache miss"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWithLevel = _internal_effect_js__rspack_import_1/* .logWithLevel */.lIX; +/** + * Logs one or more messages using the default log level. + * + * **Example** (Logging at the default level) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = 2 + 2 + * yield* Effect.log("Result:", result) + * return result + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * void output.push(Effect.runSync(runnable)) + * output // => ["Info: Result: 4", 4] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const log = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel())); +/** + * Logs one or more messages at the FATAL level. + * + * **Example** (Logging fatal messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logFatal("Critical system failure") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * Effect.runSync(runnable) + * output // => ["Fatal: Critical system failure"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logFatal = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Fatal"))); +/** + * Logs one or more messages at the WARNING level. + * + * **Example** (Logging warnings) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logWarning("API rate limit approaching") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Warn: API rate limit approaching"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWarning = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Warn"))); +/** + * Logs one or more messages at the ERROR level. + * + * **Example** (Logging errors) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logError("Database connection failed") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Error: Database connection failed"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logError = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Error"))); +/** + * Logs one or more messages at the INFO level. + * + * **Example** (Logging information) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logInfo("Application starting up") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Info: Application starting up"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logInfo = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Info"))); +/** + * Logs one or more messages at the DEBUG level. + * + * **Example** (Logging debug messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logDebug("Debug mode enabled") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Debug: Debug mode enabled"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logDebug = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Debug"))); +/** + * Logs one or more messages at the TRACE level. + * + * **Example** (Logging trace messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logTrace("Entering function processData") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Trace"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Trace: Entering function processData"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logTrace = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Trace"))); +/** + * Adds a logger to the set of loggers which will output logs for this effect. + * + * **Example** (Adding a logger to an effect) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * // Create a custom logger that logs to the console + * const customLogger = Logger.make(({ message }) => + * void output.push(`[CUSTOM]: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * ) + * + * const program = Effect.gen(function*() { + * yield* Effect.log("This will go to both default and custom logger") + * return "completed" + * }) + * + * // Add the custom logger to the effect + * const programWithLogger = Effect.withLogger(program, customLogger) + * + * Effect.runSync(Effect.provide(programWithLogger, Logger.layer([]))) + * output // => ["[CUSTOM]: This will go to both default and custom logger"] + * ``` + * + * @category logging + * @since 4.0.0 + */ +const withLogger = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, logger) => internal.updateService(effect, internal.CurrentLoggers, loggers => new Set([...loggers, logger]))))); +/** + * Adds an annotation to each log line in this effect. + * + * **Example** (Adding log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.log("Starting operation") + * }) + * + * // Add annotations to all log messages + * const annotatedProgram = Effect.annotateLogs(program, { + * userId: "user123", + * operation: "data-processing" + * }) + * + * // Also supports single key-value annotations + * const singleAnnotated = Effect.annotateLogs(program, "requestId", "req-456") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * const run = (effect: Effect.Effect) => + * Effect.runSync(Effect.provide(effect, Logger.layer([logger]))) + * run(annotatedProgram) + * run(singleAnnotated) + * output // => ["Starting operation", "Starting operation"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const annotateLogs = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (effect, ...args) => internal.updateService(effect, CurrentLogAnnotations, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + InternalRecord.assignProperty(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})))); +/** + * Adds log annotations to the current scope. + * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * + * This differs from `annotateLogs`, which only annotates a specific effect. + * `annotateLogsScoped` updates annotations for the entire current `Scope` and + * restores the previous annotations when the scope closes. + * + * **Example** (Adding scoped log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.log("before") + * yield* Effect.annotateLogsScoped({ requestId: "req-123" }) + * yield* Effect.log("inside scope") + * }) + * ) + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["before", "inside scope"] + * ``` + * + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 + */ +const annotateLogsScoped = _internal_effect_js__rspack_import_1/* .annotateLogsScoped */.gsV; +/** + * Adds a span to each log line in this effect. + * + * **Example** (Adding a log span) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const databaseOperation = Effect.gen(function*() { + * yield* Effect.log("Connecting to database") + * yield* Effect.log("Executing query") + * yield* Effect.log("Processing results") + * return "data" + * }) + * + * const httpRequest = Effect.gen(function*() { + * yield* Effect.log("Making HTTP request") + * const data = yield* Effect.withLogSpan(databaseOperation, "db-operation") + * yield* Effect.log("Sending response") + * return data + * }) + * + * const program = Effect.withLogSpan(httpRequest, "http-handler") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * void output.push(Effect.runSync(Effect.provide(program, Logger.layer([logger])))) + * output // => ["Making HTTP request", "Connecting to database", "Executing query", "Processing results", "Sending response", "data"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const withLogSpan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, label) => internal.flatMap(internal.currentTimeMillis, now => internal.updateService(effect, CurrentLogSpans, spans => { + const span = [label, now]; + return [span, ...spans]; +}))))); +// ----------------------------------------------------------------------------- +// Metrics +// ----------------------------------------------------------------------------- +/** + * Updates the `Metric` every time the `Effect` is executed. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Exit` value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Incrementing a metric for each execution) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const counter = Metric.counter("effect_executions", { + * description: "Counts effect executions" + * }).pipe(Metric.withConstantInput(1)) + * + * const program = Effect.succeed("Hello").pipe( + * Effect.track(counter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(counter)).count // => 1 + * ``` + * + * **Example** (Mapping exits before updating a metric) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Metric } from "effect" + * + * // Track different exit types with custom mapping + * const exitTracker = Metric.frequency("exit_types", { + * description: "Tracks success/failure/defect counts" + * }) + * + * const mapExitToString = (exit: Exit.Exit) => { + * if (Exit.isSuccess(exit)) return "success" + * if (Exit.isFailure(exit)) return "failure" + * return "defect" + * } + * + * const effect = Effect.succeed("result").pipe( + * Effect.track(exitTracker, mapExitToString) + * ) + * Effect.runSync(effect) + * Effect.runSync(Metric.value(exitTracker)).occurrences.get("success") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const track = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => onExit(self, exit => { + const input = f === undefined ? exit : internalCall(() => f(exit)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` succeeds with + * a value. + * + * **Details** + * + * Also accepts an optional function which can be used to map the success value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting successful results) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const successCounter = Metric.counter("successes").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.succeed(42).pipe( + * Effect.trackSuccesses(successCounter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(successCounter)).count // => 1 + * ``` + * + * **Example** (Mapping successes before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track successful request sizes + * const requestSizeGauge = Metric.gauge("request_size_bytes") + * + * const program = Effect.succeed("Hello World!").pipe( + * Effect.trackSuccesses(requestSizeGauge, (value: string) => value.length) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(requestSizeGauge)).value // => 12 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackSuccesses = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tap(self, value => { + const input = f === undefined ? value : f(value); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **expected** error. + * + * **Details** + * + * Also accepts an optional function which can be used to map the error value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting expected failures) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const errorCounter = Metric.counter("errors").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.fail("Network timeout").pipe( + * Effect.trackErrors(errorCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorCounter)).count // => 1 + * ``` + * + * **Example** (Mapping errors before tracking) + * + * ```ts import.meta.vitest + * import { Data, Effect, Metric } from "effect" + * + * class ConnectionFailedError extends Data.TaggedError("ConnectionFailedError")<{}> {} + * + * // Track error types using frequency metric + * const errorTypeFrequency = Metric.frequency("error_types") + * + * const program = Effect.fail(new ConnectionFailedError()).pipe( + * Effect.trackErrors(errorTypeFrequency, (error: ConnectionFailedError) => error._tag) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorTypeFrequency)).occurrences.get("ConnectionFailedError") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackErrors = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapError(self, error => { + const input = f === undefined ? error : internalCall(() => f(error)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **unexpected** error (i.e. a defect). + * + * **Details** + * + * Also accepts an optional function which can be used to map the defect value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting defects) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const defectCounter = Metric.counter("defects").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.die("Critical system failure").pipe( + * Effect.trackDefects(defectCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectCounter)).count // => 1 + * ``` + * + * **Example** (Mapping defects before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track defect types using frequency metric + * const defectTypeFrequency = Metric.frequency("defect_types") + * + * const program = Effect.die(new Error("Null pointer exception")).pipe( + * Effect.trackDefects(defectTypeFrequency, (defect: unknown) => { + * if (defect instanceof Error) return defect.constructor.name + * return typeof defect + * }) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectTypeFrequency)).occurrences.get("Error") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDefects = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapDefect(self, defect => { + const input = f === undefined ? defect : internalCall(() => f(defect)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) + * that the wrapped `Effect` took to complete. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Duration` + * that the wrapped `Effect` took to complete into a valid `Input` for the + * `Metric`. + * + * **Example** (Recording execution duration) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const executionTimer = Metric.timer("execution_time") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(executionTimer) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(executionTimer)).count // => 1 + * ``` + * + * **Example** (Mapping duration before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track execution time in milliseconds using custom mapping + * const durationGauge = Metric.gauge("execution_millis") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(durationGauge, () => 1) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(durationGauge)).value // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDuration = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => clockWith(clock => { + const startTime = clock.monotonicTimeNanosUnsafe(); + return onExit(self, () => { + const endTime = clock.monotonicTimeNanosUnsafe(); + const duration = Duration.subtract(Duration.fromInputUnsafe(endTime), Duration.fromInputUnsafe(startTime)); + const input = f === undefined ? duration : internalCall(() => f(duration)); + return Metric.update(metric, input); + }); +})))); +// ----------------------------------------------------------------------------- +// Transactions +// ----------------------------------------------------------------------------- +/** + * Service that holds the current transaction state. + * + * **Details** + * + * It includes a journal that stores non-committed changes to `TxRef` values and + * a retry flag that records whether the transaction should be retried. + * + * **Example** (Building transactions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Transaction class for software transactional memory operations + * const txEffect = Effect.gen(function*() { + * const tx = yield* Effect.Transaction + * // Use transaction for coordinated state changes + * return "Transaction complete" + * }) + * + * const runnable = Effect.provideService(txEffect, Effect.Transaction, { + * retry: false, + * journal: new Map() + * }) + * Effect.runSync(runnable) // => "Transaction complete" + * ``` + * + * @category services + * @since 4.0.0 + */ +class Transaction extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Effect/Transaction"))) {} +/** + * Defines a transaction boundary. Transactions are "all or nothing" with respect to changes + * made to transactional values (i.e. TxRef) that occur within the transaction body. + * + * **Details** + * + * If called inside an active transaction, `tx` composes with the current transaction and reuses + * its journal and retry state instead of creating a nested boundary. + * + * Effect transactions are optimistic with retry. A transaction is retried when + * its body explicitly calls `Effect.txRetry` and any accessed transactional + * value changes, or when any accessed transactional value changes because a + * different transaction commits before the current one. + * + * The outermost `tx` call creates the transaction boundary and commits or rolls back the full + * composed transaction. + * + * **Example** (Running a transaction) + * + * ```ts import.meta.vitest + * import { Effect, TxRef } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ref1 = yield* TxRef.make(0) + * const ref2 = yield* TxRef.make(0) + * + * // Nested tx calls compose into the same transaction + * yield* Effect.tx(Effect.gen(function*() { + * yield* TxRef.set(ref1, 10) + * yield* Effect.tx(TxRef.set(ref2, 20)) + * const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2)) + * void output.push(`Transaction sum: ${sum}`) + * })) + * + * void output.push(`Final ref1: ${yield* TxRef.get(ref1)}`) + * void output.push(`Final ref2: ${yield* TxRef.get(ref2)}`) + * }) + * + * Effect.runSync(program) + * output // => ["Transaction sum: 30", "Final ref1: 10", "Final ref2: 20"] + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const tx = effect => withFiber(fiber => { + let state = Context.getOrUndefined(fiber.context, Transaction); + if (state) { + return effect; + } + // Create transaction state only at the outermost boundary + state = { + journal: new Map(), + retry: false + }; + let result; + return uninterruptibleMask(restore => flatMap(whileLoop({ + while: () => !result, + body: constant(restore(effect).pipe(provideService(Transaction, state), tapCause(() => { + if (!state.retry) return void_; + return restore(awaitPendingTransaction(state)); + }), exit)), + step(exit) { + if (state.retry || !isTransactionConsistent(state)) { + return clearTransaction(state); + } + if (Exit.isSuccess(exit)) { + commitTransaction(fiber, state); + } else { + clearTransaction(state); + } + result = exit; + } + }), () => result)); +}); +const isTransactionConsistent = state => { + for (const [ref, { + version + }] of state.journal) { + if (ref.version !== version) { + return false; + } + } + return true; +}; +const awaitPendingTransaction = state => suspend(() => { + const key = {}; + const refs = Array.from(state.journal.keys()); + const clearPending = () => { + for (const clear of refs) { + clear.pending.delete(key); + } + }; + return callback(resume => { + const onCall = () => { + clearPending(); + resume(void_); + }; + for (const ref of refs) { + ref.pending.set(key, onCall); + } + return sync(clearPending); + }); +}); +function commitTransaction(fiber, state) { + for (const [ref, { + value + }] of state.journal) { + if (value !== ref.value) { + ref.version = ref.version + 1; + ref.value = value; + } + for (const pending of ref.pending.values()) { + fiber.currentDispatcher.scheduleTask(pending, 0); + } + ref.pending.clear(); + } +} +function clearTransaction(state) { + state.retry = false; + state.journal.clear(); +} +/** + * Retries the current transaction by signaling that it must be retried. + * + * **Details** + * + * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. + * + * **Example** (Retrying transactions) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, TxRef } from "effect" + * + * const program = Effect.gen(function*() { + * const ref = yield* TxRef.make(0) + * const update = yield* Deferred.make() + * + * yield* Effect.forkChild( + * Deferred.await(update).pipe(Effect.andThen(Effect.tx(TxRef.set(ref, 1)))) + * ) + * + * return yield* Effect.tx(Effect.gen(function*() { + * const value = yield* TxRef.get(ref) + * if (value === 0) { + * yield* Deferred.succeed(update, undefined) + * return yield* Effect.txRetry + * } + * return value + * })) + * }) + * + * await Effect.runPromise(program) // => 1 + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const txRetry = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(Transaction, state => { + state.retry = true; + return interrupt; +}))); +/** + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const uppercase = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(null, input.toUpperCase())) + * + * const effectfulUppercase = Effect.effectify(uppercase) + * const program = effectfulUppercase("hello") + * + * await Effect.runPromise(program) // => "HELLO" + * ``` + * + * **Example** (Mapping callback errors to typed failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const fail = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(new Error("unavailable"))) + * + * const effectfulFail = Effect.effectify( + * fail, + * (error, args) => new Error(`Failed to process ${args[0]}: ${error.message}`) + * ) + * + * const program = Effect.flip(effectfulFail("hello")) + * + * const error = await Effect.runPromise(program) + * error.message // => "Failed to process hello: unavailable" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const effectify = (fn, onError, onSyncError) => (...args) => callback(resume => { + try { + fn(...args, (err, result) => { + if (err) { + resume(fail(onError ? onError(err, args) : err)); + } else { + resume(succeed(result)); + } + }); + } catch (err) { + resume(onSyncError ? fail(onSyncError(err, args)) : die(err)); + } +}); +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that an effect's success type extends a given type `A`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the success type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Effect.satisfiesSuccessType() + * + * // This works - Effect<42, never, never> extends Effect + * const validEffect = satisfiesNumber(Effect.succeed(42)) + * Effect.runSync(validEffect) // => 42 + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesNumber(Effect.succeed("string")) + * // ^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'number' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => effect => effect; +/** + * Ensures that an effect's error type extends a given type `E`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the error type) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ValidationError extends Data.TaggedError("ValidationError")<{}> {} + * + * // Define a constraint that the error type must be a ValidationError + * const satisfiesError = Effect.satisfiesErrorType() + * + * // This works - Effect extends the constrained type + * const validEffect = satisfiesError(Effect.fail(new ValidationError())) + * Effect.runSync(Effect.flip(validEffect))._tag // => "ValidationError" + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesError(Effect.fail("string error")) + * // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'ValidationError' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => effect => effect; +/** + * Ensures that an effect's requirements type extends a given type `R`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the services type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that requires a string as the requirements type + * const satisfiesStringServices = Effect.satisfiesServicesType() + * + * // This works - effect requires string + * const validEffect: Effect.Effect = Effect.succeed(42) + * const constrainedEffect = satisfiesStringServices(validEffect) + * + * // This would cause a TypeScript compilation error if uncommented: + * // const invalidEffect: Effect.Effect = Effect.succeed(42) + * // const constrainedInvalid = satisfiesStringServices(invalidEffect) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => effect => effect; +/** + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. + * + * **Details** + * + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. + * + * **Example** (Mapping already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the mapping is applied immediately + * const resolved = Effect.succeed(5) + * const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly + * + * // For pending effects, behaves like regular map + * const pending = Effect.delay(Effect.succeed(5), 0) + * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map + * + * await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapEager = _internal_effect_js__rspack_import_1/* .mapEager */.jkJ; +/** + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. + * + * **Example** (Mapping errors eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the error mapping is applied immediately + * const failed = Effect.fail("original error") + * const mapped = Effect.mapErrorEager(failed, (err: string) => `mapped: ${err}`) // Applied eagerly + * + * // For pending effects, behaves like regular mapError + * const pending = Effect.delay(Effect.fail("error"), 0) + * const mappedPending = Effect.mapErrorEager( + * pending, + * (err: string) => `mapped: ${err}` + * ) // Uses regular mapError + * + * void output.push(await Effect.runPromise(Effect.all([ + * Effect.flip(mapped), + * Effect.flip(mappedPending) + * ]))) + * output // => [['mapped: original error', 'mapped: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const mapErrorEager = _internal_effect_js__rspack_import_1/* .mapErrorEager */.Z9x; +/** + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. + * + * **Details** + * + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. + * + * **Example** (Mapping both channels eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved effects, the appropriate mapping is applied immediately + * const success = Effect.succeed(5) + * const mapped = Effect.mapBothEager(success, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onSuccess applied eagerly + * + * const failure = Effect.fail("error") + * const mappedError = Effect.mapBothEager(failure, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onFailure applied eagerly + * + * void output.push(Effect.runSync(mapped)) + * void output.push(Effect.runSync(Effect.flip(mappedError))) + * output // => [10, "Failed: error"] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapBothEager = _internal_effect_js__rspack_import_1/* .mapBothEager */.q7Y; +/** + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. + * + * **Details** + * + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. + * + * **Example** (Flat mapping eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the flatMap is applied immediately + * const resolved = Effect.succeed(5) + * const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly + * + * // For pending effects, behaves like regular flatMap + * const pending = Effect.delay(Effect.succeed(5), 0) + * const flatMappedPending = Effect.flatMapEager( + * pending, + * (n) => Effect.succeed(n * 2) + * ) // Uses regular flatMap + * + * await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapEager = _internal_effect_js__rspack_import_1/* .flatMapEager */.Ab9; +/** + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. + * + * **Example** (Catching failures eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the catch function is applied immediately + * const failed = Effect.fail("original error") + * const recovered = Effect.catchEager( + * failed, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Applied eagerly + * + * // For success effects, returns success as-is + * const success = Effect.succeed(42) + * const unchanged = Effect.catchEager( + * success, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Returns success as-is + * + * // For pending effects, behaves like regular catch + * const pending = Effect.delay(Effect.fail("error"), 0) + * const recoveredPending = Effect.catchEager( + * pending, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Uses regular catch + * + * void output.push(await Effect.runPromise(Effect.all([ + * recovered, + * unchanged, + * recoveredPending + * ]))) + * output // => [['recovered from: original error', 42, 'recovered from: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchEager = _internal_effect_js__rspack_import_1/* .catchEager */.UVN; +/** + * Creates untraced function effects with eager evaluation optimization. + * + * **Details** + * + * Executes generator functions eagerly when all yielded effects are synchronous, + * stopping at the first async effect and deferring to normal execution. + * + * **Example** (Defining eager untraced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const computation = Effect.fnUntracedEager(function*() { + * yield* Effect.succeed(1) + * yield* Effect.succeed(2) + * return "computed eagerly" + * }) + * + * const effect = computation() // Executed immediately if all effects are sync + * Effect.runSync(effect) // => "computed eagerly" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fnUntracedEager = _internal_effect_js__rspack_import_1/* .fnUntracedEager */.vCS; +//# sourceMappingURL=Effect.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + $mh: tryPromise, + ATB: failCause, + Ab9: flatMapEager, + Bqz: flatten, + D9k: fnUntraced, + DYE: suspend, + E2r: callback, + F_Q: die, + GaK: interrupt, + JkU: gen, + KT6: raceFirst, + MY7: runFork, + Mim: tap, + NLW: asVoid, + NS5: exit, + NpQ: runPromiseExit, + OH5: sync, + PfK: provideService, + PyW: succeed, + Q56: acquireRelease, + S5A: onError, + SvU: try_, + TjK: map, + Tyx: catchCause, + Vdx: raceAll, + ZmZ: never, + _OA: context, + ar0: forkIn, + as: as, + cfM: onExit, + dsN: abortSignal, + eJC: runForkWith, + fJG: fail, + hgn: andThen, + i4r: forever, + iMI: whileLoop, + ivC: promise, + khu: matchCauseEffect, + m9E: yieldNow, + qIB: flatMap, + rIH: void_, + sFT: tapError, + yy4: sleep, + zhn: forkChild +}); + + +}, +"./node_modules/effect/dist/Effectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.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 + * + * @category prototypes + * @since 4.0.0 + */ +const Prototype = options => (0,_internal_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: options.label, + [_internal_core_js__rspack_import_0/* .evaluate */._3]: options.evaluate +}); +const Base = /*#__PURE__*/(/* unused pure expression or super */ null && ((() => { + const Base = function () {}; + Base.prototype = /*#__PURE__*/Prototype({ + label: "Effectable", + evaluate(_) { + return this; + } + }); + return Base; +})())); +/** + * Provides an abstract class that can be extended to create an `Effect`. + * + * **When to use** + * + * Use as an abstract base class to define custom classes whose instances behave + * as `Effect` values. + * + * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class + * @category constructors + * @since 2.0.0 + */ +class Class extends (/* unused pure expression or super */ null && (Base)) {} +//# sourceMappingURL=Effectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + b: Prototype +}); + + +}, +"./node_modules/effect/dist/Encoding.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text. + * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes. + * Encode functions return strings directly, while decode functions return + * `Result.Result` so invalid input is reported as an `EncodingError` instead of + * being thrown. + * + * @since 4.0.0 + */ + + + +// ------------------------------------------------------------------------------------- +// EncodingError +// ------------------------------------------------------------------------------------- +/** + * Type identifier stored on `EncodingError` values and used by + * `isEncodingError`. + * + * **When to use** + * + * Use when implementing low-level `EncodingError`-compatible values that need + * to carry the runtime marker. + * + * **Details** + * + * This marker is part of the runtime representation of `EncodingError`. Prefer + * `isEncodingError` when narrowing unknown values. + * + * @see {@link isEncodingError} for the public guard that checks this marker + * + * @category type IDs + * @since 4.0.0 + */ +const EncodingErrorTypeId = "~effect/encoding/EncodingError"; +/** + * Error returned when an encoding or decoding operation cannot process its + * input. + * + * **When to use** + * + * Use when you need to handle or inspect failures from encoding or decoding + * operations. + * + * **Details** + * + * The error records whether the failure happened during encoding or decoding, + * which encoding module reported it, the original input, and a human-readable + * message. + * + * @see {@link isEncodingError} for checking whether a value is an EncodingError + * @category errors + * @since 4.0.0 + */ +class EncodingError extends /*#__PURE__*/(/* unused pure expression or super */ null && (Data.TaggedError("EncodingError"))) { + /** + * Marks this value as an encoding or decoding error for runtime guards. + * + * **When to use** + * + * Use to identify `EncodingError` instances through `isEncodingError`. + * + * @since 4.0.0 + */ + [EncodingErrorTypeId] = EncodingErrorTypeId; +} +/** + * Checks whether a value is an `EncodingError`. + * + * **When to use** + * + * Use to narrow an unknown value before handling it as an `EncodingError` from + * encoding or decoding code. + * + * **Details** + * + * Returns `true` when the value carries the `EncodingErrorTypeId` marker and + * narrows the value to `EncodingError`. + * + * @see {@link EncodingError} for the structured error produced by failed + * encoding and decoding operations + * + * @category guards + * @since 4.0.0 + */ +const isEncodingError = u => hasProperty(u, EncodingErrorTypeId); +// ------------------------------------------------------------------------------------- +// Base64 +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (RFC4648) `string`. + * + * **When to use** + * + * Use to encode text or bytes as a standard padded Base64 string for storage or + * transport. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64 encoding. + * `Uint8Array` inputs are encoded directly. The output uses the standard + * RFC4648 alphabet with `=` padding. + * + * **Example** (Encoding Base64 strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string + * Encoding.encodeBase64("hello") // => "aGVsbG8=" + * + * // Encode binary data + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeBase64(bytes) // => "SGVsbG8=" + * ``` + * + * @see {@link decodeBase64} for decoding standard Base64 to bytes + * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text + * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64 = input => typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input); +/** + * Decodes a base64 (RFC4648) string into bytes safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into bytes without throwing on + * invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64 = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 !== 0) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Length must be a multiple of 4, but is ${length}` + })); + } + const index = stripped.indexOf("="); + if (index !== -1 && (index < length - 2 || index === length - 2 && stripped[length - 1] !== "=")) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Found a '=' character, but it is not at the end` + })); + } + try { + const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0; + const result = new Uint8Array(3 * (length / 4) - missingOctets); + for (let i = 0, j = 0; i < length; i += 4, j += 3) { + const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | getBase64Code(stripped.charCodeAt(i + 3)); + result[j] = buffer >> 16; + result[j + 1] = buffer >> 8 & 0xff; + result[j + 2] = buffer & 0xff; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a base64 (RFC4648) string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64String("aGVsbG8=") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64String = str => Result.map(decodeBase64(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Base64Url +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (URL) `string`. + * + * **When to use** + * + * Use to encode text or bytes as an unpadded Base64Url string for contexts that + * require the URL-safe alphabet. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64Url encoding. + * `Uint8Array` inputs are encoded directly. The output removes `=` padding and + * replaces `+` with `-` and `/` with `_`. + * + * **Example** (Encoding URL-safe Base64) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // URL-safe base64 encoding (uses - and _ instead of + and /) + * Encoding.encodeBase64Url("hello?") // => "aGVsbG8_" + * + * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63]) + * Encoding.encodeBase64Url(bytes) // => "SGVsbG8_" + * ``` + * + * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes + * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text + * @see {@link encodeBase64} for standard padded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64Url = input => typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input); +/** + * Decodes a URL-safe base64 string into bytes safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into bytes without throwing + * on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. Both padded and unpadded URL-safe base64 forms are accepted when + * otherwise valid. + * + * **Example** (Decoding URL-safe Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64Url("SGVsbG8_") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64Url = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 === 1) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: `Length should be a multiple of 4, but is ${length}` + })); + } + if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: "Invalid input" + })); + } + // Some variants allow or require omitting the padding '=' signs + let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped; + sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/"); + return decodeBase64(sanitized); +}; +/** + * Decodes a URL-safe base64 string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. + * + * **Example** (Decoding URL-safe Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64UrlString("aGVsbG8_") // => Result.succeed("hello?") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64UrlString = str => Result.map(decodeBase64Url(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Hex +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a hex `string`. + * + * **When to use** + * + * Use to encode text or bytes as lowercase hexadecimal text. + * + * **Example** (Encoding hex strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string to hex + * Encoding.encodeHex("hello") // => "68656c6c6f" + * + * // Encode binary data to hex + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeHex(bytes) // => "48656c6c6f" + * ``` + * + * @category encoding + * @since 2.0.0 + */ +const encodeHex = input => typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input); +/** + * Generates a random lowercase hexadecimal string, optimized for lengths that + * are multiples of 8. + * + * `length` is not validated. The function generates `length >>> 3` random + * 8-character words, so non-negative lengths below `2 ** 32` are rounded down + * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit + * coercion rules. + * + * This function uses `Math.random()` and is not cryptographically secure. For + * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes` + * method and encode the result with {@link encodeHex}. + * + * @category encoding + * @since 4.0.0 + */ +const randomHex = length => { + let result = ""; + for (let i = length >>> 3; i > 0; i--) { + const word = Math.random() * 0x100000000 >>> 0; + result += byteToHex[word >>> 24] + byteToHex[word >>> 16 & 0xff] + byteToHex[word >>> 8 & 0xff] + byteToHex[word & 0xff]; + } + return result; +}; +/** + * Decodes a hexadecimal string into bytes safely. + * + * **When to use** + * + * Use to decode hexadecimal text into bytes without throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input has an odd length or + * contains invalid hex characters. + * + * **Example** (Decoding hex bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHex("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHex = str => { + const bytes = new TextEncoder().encode(str); + if (bytes.length % 2 !== 0) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: `Length must be a multiple of 2, but is ${bytes.length}` + })); + } + try { + const length = bytes.length / 2; + const result = new Uint8Array(length); + for (let i = 0; i < length; i++) { + const a = fromHexChar(bytes[i * 2]); + const b = fromHexChar(bytes[i * 2 + 1]); + result[i] = a << 4 | b; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a hexadecimal string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode hexadecimal text into UTF-8 text without throwing on invalid + * input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid hex. + * + * **Example** (Decoding hex strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHexString("68656c6c6f") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHexString = str => Result.map(decodeHex(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// internals +// ------------------------------------------------------------------------------------- +const encoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextEncoder())); +const decoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextDecoder())); +const stripCrlf = str => str.replace(/[\n\r]/g, ""); +// Base64 internals +const base64EncodeUint8Array = bytes => { + const length = bytes.length; + let result = ""; + let i; + for (i = 2; i < length; i += 3) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2 | bytes[i] >> 6]; + result += base64abc[bytes[i] & 0x3f]; + } + if (i === length + 1) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4]; + result += "=="; + } + if (i === length) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2]; + result += "="; + } + return result; +}; +function getBase64Code(charCode) { + if (charCode >= base64codes.length) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + const code = base64codes[charCode]; + if (code === 255) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + return code; +} +const base64abc = (/* unused pure expression or super */ null && (["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"])); +const base64codes = (/* unused pure expression or super */ null && ([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51])); +// Base64Url internals +const base64UrlEncodeUint8Array = data => base64EncodeUint8Array(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +// Hex internals +const byteToHex = []; +for (let i = 0; i < 256; i++) { + byteToHex.push(i.toString(16).padStart(2, "0")); +} +const hexEncodeUint8Array = bytes => { + let result = ""; + for (let i = 0; i < bytes.length; i++) { + result += byteToHex[bytes[i]]; + } + return result; +}; +const fromHexChar = byte => { + if (48 <= byte && byte <= 57) { + return byte - 48; + } + if (97 <= byte && byte <= 102) { + return byte - 97 + 10; + } + if (65 <= byte && byte <= 70) { + return byte - 65 + 10; + } + throw new TypeError("Invalid input"); +}; +//# sourceMappingURL=Encoding.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + nw: randomHex +}); + + +}, +"./node_modules/effect/dist/Equal.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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; + } + // Special case for NaN: NaN should be considered equal to NaN + if (selfType === "number" && self !== self && that !== that) { + return true; + } + if (selfType !== "object" && selfType !== "function") { + return false; + } + if (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self) || _internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(that)) { + return false; + } + // For objects and functions, use cached comparison + return withCache(self, that, compareObjects); +} +/** Helper to run comparison with proper visited tracking */ +function withVisitedTracking(self, that, fn) { + const hasLeft = visitedLeft.has(self); + const hasRight = visitedRight.has(that); + // Check for circular references before adding + if (hasLeft && hasRight) { + return true; // Both are circular at the same level + } + if (hasLeft || hasRight) { + return false; // Only one is circular + } + visitedLeft.add(self); + visitedRight.add(that); + const result = fn(); + visitedLeft.delete(self); + visitedRight.delete(that); + return result; +} +const visitedLeft = /*#__PURE__*/new WeakSet(); +const visitedRight = /*#__PURE__*/new WeakSet(); +/** Helper to perform cached object comparison */ +function compareObjects(self, that) { + if (_Hash_js__rspack_import_1/* .hash */.tW(self) !== _Hash_js__rspack_import_1/* .hash */.tW(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) { + if (!(that instanceof RegExp)) return false; + return self.toString() === that.toString(); + } + const selfIsEqual = isEqual(self); + const thatIsEqual = isEqual(that); + if (selfIsEqual !== thatIsEqual) return false; + const bothEquals = selfIsEqual && thatIsEqual; + if (typeof self === "function" && !bothEquals) { + return false; + } + return withVisitedTracking(self, that, () => { + 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 (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) { + return false; + } + if (selfIsDataView) { + const thatDataView = that; + return compareTypedArrays(new Uint8Array(self.buffer, self.byteOffset, self.byteLength), new Uint8Array(thatDataView.buffer, thatDataView.byteOffset, thatDataView.byteLength)); + } + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) { + return false; + } + return compareMaps(self, that); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) { + return false; + } + return compareSets(self, that); + } + return compareRecords(self, that); + }); +} +function withCache(self, that, f) { + // Check cache first + let selfMap = equalityCache.get(self); + if (!selfMap) { + selfMap = new WeakMap(); + equalityCache.set(self, selfMap); + } else if (selfMap.has(that)) { + return selfMap.get(that); + } + // Perform the comparison + const result = f(self, that); + // Cache the result bidirectionally + selfMap.set(that, result); + let thatMap = equalityCache.get(that); + if (!thatMap) { + thatMap = new WeakMap(); + equalityCache.set(that, thatMap); + } + thatMap.set(self, result); + return result; +} +const equalityCache = /*#__PURE__*/new WeakMap(); +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 = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(self); + const thatKeys = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(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; +} +/** @internal */ +function makeCompareMap(keyEquivalence, valueEquivalence) { + return function compareMaps(self, that) { + const thatEntries = Array.from(that); + for (const [selfKey, selfValue] of self) { + let found = false; + for (let i = 0; i < thatEntries.length; i++) { + const [thatKey, thatValue] = thatEntries[i]; + if (keyEquivalence(selfKey, thatKey) && valueEquivalence(selfValue, thatValue)) { + thatEntries[i] = thatEntries[thatEntries.length - 1]; + thatEntries.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareMaps = /*#__PURE__*/makeCompareMap(compareBoth, compareBoth); +/** @internal */ +function makeCompareSet(equivalence) { + return function compareSets(self, that) { + const thatValues = Array.from(that); + for (const selfValue of self) { + let found = false; + for (let i = 0; i < thatValues.length; i++) { + const thatValue = thatValues[i]; + if (equivalence(selfValue, thatValue)) { + thatValues[i] = thatValues[thatValues.length - 1]; + thatValues.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareSets = /*#__PURE__*/makeCompareSet(compareBoth); +/** + * 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 property keyed by + * {@link symbol}. + * - 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 + * @category guards + * @since 2.0.0 + */ +const isEqual = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Wraps {@link equals} as an `Equivalence`. + * + * **When to use** + * + * Use when you want to pass `Equal.equals` to APIs that require an + * `Equivalence`. + * + * **Details** + * + * - Returns a function `(a: A, b: A) => boolean` that delegates to + * {@link equals}. + * - Pure; allocates a thin wrapper on each call. + * + * **Example** (Deduplicating with Equal semantics) + * + * ```ts import.meta.vitest + * import { Array, Equal } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 1], Equal.asEquivalence()) // => [1, 2, 3] + * ``` + * + * @see {@link equals} — the underlying comparison function + * @category instances + * @since 4.0.0 + */ +const asEquivalence = () => equals; +/** + * Creates a proxy that uses reference equality instead of structural equality. + * + * **When to use** + * + * Use when you need to compare a plain object or array by identity without + * mutating the original value. + * + * **Details** + * + * - Returns a `Proxy` wrapping `obj`. The proxy reads through to the + * original, so property access is unchanged. + * - The proxy is registered in an internal WeakSet; {@link equals} returns + * `false` for any pair where at least one operand is in that set (unless + * they are the same reference). + * - Each call creates a **new** proxy, so `byReference(x) !== byReference(x)`. + * - Does **not** mutate the original object (unlike {@link byReferenceUnsafe}). + * + * **Example** (Opting out of structural equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const a = { x: 1 } + * const b = { x: 1 } + * + * Equal.equals(a, b) // => true + * + * const aRef = Equal.byReference(a) + * Equal.equals(aRef, b) // => false + * Equal.equals(aRef, aRef) // => true + * aRef.x // => 1 + * ``` + * + * @see {@link byReferenceUnsafe} — same effect without a proxy (mutates the + * original) + * @see {@link equals} — the comparison function affected by this opt-out + * @category equality + * @since 4.0.0 + */ +const byReference = obj => byReferenceUnsafe(new Proxy(obj, {})); +/** + * Marks an object permanently to use reference equality, without creating a proxy. + * + * **When to use** + * + * Use when you need reference equality without proxy allocation and accept + * permanently marking the original object for reference-only equality. + * + * **Details** + * + * - Adds `obj` to an internal WeakSet. From that point on, {@link equals} + * treats it as reference-only. + * - Returns the **same** object (not a copy or proxy), so + * `byReferenceUnsafe(x) === x`. + * - Does **not** affect the object's prototype, properties, or behavior + * beyond equality checks. + * + * **Gotchas** + * + * The marking is irreversible for the lifetime of the object. + * + * **Example** (Marking an object for reference equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const obj1 = { a: 1, b: 2 } + * const obj2 = { a: 1, b: 2 } + * + * const marked = Equal.byReferenceUnsafe(obj1) + * + * Equal.equals(obj1, obj2) // => false + * Equal.equals(obj1, obj1) // => true + * marked === obj1 // => true + * ``` + * + * @see {@link byReference} — safer alternative that creates a proxy + * @see {@link equals} — the comparison function affected by this opt-out + * @category unsafe + * @since 4.0.0 + */ +const byReferenceUnsafe = obj => { + _internal_equal_js__rspack_import_0/* .byReferenceInstances.add */.J.add(obj); + return obj; +}; +//# sourceMappingURL=Equal.js.map +__webpack_require__.d(__webpack_exports__, { + aI: () => (equals) +}, { + HR: symbol, + Xq: byReferenceUnsafe, + jI: asEquivalence +}); + + +}, +"./node_modules/effect/dist/Equivalence.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Defines reusable equality functions for values of the same type. + * + * An `Equivalence` returns `true` when two `A` values should be treated as + * the same for a particular purpose. This module includes strict equality + * instances for primitive types, constructors for custom comparisons, and + * helpers for tuples, arrays, structs, records, dates, and values compared + * through a derived field. + * + * @since 2.0.0 + */ + + +/** + * Creates a custom equivalence relation with an optimized reference equality check. + * + * **When to use** + * + * Use when you need an equality rule that the built-in instances and input + * mapping helpers cannot express, and you can provide a law-abiding comparison. + * + * **Details** + * + * The returned equivalence first checks reference equality (`===`) for + * performance. If the values are not the same reference, it falls back to the + * provided equivalence function, which must satisfy reflexive, symmetric, and + * transitive properties. + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.make((a, b) => + * a.toLowerCase() === b.toLowerCase() + * ) + * + * caseInsensitive("Hello", "HELLO") // => true + * caseInsensitive("foo", "bar") // => false + * + * // Same reference optimization + * const str = "test" + * caseInsensitive(str, str) // => true + * ``` + * + * **Example** (Comparing numbers with tolerance) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const tolerance = Equivalence.make((a, b) => Math.abs(a - b) < 0.0001) + * + * tolerance(1.0, 1.001) // => false + * tolerance(1.0, 1.00001) // => true + * ``` + * + * @see {@link strictEqual} + * @see {@link mapInput} + * @category constructors + * @since 2.0.0 + */ +const make = isEquivalent => (self, that) => self === that || isEquivalent(self, that); +const isStrictEquivalent = (x, y) => x === y; +/** + * Creates an equivalence relation that uses strict equality (`===`) to compare values. + * + * **When to use** + * + * Use when you need strict equality (`===`) as the comparison. + * + * **Details** + * + * Uses JavaScript's strict equality operator (`===`). Primitives compare by + * value. Objects compare by reference, so only the same object instance is + * equivalent. Use this as a building block for more complex equivalences via + * `mapInput` or `combine`. + * + * **Gotchas** + * + * `NaN !== NaN`, so `NaN` values are never considered equivalent. + * + * **Example** (Comparing primitive types) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const strictEq = Equivalence.strictEqual() + * + * strictEq(1, 1) // => true + * strictEq(1, 2) // => false + * strictEq(NaN, NaN) // => false + * ``` + * + * **Example** (Comparing objects by reference) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const obj = { value: 42 } + * const strictObjEq = Equivalence.strictEqual() + * + * strictObjEq(obj, obj) // => true + * strictObjEq(obj, { value: 42 }) // => false + * ``` + * + * @see {@link make} + * @see `Equal` for structural equality + * @category constructors + * @since 4.0.0 + */ +const strictEqual = () => isStrictEquivalent; +/** + * Equivalence instance for strings using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply case-sensitive string equality. + * + * **Example** (Comparing strings) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.String("hello", "hello") // => true + * Equivalence.String("hello", "world") // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const String = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for numbers. + * + * **When to use** + * + * Use when you need numeric equality that treats NaN as equal to itself. + * + * **Example** (Comparing numbers) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Number(1, 1) // => true + * Equivalence.Number(1, 2) // => false + * Equivalence.Number(NaN, NaN) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)))); +/** + * Equivalence instance for booleans using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply boolean equality. + * + * **Example** (Comparing booleans) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Boolean(true, true) // => true + * Equivalence.Boolean(true, false) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Boolean = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for bigints using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply bigint equality. + * + * **Example** (Comparing bigints) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.BigInt(1n, 1n) // => true + * Equivalence.BigInt(1n, 2n) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const BigInt = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Combines two equivalence relations using logical AND. + * + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** + * + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining name and age equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * } + * + * const nameEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.name + * ) + * + * const ageEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.age + * ) + * + * const personEquivalence = Equivalence.combine(nameEquivalence, ageEquivalence) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Alice", age: 30 } + * const person3 = { name: "Alice", age: 31 } + * + * personEquivalence(person1, person2) // => true + * personEquivalence(person1, person3) // => false + * ``` + * + * @see {@link combineAll} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((x, y) => self(x, y) && that(x, y))))); +/** + * Combines multiple equivalence relations into a single equivalence using logical AND. + * + * **When to use** + * + * Use when you need to combine many `Equivalence` instances from an iterable. + * + * **Details** + * + * Returns `true` only if all equivalences in the collection return `true`. The + * comparison stops at the first equivalence that returns `false`. Empty + * collections return an equivalence that always returns `true`. The result is + * also an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining multiple field equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Point3D { + * x: number + * y: number + * z: number + * } + * + * const xEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.x + * ) + * const yEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.y + * ) + * const zEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.z + * ) + * + * const point3DEq = Equivalence.combineAll([xEq, yEq, zEq]) + * + * const point1 = { x: 1, y: 2, z: 3 } + * const point2 = { x: 1, y: 2, z: 3 } + * const point3 = { x: 1, y: 2, z: 4 } + * + * point3DEq(point1, point2) // => true + * point3DEq(point1, point3) // => false + * ``` + * + * **Example** (Handling empty collections) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * // Empty collection always returns true + * const alwaysEq = Equivalence.combineAll([]) + * alwaysEq("anything", "else") // => true + * ``` + * + * @see {@link combine} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combineAll = collection => make((x, y) => { + for (const equivalence of collection) { + if (!equivalence(x, y)) { + return false; + } + } + return true; +}); +/** + * Transforms an equivalence relation by mapping the input values before comparison. + * + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** + * + * - Applies the transformation function to both values before comparing + * - The transformation function should be pure and have no side effects + * - The resulting equivalence compares the transformed values using the provided equivalence + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings + * + * **Example** (Deriving equivalence from an object property) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface User { + * id: number + * name: string + * email: string + * } + * + * // Create equivalence based on user ID only + * const userByIdEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (user: User) => user.id + * ) + * + * const user1 = { id: 1, name: "Alice", email: "alice@example.com" } + * const user2 = { id: 1, name: "Alice Smith", email: "alice.smith@example.com" } + * const user3 = { id: 2, name: "Bob", email: "bob@example.com" } + * + * userByIdEq(user1, user2) // => true + * userByIdEq(user1, user3) // => false + * ``` + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitiveEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * caseInsensitiveEq("Hello", "HELLO") // => true + * caseInsensitiveEq("Hello", "World") // => false + * ``` + * + * @see {@link combine} + * @see {@link Struct} + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => make((x, y) => self(f(x), f(y)))))); +/** + * Creates an equivalence for tuples with heterogeneous element types. + * + * **When to use** + * + * Use when you need an `Equivalence` for fixed-length tuples with per-position + * equivalences. + * + * **Details** + * + * Tuples must have the same length; different lengths are never equivalent. + * Each equivalence is applied to the corresponding element position. The result + * returns `true` only if all elements are equivalent according to their + * respective equivalences, and it also satisfies reflexive, symmetric, and + * transitive properties. + * + * **Example** (Comparing homogeneous tuples) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringTupleEq = Equivalence.Tuple([ + * Equivalence.strictEqual(), + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ]) + * + * const tuple1 = ["hello", "world", "test"] as const + * const tuple2 = ["hello", "world", "test"] as const + * const tuple3 = ["hello", "world", "different"] as const + * + * stringTupleEq(tuple1, tuple2) // => true + * stringTupleEq(tuple1, tuple3) // => false + * ``` + * + * **Example** (Comparing tuples with custom equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const customTupleEq = Equivalence.Tuple([ + * caseInsensitive, + * caseInsensitive, + * caseInsensitive + * ]) + * + * customTupleEq(["Hello", "World", "Test"], ["HELLO", "WORLD", "TEST"]) // => true + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + if (self.length !== that.length) { + return false; + } + for (let i = 0; i < self.length; i++) { + if (!elements[i](self[i], that[i])) { + return false; + } + } + return true; + }); +} +/** + * @since 4.0.0 + */ +function Array_(item) { + return make((self, that) => { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) { + if (!item(self[i], that[i])) return false; + } + return true; + }); +} + +/** + * Creates an equivalence for objects by comparing their properties using provided equivalences. + * + * **When to use** + * + * Use when you need an `Equivalence` for objects with known, fixed property + * names. + * + * **Details** + * + * Compares only the properties specified in the struct definition; other + * properties are ignored. String and symbol keys are supported via + * `Reflect.ownKeys`. The result returns `true` only if all specified properties + * are equivalent according to their equivalences, and it also satisfies + * reflexive, symmetric, and transitive properties. + * + * **Example** (Comparing structs with different equivalences per field) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * email: string + * } + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const personEq = Equivalence.Struct({ + * name: caseInsensitive, + * age: Equivalence.strictEqual(), + * email: caseInsensitive + * }) + * + * const person1 = { name: "Alice", age: 30, email: "alice@example.com" } + * const person2 = { name: "ALICE", age: 30, email: "ALICE@EXAMPLE.COM" } + * const person3 = { name: "Alice", age: 31, email: "alice@example.com" } + * + * personEq(person1, person2) // => true + * personEq(person1, person3) // => false + * ``` + * + * **Example** (Comparing specific fields) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const nameAgeEq = Equivalence.Struct({ + * name: Equivalence.strictEqual(), + * age: Equivalence.strictEqual() + * }) + * + * // Only compares name and age, ignores other properties + * const obj1 = { name: "Alice", age: 30, extra: "ignored" } + * const obj2 = { name: "Alice", age: 30, extra: "different" } + * nameAgeEq(obj1, obj2) // => true + * ``` + * + * @see {@link Record} + * @see {@link mapInput} + * @see {@link combine} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Reflect.ownKeys(fields); + return make((self, that) => { + for (const key of keys) { + if (!fields[key](self[key], that[key])) return false; + } + return true; + }); +} +/** + * Creates an equivalence for objects by comparing all properties using the same equivalence. + * + * **When to use** + * + * Use when you need to compare records with the same equivalence for every + * property value. + * + * **Details** + * + * - Compares all properties present in both objects + * - Requires both objects to have the same set of keys; different keys result in `false` + * - All property values must be equivalent according to the provided equivalence + * - Supports both string and symbol keys via `Reflect.ownKeys` + * - Empty objects are considered equivalent + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * + * **Example** (Defining records with string values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const record1 = { a: "hello", b: "world" } + * const record2 = { a: "hello", b: "world" } + * const record3 = { a: "hello", b: "different" } + * const record4 = { a: "hello" } // missing key 'b' + * + * stringRecordEq(record1, record2) // => true + * stringRecordEq(record1, record3) // => false + * stringRecordEq(record1, record4) // => false + * ``` + * + * **Example** (Defining records with number values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const numberRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const scores1 = { alice: 100, bob: 85 } + * const scores2 = { alice: 100, bob: 85 } + * const scores3 = { alice: 100, bob: 90 } + * + * numberRecordEq(scores1, scores2) // => true + * numberRecordEq(scores1, scores3) // => false + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Record(value) { + return make((self, that) => { + const selfKeys = Reflect.ownKeys(self); + const thatKeys = Reflect.ownKeys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (const key of selfKeys) { + if (!Object.hasOwn(that, key) || !value(self[key], that[key])) { + return false; + } + } + return true; + }); +} +/** + * Creates a `Reducer` for combining `Equivalence` instances, useful for aggregating equivalences in collections. + * + * **When to use** + * + * Use when you need a reducer that combines equivalences. + * + * **Details** + * + * Returns a reducer that combines equivalences using `combine`. The identity + * element for empty collections is an equivalence that always returns `true`. + * The reducer uses `combineAll` for collections of equivalences and can be used + * with fold operations. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const reducer = Equivalence.makeReducer() + * const equivalences = [ + * Equivalence.strictEqual(), + * Equivalence.make((a, b) => Math.abs(a - b) < 1) + * ] + * + * const combined = reducer.combineAll(equivalences) + * // Combined equivalence requires both conditions to be true + * combined(1, 1) // => true + * combined(1, 1.5) // => false + * ``` + * + * @see {@link combine} Combine two equivalences + * @see {@link combineAll} Combine multiple equivalences + * @see {@link Reducer} Reducer type for collection operations + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => true, combineAll); +} +/** + * Equivalence instance for `Date` objects that compares their `getTime()` values using `Equivalence.Number`. + * + * **When to use** + * + * Use when you need an `Equivalence` for JavaScript date objects by their + * millisecond timestamp. + * + * **Details** + * + * Different `Date` instances that represent the same millisecond timestamp are equivalent. Because `Equivalence.Number` + * treats `NaN` as equal to `NaN`, two invalid `Date` values are also considered equivalent. + * + * **Example** (Comparing Date values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date("2020-01-01T00:00:00.000Z") + * const d2 = new Date("2020-01-01T00:00:00.000Z") + * const d3 = new Date("2021-01-01T00:00:00.000Z") + * const invalidDate1 = new Date("foo") + * const invalidDate2 = new Date("bar") + * + * Equivalence.Date(d1, d2) // => true + * Equivalence.Date(d1, d3) // => false + * Equivalence.Date(invalidDate1, invalidDate2) // => true + * Equivalence.Date(invalidDate1, d1) // => false + * ``` + * + * **Example** (Comparing reference and value equality) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date(0) + * const d2 = new Date(0) + * + * d1 === d2 // => false + * Equivalence.Date(d1, d2) // => true + * ``` + * + * @see {@link Number} for the numeric equivalence applied to each `Date#getTime()` result + * @see {@link mapInput} for deriving an equivalence by mapping inputs before comparison + * @see {@link strictEqual} for reference equality when two values must be the same object + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, d => d.getTime()))); +//# sourceMappingURL=Equivalence.js.map +__webpack_require__.d(__webpack_exports__, { + O3: () => (Array_) +}, { + L8: make +}); + + +}, +"./node_modules/effect/dist/ExecutionPlan.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); + + + + + + +/** + * Runtime type identifier attached to `ExecutionPlan` values and used by + * `isExecutionPlan`. + * + * @category type IDs + * @since 3.16.0 + */ +const TypeId = "~effect/ExecutionPlan"; +/** + * Returns `true` if a value is an `ExecutionPlan` by checking for the + * `ExecutionPlan.TypeId` marker. + * + * **When to use** + * + * Use when accepting an unknown value and you need to narrow it to an + * `ExecutionPlan` before reading plan fields or passing it to plan-consuming + * APIs. + * + * **Gotchas** + * + * This is a structural marker check; it does not validate the marker value or + * the shape of the plan steps. + * + * @see {@link make} for constructing execution plans that satisfy this guard + * @see {@link TypeId} for the runtime marker checked by this guard + * + * @category guards + * @since 3.16.0 + */ +const isExecutionPlan = u => Predicate.hasProperty(u, TypeId); +/** + * Create an `ExecutionPlan`, which can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. + * + * **Example** (Creating an execution plan) + * + * ```ts import.meta.vitest + * import { Context, ExecutionPlan } from "effect" + * + * const ThePlan = ExecutionPlan.make( + * { + * provide: Context.empty(), + * attempts: 2 + * }, + * { + * provide: Context.empty() + * } + * ) + * + * ThePlan.steps.length // => 2 + * ``` + * + * @category constructors + * @since 3.16.0 + */ +const make = (...steps) => makeProto(steps.map((options, i) => { + if (options.attempts !== undefined && options.attempts < 1) { + throw new Error(`ExecutionPlan.make: step[${i}].attempts must be greater than 0`); + } + return { + schedule: options.schedule, + attempts: options.attempts, + while: options.while ? input => effect.suspend(() => { + const result = options.while(input); + return typeof result === "boolean" ? effect.succeed(result) : result; + }) : undefined, + provide: options.provide + }; +})); +const Proto = (/* unused pure expression or super */ null && ({ + [TypeId]: TypeId, + get captureRequirements() { + const self = this; + return effect.contextWith(context => effect.succeed(makeProto(self.steps.map(step => ({ + ...step, + provide: Layer.isLayer(step.provide) ? Layer.provide(step.provide, Layer.succeedContext(context)) : step.provide + }))))); + }, + pipe() { + return pipeArguments(this, arguments); + } +})); +const makeProto = steps => { + const self = Object.create(Proto); + self.steps = steps; + return self; +}; +/** + * Combines multiple execution plans by concatenating their steps in order. + * + * **When to use** + * + * Use to combine separately defined fallback plans into one ordered plan before + * applying it to an effect or stream. + * + * **Details** + * + * The resulting plan tries every step from the first plan, then every step from + * the next plan, and so on. + * + * @see {@link make} for building a plan from individual steps instead of combining existing plans + * + * @category combining + * @since 3.16.0 + */ +const merge = (...plans) => makeProto(plans.flatMap(plan => plan.steps)); +/** + * Context reference containing metadata for the currently running + * execution-plan attempt. + * + * **When to use** + * + * Use to read the active plan step and attempt while code is running under an + * execution plan. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/ExecutionPlan/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + attempt: 0, + stepIndex: 0 + }) +}); +//# sourceMappingURL=ExecutionPlan.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + d3: CurrentMetadata +}); + + +}, +"./node_modules/effect/dist/Exit.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = _internal_core_js__rspack_import_0/* .ExitTypeId */.IH; +/** + * Checks whether an unknown value is an Exit. + * + * **When to use** + * + * Use to validate unknown values at system boundaries and narrow them to + * `Exit`. + * + * **Details** + * + * Does not inspect the contents of the Exit. Returns `true` for both Success + * and Failure exits. + * + * **Example** (Checking if a value is an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.isExit(Exit.succeed(42)) // => true + * Exit.isExit(Exit.fail("err")) // => true + * Exit.isExit("not an exit") // => false + * ``` + * + * @see {@link isSuccess} to check for a successful Exit + * @see {@link isFailure} to check for a failed Exit + * + * @category guards + * @since 2.0.0 + */ +const isExit = _internal_core_js__rspack_import_0/* .isExit */.b9; +/** + * Creates a successful Exit containing the given value. + * + * **When to use** + * + * Use when you need an Exit that contains a known success value. + * + * **Details** + * + * Returns a `Success` with the provided value. Does not perform any + * computation. + * + * **Example** (Creating a successful Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.succeed(42) // => Exit.succeed(42) + * ``` + * + * @see {@link fail} to create a failed Exit + * @see {@link void_ void} for a pre-allocated success with no value + * + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_core_js__rspack_import_0/* .exitSucceed */.xt; +/** + * Creates a failed Exit from a Cause. + * + * **When to use** + * + * Use when you already have a `Cause` and want to wrap it in an Exit + * for advanced error handling where you need full control over the Cause + * structure. + * + * **Details** + * + * Returns a `Failure`. If you only have an error value, use + * {@link fail} instead. + * + * **Example** (Creating a failed Exit from a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link fail} to create a Failure from a plain error value + * @see {@link die} to create a Failure from a defect + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_core_js__rspack_import_0/* .exitFailCause */.cb; +/** + * Creates a failed Exit from a typed error value. + * + * **When to use** + * + * Use when you need to represent an expected typed failure as an `Exit`. + * + * **Details** + * + * The error is wrapped in a `Cause.Fail` internally. + * + * Returns a `Failure`. + * + * **Example** (Creating a failed Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.fail("Something went wrong") // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link succeed} to create a successful Exit + * @see {@link die} to create a Failure from an unexpected defect + * @see {@link failCause} to create a Failure from a full Cause + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .exitFail */.Rk; +/** + * Creates a failed Exit from a defect (unexpected error). + * + * **When to use** + * + * Use when you need unexpected, unrecoverable errors that should not appear in + * the typed error channel. + * + * **Details** + * + * The defect is wrapped in a `Cause.Die` internally. + * + * Returns a `Failure` with `E = never`, since defects do not appear in + * the typed error channel. + * + * **Example** (Creating a defect Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.die("Unexpected error") // => Exit.die("Unexpected error") + * ``` + * + * @see {@link fail} to create a Failure from a typed error + * @see {@link hasDies} to check whether an Exit contains defects + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .exitDie */.V2; +/** + * Creates a failed Exit representing fiber interruption. + * + * **When to use** + * + * Use to signal that a fiber was interrupted. + * + * **Details** + * + * Optionally pass a fiber ID to identify which fiber was interrupted. Returns + * a `Failure` with an `Interrupt` cause. + * + * **Example** (Creating an interruption Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.interrupt(123) // => Exit.interrupt(123) + * ``` + * + * @see {@link hasInterrupts} to check whether an Exit contains interruptions + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .exitInterrupt */._sz; +const void_ = _internal_effect_js__rspack_import_1/* .exitVoid */.x5l; + +/** + * Checks whether an Exit is a Success. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Success` and access the + * `value` property. + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * const exit = Exit.succeed(42) + * + * if (Exit.isSuccess(exit)) { + * exit.value // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .exitIsSuccess */.CoE; +/** + * Checks whether an Exit is a Failure. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Failure` and access the + * `cause` property. + * + * **Example** (Narrowing to failure) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * const exit = Exit.fail("error") + * + * if (Exit.isFailure(exit)) { + * exit.cause // => Cause.fail("error") + * } + * ``` + * + * @see {@link isSuccess} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .exitIsFailure */.VE1; +/** + * Checks whether a failed Exit contains typed errors (Fail reasons). + * + * **When to use** + * + * Use to distinguish typed failures from defects or interruptions. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Fail` reasons in the + * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasFails(Exit.fail("err")) // => true + * Exit.hasFails(Exit.die("bug")) // => false + * Exit.hasFails(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasDies} to check for defects + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .exitHasFails */._mh; +/** + * Checks whether a failed Exit contains defects (Die reasons). + * + * **When to use** + * + * Use to check whether an `Exit` failure cause contains unexpected errors. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Die` reasons in the + * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasDies(Exit.die("bug")) // => true + * Exit.hasDies(Exit.fail("err")) // => false + * Exit.hasDies(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .exitHasDies */.YDM; +/** + * Checks whether a failed Exit contains interruptions (Interrupt reasons). + * + * **When to use** + * + * Use to check whether an `Exit` contains fiber interruption. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Interrupt` reasons in + * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasInterrupts(Exit.interrupt(1)) // => true + * Exit.hasInterrupts(Exit.fail("err")) // => false + * Exit.hasInterrupts(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasDies} to check for defects + * + * @category guards + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .exitHasInterrupts */.lNM; +/** + * Extracts the Success variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Success wrapper. + * + * **Details** + * + * Returns `Result.succeed(success)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for success) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterSuccess(Exit.succeed(42)) // => Result.succeed(Exit.succeed(42)) + * ``` + * + * @see {@link filterFailure} for the inverse + * @see {@link filterValue} to extract the raw value instead of the Success object + * + * @category filtering + * @since 4.0.0 + */ +const filterSuccess = _internal_effect_js__rspack_import_1/* .exitFilterSuccess */.K$2; +/** + * Extracts the success value from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw success value rather than the Success + * wrapper. + * + * **Details** + * + * Returns `Result.succeed(value)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the value) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterValue(Exit.succeed(42)) // => Result.succeed(42) + * ``` + * + * @see {@link filterSuccess} to get the full Success object + * @see {@link getSuccess} to get the value as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterValue = _internal_effect_js__rspack_import_1/* .exitFilterValue */.GUt; +/** + * Extracts the Failure variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(failure)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for failure) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterFailure(Exit.fail("err")) // => Result.succeed(Exit.fail("err")) + * ``` + * + * @see {@link filterSuccess} for the inverse + * @see {@link filterCause} to extract the Cause directly + * + * @category filtering + * @since 4.0.0 + */ +const filterFailure = _internal_effect_js__rspack_import_1/* .exitFilterFailure */.HIt; +/** + * Extracts the Cause from a failed Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw Cause rather than the Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(cause)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Result } from "effect" + * + * Exit.filterCause(Exit.fail("err")) // => Result.succeed(Cause.fail("err")) + * ``` + * + * @see {@link filterFailure} to get the full Failure object + * @see {@link getCause} to get the Cause as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterCause = _internal_effect_js__rspack_import_1/* .exitFilterCause */.yJo; +/** + * Extracts the first typed error value from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(error)` when the Cause contains a Fail reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple errors, the rest + * are ignored. + * + * **Example** (Finding the first typed error) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findError(Exit.fail("not found")) // => Result.succeed("not found") + * Exit.findError(Exit.die("bug")) // => Result.fail(Exit.die("bug")) + * ``` + * + * @see {@link findErrorOption} to get the error as an Option instead + * @see {@link findDefect} to find defects instead + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .exitFindError */._OD; +/** + * Extracts the first defect from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first defect from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(defect)` when the Cause contains a Die reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Die reason. If the Cause has multiple defects, the rest + * are ignored. + * + * **Example** (Finding the first defect) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findDefect(Exit.die("boom")) // => Result.succeed("boom") + * Exit.findDefect(Exit.fail("err")) // => Result.fail(Exit.fail("err")) + * ``` + * + * @see {@link findError} to find typed errors instead + * @see {@link hasDies} to check for defects without extracting them + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .exitFindDefect */.jCT; +/** + * Pattern matches on an Exit, handling both success and failure cases. + * + * **When to use** + * + * Use when you need exhaustive handling of both `Exit` success and failure + * outcomes. + * + * **Details** + * + * Calls `onSuccess` with the value if the Exit is a Success, and calls + * `onFailure` with the Cause if the Exit is a Failure. + * + * **Example** (Matching on an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.match(Exit.succeed(42), { + * onSuccess: (value) => `Got: ${value}`, + * onFailure: () => "Failed" + * }) // => "Got: 42" + * ``` + * + * @see {@link isSuccess} and {@link isFailure} for simple boolean checks + * + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .exitMatch */.Wtn; +/** + * Transforms the success value of an Exit using the given function. + * + * **When to use** + * + * Use to apply a transformation to the value inside a successful Exit + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Mapping over a success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.map(Exit.succeed(21), (x) => x * 2) // => Exit.succeed(42) + * ``` + * + * @see {@link mapError} to transform the error + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .exitMap */.v9O; +/** + * Transforms the typed error of a failed Exit using the given function. + * + * **When to use** + * + * Use to remap typed errors while preserving the Exit structure + * + * **Details** + * + * Successes pass through unchanged. + * + * Allocates a new Exit if the error is transformed. + * + * **Gotchas** + * + * Only transforms typed errors (Fail reasons). If the Cause contains only + * defects or interruptions, the failure passes through unchanged. + * + * **Example** (Mapping over an error) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapError(Exit.fail("bad input"), (error) => error.toUpperCase()) // => Exit.fail("BAD INPUT") + * ``` + * + * @see {@link map} to transform the success value + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .exitMapError */.zPu; +/** + * Transforms both the success value and typed error of an Exit. + * + * **When to use** + * + * Use when you need to remap both channels in one step. + * + * **Details** + * + * `onSuccess` transforms the value if the Exit is a Success. `onFailure` + * transforms the typed error if the Exit is a Failure with a Fail reason. + * Allocates a new Exit. + * + * **Gotchas** + * + * If the Cause contains only defects or interruptions, the failure passes + * through unchanged. + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapBoth(Exit.succeed(42), { + * onSuccess: (x) => String(x), + * onFailure: (error: string) => error.toUpperCase() + * }) // => Exit.succeed("42") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error + * + * @category combinators + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .exitMapBoth */.EkE; +/** + * Discards the success value of an Exit, replacing it with `void`. + * + * **When to use** + * + * Use when you need to discard a successful `Exit` value while preserving + * whether the `Exit` succeeded or failed. + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Discarding the success value) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoid(Exit.succeed(42)) // => Exit.succeed(undefined) + * ``` + * + * @see {@link void_ void} for a pre-allocated void success + * @see {@link asVoidAll} to combine multiple exits into a single void Exit + * + * @category combinators + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .exitAsVoid */.Hox; +/** + * Combines multiple Exit values into a single `Exit`. + * + * **When to use** + * + * Use to validate that all exits in a collection succeeded + * + * **Details** + * + * If all exits are successful, this returns a void success. If any exit is a + * failure, this returns a single failure with all error causes combined. + * + * Iterates over the entire collection. Collects all failure causes, not just + * the first. + * + * **Example** (Combining exits) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoidAll([Exit.succeed(1), Exit.succeed(2), Exit.succeed(3)]) // => Exit.succeed(undefined) + * Exit.asVoidAll([Exit.succeed(1), Exit.fail("err"), Exit.succeed(3)]) // => Exit.fail("err") + * ``` + * + * @see {@link asVoid} to discard the value of a single Exit + * + * @category combinators + * @since 4.0.0 + */ +const asVoidAll = _internal_effect_js__rspack_import_1/* .exitAsVoidAll */.ely; +/** + * Returns the success value of an Exit as an Option. + * + * **When to use** + * + * Use when you need the success value from an `Exit` as an `Option` instead of + * pattern matching. + * + * **Details** + * + * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure. + * + * **Example** (Getting the success value) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.getSuccess(Exit.succeed(42)) // => Option.some(42) + * Exit.getSuccess(Exit.fail("err")) // => Option.none() + * ``` + * + * @see {@link getCause} to extract the Cause of a failure + * @see {@link filterValue} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_effect_js__rspack_import_1/* .exitGetSuccess */.kMI; +/** + * Returns the Cause of a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the failure `Cause` from an `Exit` as an `Option` instead + * of pattern matching. + * + * **Details** + * + * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success. + * + * **Example** (Getting the failure cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Option } from "effect" + * + * Exit.getCause(Exit.fail("err")) // => Option.some(Cause.fail("err")) + * Exit.getCause(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link getSuccess} to extract the success value + * @see {@link filterCause} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getCause = _internal_effect_js__rspack_import_1/* .exitGetCause */.Sv3; +/** + * Returns the first typed error from a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as an `Option`, + * ignoring successes and non-typed failures. + * + * **Details** + * + * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes, + * defect-only failures, and interrupt-only failures return `Option.none()`. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple typed errors, + * the rest are ignored. + * + * **Example** (Getting the first error) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.findErrorOption(Exit.fail("err")) // => Option.some("err") + * Exit.findErrorOption(Exit.die("bug")) // => Option.none() + * Exit.findErrorOption(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link findError} for filter-pipeline usage + * @see {@link getCause} to get the full Cause as an Option + * + * @category getters + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .exitFindErrorOption */.lgw; +//# sourceMappingURL=Exit.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + AT: failCause, + N6: isFailure, + Py: succeed, + oJ: isSuccess, + rI: void_ +}); + + +}, +"./node_modules/effect/dist/Fiber.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = "~effect/Fiber"; +const await_ = _internal_effect_js__rspack_import_0/* .fiberAwait */.zFM; + +/** + * Waits for all fibers in the provided iterable to complete and returns + * an array of their exit values. + * + * **When to use** + * + * Use when you need every fiber outcome as data, including failures and + * interruptions. + * + * **Details** + * + * The returned array is ordered like the input iterable. + * + * **Gotchas** + * + * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you + * want the first failed fiber to fail the returned Effect. + * + * **Example** (Awaiting multiple fiber exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.succeed(1)) + * const fiber2 = yield* Effect.forkChild(Effect.succeed(2)) + * return yield* Fiber.awaitAll([fiber1, fiber2]) + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [Exit.succeed(1), Exit.succeed(2)] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const awaitAll = _internal_effect_js__rspack_import_0/* .fiberAwaitAll */.C6p; +/** + * 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 + * + * @category combinators + * @since 2.0.0 + */ +const join = _internal_effect_js__rspack_import_0/* .fiberJoin */.D7p; +/** + * Waits for all fibers to succeed and returns their values in input order. + * + * **When to use** + * + * Use when you need every fiber to succeed and want the successful values + * rather than the `Exit` values. + * + * **Details** + * + * If any fiber fails, the returned `Effect` fails with that fiber's cause and + * stops waiting for additional results. This does not interrupt the remaining + * fibers. + * + * **Gotchas** + * + * A failure stops waiting, but it does not interrupt any other fibers. Use + * {@link interruptAll} separately when remaining fibers should be stopped. + * + * @see {@link awaitAll} for collecting every fiber outcome as an Exit + * + * @category combinators + * @since 2.0.0 + */ +const joinAll = _internal_effect_js__rspack_import_0/* .fiberJoinAll */.INJ; +/** + * Interrupts a fiber, causing it to stop executing and clean up any + * acquired resources. + * + * **When to use** + * + * Use when you need to cancel a forked fiber and wait for its cleanup to + * complete. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * Interruption is cooperative. A fiber can continue running while it is inside + * uninterruptible work or finalizers. + * + * **Example** (Interrupting a fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild( + * Effect.delay("1 second")(Effect.succeed(42)) + * ) + * yield* Fiber.interrupt(fiber) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAs} for specifying the interrupting fiber ID + * @see {@link await_ await} for observing the interrupted fiber's Exit + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_0/* .fiberInterrupt */.mKq; +/** + * Interrupts a fiber with a specific fiber ID as the interruptor. This allows + * tracking which fiber initiated the interruption. + * + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const targetFiber = yield* Effect.forkChild( + * Effect.delay("5 seconds")(Effect.succeed("task completed")) + * ) + * + * // Interrupt the fiber, specifying fiber ID 123 as the interruptor + * yield* Fiber.interruptAs(targetFiber, 123) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interrupt} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAs */.eGS; +/** + * Interrupts all fibers in the provided iterable, causing them to stop executing + * and clean up any acquired resources. + * + * **When to use** + * + * Use when you need to cancel several forked fibers and wait for their cleanup + * to complete. + * + * **Details** + * + * The current fiber is recorded as the interruptor. The returned Effect + * completes only after all interrupted fibers have completed. + * + * **Gotchas** + * + * Interruption is cooperative for each fiber. The returned Effect can wait for + * uninterruptible work and finalizers in any interrupted fiber. + * + * **Example** (Interrupting multiple fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.never) + * const fiber2 = yield* Effect.forkChild(Effect.never) + * const fiber3 = yield* Effect.forkChild(Effect.never) + * yield* Fiber.interruptAll([fiber1, fiber2, fiber3]) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAllAs} for specifying the interrupting fiber ID + * + * @category interruption + * @since 2.0.0 + */ +const interruptAll = _internal_effect_js__rspack_import_0/* .fiberInterruptAll */.DKo; +/** + * Interrupts all fibers in the provided iterable using the specified fiber ID as the + * interrupting fiber. This allows you to control which fiber is considered the source + * of the interruption, which can be useful for debugging and tracing. + * + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a controlling fiber + * const controllerFiber = yield* Effect.forkChild(Effect.succeed("controller")) + * + * const worker1 = yield* Effect.forkChild(Effect.never) + * const worker2 = yield* Effect.forkChild(Effect.never) + * + * yield* Fiber.interruptAllAs([worker1, worker2], controllerFiber.id) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAll} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAllAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAllAs */.$MQ; +/** + * Checks whether a value is a Fiber. This is a type guard that can be used to + * determine if an unknown value is a Fiber instance. + * + * **When to use** + * + * Use when checking values at boundaries where an unknown value may be a + * runtime fiber. + * + * **Details** + * + * The check looks for the internal Fiber type ID marker and does not inspect + * the fiber's current state. + * + * **Example** (Checking for fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a fiber + * const fiber = yield* Effect.forkChild(Effect.succeed(42)) + * + * // Test if values are fibers + * return [Fiber.isFiber(fiber), Fiber.isFiber("hello"), Fiber.isFiber(42), Fiber.isFiber(null)] + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [true, false, false, false] + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isFiber = u => hasProperty(u, effect.FiberTypeId); +/** + * Returns the current fiber if called from within a fiber context, + * otherwise returns `undefined`. + * + * **When to use** + * + * Use when you need low-level runtime integrations that need access to the currently + * executing fiber. + * + * **Gotchas** + * + * This is a synchronous accessor, not an Effect. It returns `undefined` outside + * an active fiber runtime context. + * + * **Example** (Getting the current fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const current = Fiber.getCurrent() + * return current !== undefined + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => true + * ``` + * + * @category getters + * @since 4.0.0 + */ +const getCurrent = _internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku; +/** + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. + * + * **Details** + * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion + * + * @category resource management + * @since 4.0.0 + */ +const runIn = _internal_effect_js__rspack_import_0/* .fiberRunIn */.vTQ; +//# sourceMappingURL=Fiber.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + G: interrupt, + VO: runIn, + fj: join +}); + + +}, +"./node_modules/effect/dist/Filter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Result.js"); + + + + + +// ------------------------------------------------------------------------------------- +// Constructors +// ------------------------------------------------------------------------------------- +/** + * Creates a Filter from a function that returns either a `pass` or `fail` value. + * + * **Details** + * + * This is the primary constructor for creating custom filters. The function + * should return either `Result.succeed(value)` or `Result.fail(value)`. + * + * **Example** (Creating custom filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create a filter for positive numbers + * const positiveFilter = Filter.make((n: number) => n > 0 ? Result.succeed(n) : Result.fail(n)) + * + * // Create a filter that transforms strings to uppercase + * const uppercaseFilter = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * positiveFilter(1) // => Result.succeed(1) + * uppercaseFilter("ok") // => Result.succeed("OK") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = f => f; +/** + * Creates an effectful Filter from a function that returns an Effect. + * + * **Details** + * + * This constructor is used when the filtering operation needs to perform + * effectful computations, such as async operations, error handling, or accessing + * services from the environment. + * + * **Example** (Creating effectful filters) + * + * ```ts import.meta.vitest + * import { Effect, Filter, Result } from "effect" + * + * // Create an effectful filter that validates async + * const asyncValidate = Filter.makeEffect((id: string) => + * Effect.gen(function*() { + * const isValid = yield* Effect.succeed(id.length > 0) + * return isValid ? Result.succeed(id) : Result.fail(id) + * }) + * ) + * + * await Effect.runPromise(asyncValidate("id")) // => Result.succeed("id") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeEffect = f => f; +/** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping + * @since 4.0.0 + */ +const mapFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => input => Result.mapError(self(input), f)))); +const try_ = f => input => { + try { + return Result.succeed(f(input)); + } catch { + return Result.fail(input); + } +}; + +/** + * Creates a Filter from a predicate or refinement function. + * + * **Details** + * + * This is a convenient way to create filters from boolean-returning functions. + * When the predicate returns true, the input value is passed through unchanged. + * When it returns false, the `fail` type is returned. + * + * **Example** (Creating filters from predicates) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create filter from predicate + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const nonEmptyStrings = Filter.fromPredicate((s: string) => s.length > 0) + * + * // Type refinement + * const isString = Filter.fromPredicate((x: unknown): x is string => + * typeof x === "string" + * ) + * positiveNumbers(1) // => Result.succeed(1) + * nonEmptyStrings("") // => Result.fail("") + * isString("ok") // => Result.succeed("ok") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicate = predicate => input => predicate(input) ? _Result_js__rspack_import_0/* .succeed */.Py(input) : _Result_js__rspack_import_0/* .fail */.fJ(input); +/** + * Creates a `Filter` from a function that returns an `Option`; `Some(value)` + * passes with `value`, and `None` fails with the original input. + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicateOption = predicate => input => { + const o = predicate(input); + return o._tag === "None" ? Result.fail(input) : Result.succeed(o.value); +}; +/** + * Converts a Filter into a predicate function. + * + * **When to use** + * + * Use to reuse a `Filter` with APIs that accept only boolean predicates when + * the pass and fail payloads are not needed. + * + * @see {@link toOption} for keeping passed values and discarding failure values + * @see {@link toResult} for preserving both pass and failure values + * + * @category converting + * @since 4.0.0 + */ +const toPredicate = self => input => !Result.isFailure(self(input)); +/** + * A predefined filter that only passes through string values. + * + * **Example** (Filtering strings) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.string("hello") // => Result.succeed("hello") + * Filter.string(42) // => Result.fail(42) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const string = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isString */.Kg); +/** + * Creates a `Filter` that passes only values strictly equal to the specified + * value using JavaScript `===` comparison. + * + * **When to use** + * + * Use when you need a `Filter` that accepts only the exact primitive value or + * object reference using JavaScript strict equality in a `Filter` / `Result` + * pipeline. + * + * **Gotchas** + * + * `NaN` never passes, even when the expected value is `NaN`, and objects pass + * only when they are the same reference. + * + * @see {@link equals} for structural equality when distinct values with equal + * contents should pass + * + * @category constructors + * @since 4.0.0 + */ +const equalsStrict = value => u => u === value ? Result.succeed(value) : Result.fail(u); +/** + * Creates a `Filter` that passes inputs whose `has(key)` method returns + * `true` for the specified key. + * + * **When to use** + * + * Use to keep inputs that expose a `has` method, such as `Set` or `Map`, when + * they contain a required key. + * + * @see {@link fromPredicate} for custom predicate filters or inputs without a + * `has` method + * @see {@link Predicate.hasProperty} for guarding property presence instead of + * calling an input's `has` method + * + * @category constructors + * @since 4.0.0 + */ +const has = key => input => input.has(key) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that only passes instances of the given constructor. + * + * **When to use** + * + * Use to narrow unknown input to values created by a specific JavaScript + * constructor while keeping the result in the `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when the input satisfies `instanceof constructor`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This uses JavaScript `instanceof` semantics, including prototype-chain and + * realm behavior. + * + * @see {@link fromPredicate} for custom predicate-based narrowing + * + * @category constructors + * @since 4.0.0 + */ +const instanceOf = constructor => u => u instanceof constructor ? Result.succeed(u) : Result.fail(u); +/** + * A predefined filter that only passes through number values. + * + * **Example** (Filtering numbers) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.number(42) // => Result.succeed(42) + * Filter.number("42") // => Result.fail("42") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const number = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isNumber */.Et); +/** + * A predefined filter that only passes through boolean values. + * + * **When to use** + * + * Use when accepting an unknown input only if it is already a boolean and you + * want a `Filter` result rather than a plain predicate result. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBoolean)`, so `true` and `false` + * succeed and non-booleans fail with the original input. + * + * @see {@link Predicate.isBoolean} for the underlying guard + * @see {@link fromPredicate} for custom predicate-based filters + * + * @category constructors + * @since 4.0.0 + */ +const boolean = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBoolean */.Lm); +/** + * A predefined filter that only passes through `bigint` primitive values. + * + * **When to use** + * + * Use to keep primitive big integer values from unknown input while staying in + * the composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBigInt)`, so values where + * `typeof input === "bigint"` succeed and all other inputs fail with the + * original input. + * + * **Gotchas** + * + * This filter does not coerce numbers or strings; `1n` passes while `1` fails. + * + * @see {@link number} for JavaScript `number` values + * @see {@link Predicate.isBigInt} for the underlying guard + * + * @category constructors + * @since 4.0.0 + */ +const bigint = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBigInt */.sI); +/** + * A predefined filter that only passes through Symbol values. + * + * @category constructors + * @since 4.0.0 + */ +const symbol = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isSymbol */.Bm); +/** + * A predefined filter that only passes through Date objects. + * + * **When to use** + * + * Use when you need to narrow unknown input to JavaScript `Date` instances with + * a reusable `Filter`. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isDate)`, so passing values return + * `Result.succeed(input)` and failing values return `Result.fail(input)`. + * + * **Gotchas** + * + * The check uses `instanceof Date`, so invalid `Date` objects still pass; the + * filter does not validate the timestamp. + * + * @see {@link Predicate.isDate} for the underlying guard + * @see {@link instanceOf} for constructor-based filtering + * @see {@link fromPredicate} for custom date checks + * + * @category constructors + * @since 4.0.0 + */ +const date = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isDate */.$P); +/** + * Creates a filter that checks if an input is tagged with a specific tag. + * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors + * @since 4.0.0 + */ +const tagged = function () { + return arguments.length === 0 ? taggedImpl : taggedImpl(arguments[0]); +}; +const taggedImpl = tag => input => Predicate.isTagged(input, tag) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that extracts a reason from a tagged error. + * + * @category constructors + * @since 4.0.0 + */ +const reason = function () { + return arguments.length === 0 ? reasonImpl : reasonImpl(arguments[0], arguments[1]); +}; +const reasonImpl = (tag, reasonTag) => input => { + if (Predicate.isTagged(input, tag) && Predicate.hasProperty(input, "reason") && Predicate.isTagged(input.reason, reasonTag)) { + return Result.succeed(input.reason); + } + return Result.fail(input); +}; +/** + * Creates a filter that only passes values equal to the specified value using structural equality. + * + * **When to use** + * + * Use to accept inputs that are structurally equal to a known expected value + * while staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Delegates to `Equal.equals`. On success it returns `Result.succeed(value)`; + * on failure it returns `Result.fail(input)`. + * + * @see {@link equalsStrict} for JavaScript `===` matching instead of structural + * equality + * @see {@link Equal.equals} for the underlying structural equality semantics + * + * @category constructors + * @since 4.0.0 + */ +const equals = value => u => Equal.equals(u, value) ? Result.succeed(value) : Result.fail(u); +/** + * Combines two filters with logical OR semantics. + * + * @category combinators + * @since 4.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => input => { + const selfResult = self(input); + return Result.isSuccess(selfResult) ? selfResult : that(input); +}))); +/** + * Combines two filters and applies a function to their results. + * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * + * Both filters must succeed (not return `fail`) for the combination to succeed. + * If both filters pass, their outputs are combined using the provided function. + * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators + * @since 4.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => input => { + const leftResult = left(input); + if (Result.isFailure(leftResult)) return leftResult; + const rightResult = right(input); + if (Result.isFailure(rightResult)) return rightResult; + return Result.succeed(f(leftResult.success, rightResult.success)); +}))); +/** + * Combines two filters into a tuple of their results. + * + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) + * positiveAndEven(2) // => Result.succeed([2, 2]) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (leftResult, rightResult) => [leftResult, rightResult])))); +/** + * Combines two filters but only returns the result of the left filter. + * + * **Example** (Keeping the left filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) + * positiveEven(2) // => Result.succeed(2) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, leftResult => leftResult)))); +/** + * Combines two filters but only returns the result of the right filter. + * + * **Example** (Keeping the right filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const doubleNumbers = Filter.make((n: number) => + * n > 0 ? Result.succeed(n * 2) : Result.fail(n) + * ) + * + * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) + * positiveDoubled(2) // => Result.succeed(4) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (_, rightResult) => rightResult)))); +/** + * Composes two filters sequentially, feeding the output of the first into the second. + * + * **Example** (Composing filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const stringFilter = Filter.string + * const nonEmptyUpper = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * + * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) + * stringToUpper("hello") // => Result.succeed("HELLO") + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => input => { + const leftOut = left(input); + if (Result.isFailure(leftOut)) return leftOut; + return right(leftOut.success); +}))); +/** + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. + * + * **Details** + * + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. + * + * @category combinators + * @since 4.0.0 + */ +const composePassthrough = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (left, right) => input => { + const leftOut = left(input); + if (_Result_js__rspack_import_0/* .isFailure */.N6(leftOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + const rightOut = right(leftOut.success); + if (_Result_js__rspack_import_0/* .isFailure */.N6(rightOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + return rightOut; +}); +/** + * Converts a `Filter` into a function that returns `Some` for passed values + * and `None` for filtered-out values. + * + * **When to use** + * + * Use when adapting a `Filter` to `Option`-based code where passed values + * become `Some` and filtered-out inputs become `None`. + * + * @see {@link toResult} for keeping the filter failure value + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toOption = self => input => { + const result = self(input); + return _Result_js__rspack_import_0/* .isFailure */.N6(result) ? _Option_js__rspack_import_3.none() : _Option_js__rspack_import_3.some(result.success); +}; +/** + * Converts a `Filter` into a function that returns the underlying + * `Result.Result` for each input. + * + * **When to use** + * + * Use to adapt a `Filter` to APIs that expect a plain function returning + * `Result`, while preserving both the pass value and the failure value. + * + * @see {@link toOption} for keeping only passed values + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toResult = self => input => { + const result = self(input); + return Result.isFailure(result) ? Result.fail(result.failure) : Result.succeed(result.success); +}; +//# sourceMappingURL=Filter.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Bh: composePassthrough, + zL: toOption +}); + + +}, +"./node_modules/effect/dist/Formatter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.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. + * + * @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. + * - 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} + * @category formatting + * @since 2.0.0 + */ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = 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) { + 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 (_Redactable_js__rspack_import_0/* .symbolRedactable */.uC in v) { + output = recur((0,_Redactable_js__rspack_import_0/* .getRedacted */.f6)(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 && _Predicate_js__rspack_import_1/* .hasProperty */.i5(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 ? `${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(v[k], d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map(k => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(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 an array of property keys as a bracket-notation path string. + * + * @internal + */ +function formatPath(path) { + return path.map(key => `[${formatPropertyKey(key)}]`).join(""); +} +/** + * 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]"; + } +} +/** + * Stringifies a value to JSON safely, silently dropping circular references. + * + * **When to use** + * + * Use when you need valid JSON output, unlike `format`, and the input may + * contain circular references that should be silently omitted rather than + * throwing a `TypeError`. + * + * **Details** + * + * Uses `JSON.stringify` internally with a replacer that tracks the current + * object ancestry. Circular references are replaced with `undefined`, which + * omits them from object output. `Redactable` values are automatically redacted + * before serialization. `BigInt` values are stringified with an `n` suffix. + * Values not supported by JSON otherwise follow standard `JSON.stringify` + * behavior. The `space` parameter controls indentation and defaults to `0`. + * + * **Gotchas** + * + * When the root input is `undefined`, a symbol, or a function, `formatJson` + * returns `"null"` instead of the `undefined` returned by `JSON.stringify`. + * Nested values retain standard `JSON.stringify` behavior. + * + * **Example** (Formatting compact JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * Formatter.formatJson({ name: "Alice", age: 30 }) // => "{\"name\":\"Alice\",\"age\":30}" + * ``` + * + * **Example** (Handling circular references) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const obj: any = { name: "test" } + * obj.self = obj + * Formatter.formatJson(obj) // => "{\"name\":\"test\"}" + * ``` + * + * **Example** (Pretty-printed JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const output = Formatter.formatJson({ name: "Alice", age: 30 }, { space: 2 }) + * output // => "{\n \"name\": \"Alice\",\n \"age\": 30\n}" + * ``` + * + * @see {@link format} + * @see {@link Formatter} + * @category serialization + * @since 4.0.0 + */ +function formatJson(input, options) { + const ancestors = []; + return JSON.stringify(input, function (key, value) { + const original = Object.getOwnPropertyDescriptor(this, key)?.value; + const redacted = _Predicate_js__rspack_import_1/* .hasProperty */.i5(original, _Redactable_js__rspack_import_0/* .symbolRedactable */.uC) ? (0,_Redactable_js__rspack_import_0/* .redact */.E$)(original) : (0,_Redactable_js__rspack_import_0/* .redact */.E$)(value); + if (typeof redacted === "bigint") { + return format(redacted); + } + if (typeof redacted !== "object" || redacted === null) { + return redacted; + } + while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) { + ancestors.pop(); + } + if (ancestors.includes(redacted)) { + return undefined; // circular reference + } + ancestors.push(redacted); + return redacted; + }, options?.space) ?? "null"; +} +//# sourceMappingURL=Formatter.js.map +__webpack_require__.d(__webpack_exports__, { + GP: () => (format), + IB: () => (formatJson) +}); + + +}, +"./node_modules/effect/dist/Function.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { + +/** + * 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 + * ``` + * + * @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) { + // @ts-expect-error + return body.apply(this, arguments); + } + const args = arguments; + return function (self) { + return body(self, ...args); + }; + }; + } +}; +/** + * Applies a function to a given value. + * + * **When to use** + * + * Use to pass a fixed value into a unary function, especially when the function + * is the value flowing through `pipe`. + * + * **Details** + * + * `apply(a)(f)` is equivalent to `f(a)`. + * + * **Example** (Applying an argument to a function) + * + * ```ts import.meta.vitest + * import { Function, pipe, String } from "effect" + * + * pipe(String.length, Function.apply("hello")) // => 5 + * ``` + * + * @see {@link pipe} for building left-to-right pipelines + * + * @category combinators + * @since 2.0.0 + */ +const apply = a => self => self(a); +/** + * 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 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const identity = a => a; +/** + * Ensures that the type of an expression matches some type, + * without changing the resulting type of that expression. + * + * **When to use** + * + * Use to check assignability while preserving the expression's precise inferred + * type. + * + * **Example** (Checking an expression against a type) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const test1 = Function.satisfies()(5 as const) // => 5 + * // ^? const test: 5 + * // @ts-expect-error + * const test2 = Function.satisfies()(5) + * // ^? Argument of type 'number' is not assignable to parameter of type 'string' + * ``` + * + * @see {@link cast} for changing only the static TypeScript type + * + * @category utility types + * @since 2.0.0 + */ +const satisfies = () => b => b; +/** + * Returns the input value with a different static type. + * + * **When to use** + * + * Use when you need an explicit type-level cast and accept that the value is + * returned unchanged at runtime. + * + * **Gotchas** + * + * This is a type-level cast only; it performs no runtime validation or + * conversion. + * + * @see {@link satisfies} for checking assignability without changing the resulting type + * + * @category utility types + * @since 4.0.0 + */ +const cast = (/* unused pure expression or super */ null && (identity)); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constTrue = /*#__PURE__*/constant(true); +/** + * Returns `false` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `false` on every invocation. + * + * **Example** (Returning false from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constFalse() // => false + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constFalse = /*#__PURE__*/constant(false); +/** + * Returns `null` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `null` on every invocation. + * + * **Example** (Returning null from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constNull() // => null + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constNull = /*#__PURE__*/constant(null); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constUndefined = /*#__PURE__*/constant(undefined); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constVoid = constUndefined; +/** + * Reverses the order of arguments for a curried function. + * + * **When to use** + * + * Use to adapt a curried function when its argument groups need to be supplied + * in the opposite order. + * + * **Example** (Flipping curried arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const f = (a: number) => (b: string) => a - b.length + * + * Function.flip(f)("aaa")(2) // => -1 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const flip = f => (...b) => (...a) => f(...a)(...b); +/** + * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. + * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. + * + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const increment = (n: number) => n + 1 + * const square = (n: number) => n * n + * + * Function.compose(increment, square)(2) // => 9 + * ``` + * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => bc(ab(a))))); +/** + * Marks an impossible branch by accepting a `never` value and returning any + * type. + * + * **When to use** + * + * Use when you need a return value in a branch that exhaustive checks prove + * cannot be reached. + * + * **Gotchas** + * + * Calling `absurd` throws, because a value of type `never` should be + * impossible at runtime. + * + * **Example** (Handling impossible values) + * + * ```ts import.meta.vitest + * import { absurd } from "effect" + * + * const handleNever = (value: never) => { + * return absurd(value) // This will throw an error if called + * } + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const absurd = _ => { + throw new Error("Called `absurd` function which should be uncallable"); +}; +/** + * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. + * + * **When to use** + * + * Use to adapt a multi-argument function so it accepts one tuple argument. + * + * **Example** (Converting arguments to a tuple) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const sumTupled = Function.tupled((x: number, y: number): number => x + y) + * + * sumTupled([1, 2]) // => 3 + * ``` + * + * @see {@link untupled} for adapting a tuple-argument function back to multiple arguments + * + * @category combinators + * @since 2.0.0 + */ +const tupled = f => a => f(...a); +/** + * Converts a tupled function back to an uncurried function. + * + * **When to use** + * + * Use to adapt a tuple-argument function so it accepts multiple arguments. + * + * **Example** (Converting a tuple to arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const getFirst = Function.untupled((tuple: [A, B]): A => tuple[0]) + * + * getFirst(1, 2) // => 1 + * ``` + * + * @see {@link tupled} for adapting a multi-argument function to one tuple argument + * + * @category combinators + * @since 2.0.0 + */ +const untupled = f => (...a) => f(a); +function pipe(a, ...args) { + return pipeArguments(a, args); +} +function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) { + switch (arguments.length) { + case 1: + return ab; + case 2: + return function () { + return bc(ab.apply(this, arguments)); + }; + case 3: + return function () { + return cd(bc(ab.apply(this, arguments))); + }; + case 4: + return function () { + return de(cd(bc(ab.apply(this, arguments)))); + }; + case 5: + return function () { + return ef(de(cd(bc(ab.apply(this, arguments))))); + }; + case 6: + return function () { + return fg(ef(de(cd(bc(ab.apply(this, arguments)))))); + }; + case 7: + return function () { + return gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))); + }; + case 8: + return function () { + return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))); + }; + case 9: + return function () { + return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))); + }; + } + return; +} +/** + * Creates a compile-time placeholder for a value of any type. + * + * **When to use** + * + * Use as a temporary typed placeholder while developing incomplete code. + * + * **Gotchas** + * + * `hole` is intended for temporary development use. If the placeholder is + * evaluated at runtime, it throws. + * + * **Example** (Creating a development placeholder) + * + * ```ts import.meta.vitest + * import { hole } from "effect" + * + * // Intentionally not called: `hole` throws if the placeholder is evaluated. + * const buildUser = (id: number): { readonly id: number; readonly name: string } => ({ + * id, + * name: hole() + * }) + * + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const hole = /*#__PURE__*/(/* unused pure expression or super */ null && (cast(absurd))); +/** + * Returns the second argument and discards the first. The SK combinator is + * a fundamental combinator in the lambda calculus and the SKI combinator + * calculus. + * + * **When to use** + * + * Use to discard the first argument and return the second argument. + * + * **Example** (Discarding the first argument) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.SK(0, "hello") // => "hello" + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const SK = (_, b) => b; +/** + * Creates a memoized function whose input is an object, caching results by + * object identity. + * + * **When to use** + * + * Use to reuse the result of a synchronous computation whose output is stable + * for a given object reference. + * + * **Details** + * + * Each memoized wrapper owns a private `WeakMap` keyed by object identity. + * + * **Gotchas** + * + * `undefined` is reserved to represent a cache miss and is therefore not + * supported as a return value. + * + * Structurally equal objects do not share cache entries. If the same object is + * mutated after its first call, later calls still return the cached result for + * that reference. + * + * @category caching + * @since 4.0.0 + */ +function memoize(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + return result; + }; +} +/** + * Creates a memoized idempotent object transformation that caches both inputs + * and their outputs by object identity. + * + * **When to use** + * + * Use when an object transformation is idempotent and its output can be safely + * reused as a fixed point. + * + * **Details** + * + * After computing an input, the returned function caches both the input and + * the output. Calling it with either reference returns the output without + * invoking the supplied function again. + * + * **Gotchas** + * + * The returned function treats each computed output as a fixed point. If + * applying the supplied function to an output would produce an observably + * different value, this memoization changes that behavior. + * + * @see {@link memoize} for memoizing functions without an idempotence requirement + * @category caching + * @since 4.0.0 + */ +function memoizeIdempotent(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + cache.set(result, result); + return result; + }; +} +//# sourceMappingURL=Function.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + D_: identity, + MN: constUndefined, + XR: constNull, + XY: dual, + Yi: constVoid, + dY: constant, + f4: constFalse, + ue: constTrue +}); + + +}, +"./node_modules/effect/dist/Hash.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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. + * + * @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 + * + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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 + * ``` + * + * @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 "boolean": + return string(String(self)); + case "symbol": + return string(String(self)); + case "string": + return string(self); + case "undefined": + return string("undefined"); + case "function": + case "object": + { + if (self === null) { + return string("null"); + } 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 (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self)) { + return random(self); + } + if (hashCache.has(self)) { + return hashCache.get(self); + } + const h = withVisitedTracking(self, () => { + if (isHash(self)) { + return self[symbol](); + } else if (typeof self === "function") { + return random(self); + } else if (self instanceof DataView) { + return array(new Uint8Array(self.buffer, self.byteOffset, self.byteLength)); + } else if (Array.isArray(self) || ArrayBuffer.isView(self)) { + return array(self); + } else if (self instanceof Map) { + return hashMap(self); + } else if (self instanceof Set) { + return hashSet(self); + } + return structure(self); + }); + hashCache.set(self, h); + return h; + } + } + default: + throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`); + } +}; +/** + * 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" + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const random = self => { + if (!randomHashCache.has(self)) { + randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))); + } + return randomHashCache.get(self); +}; +/** + * 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 both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **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 + * + * @category hashing + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => self * 53 ^ b); +/** + * 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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const optimize = n => n & 0xbfffffff | n >>> 1 & 0x40000000; +/** + * 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 the Hash symbol property, + * indicating that it can provide its own hash value implementation. + * + * **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 + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isHash = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Computes a hash value for a number. + * + * **When to use** + * + * Use to hash a JavaScript number with Effect's numeric hash semantics. + * + * **Details** + * + * This function creates a hash value for numeric inputs, handling special cases + * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution + * of hash values across different numeric inputs. + * + * **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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const number = n => { + if (n !== n) { + return string("NaN"); + } + if (n === Infinity) { + return string("Infinity"); + } + if (n === -Infinity) { + return string("-Infinity"); + } + let h = n | 0; + if (h !== n) { + h ^= n * 0xffffffff; + } + while (n > 0xffffffff) { + h ^= n /= 0xffffffff; + } + return optimize(h); +}; +/** + * 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 + * ``` + * + * @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 // => -590673747 + * hash2 // => 284850673 + * + * const person2 = { name: "John", age: 30, city: "Boston" } + * const hash3 = Hash.structureKeys(person2, ["name", "age"]) + * hash1 === hash3 // => true + * ``` + * + * @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) // => -590673747 + * Hash.structure(obj2) // => -590160631 + * Hash.structure(obj3) // => -590673747 + * Hash.structure(obj1) === Hash.structure(obj3) // => true + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const structure = o => structureKeys(o, (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(o)); +const iterableWith = (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** + * + * The implementation folds element hashes from the seed `6151` with XOR and + * then optimizes the final hash. + * + * **Gotchas** + * + * A hash is not an equality proof. Because this implementation uses XOR, + * reordered inputs can produce the same 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) // => 6151 + * Hash.array(arr2) // => 6151 + * Hash.array(arr3) // => 6151 + * Hash.array(arr1) === Hash.array(arr2) // => true + * Hash.array(arr1) === Hash.array(arr3) // => true + * ``` + * + * @see {@link hash} for the general-purpose hash dispatcher + * + * @category hashing + * @since 2.0.0 + */ +const array = /*#__PURE__*/iterableWith(6151, hash); +const hashMap = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const hashSet = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Set"), hash); +const randomHashCache = /*#__PURE__*/new WeakMap(); +const hashCache = /*#__PURE__*/new WeakMap(); +const visitedObjects = /*#__PURE__*/new WeakSet(); +function withVisitedTracking(obj, fn) { + if (visitedObjects.has(obj)) { + return string("[Circular]"); + } + visitedObjects.add(obj); + const result = fn(); + visitedObjects.delete(obj); + return result; +} +//# sourceMappingURL=Hash.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + HR: symbol, + QK: structure, + YO: array, + Yj: string, + ai: number, + kg: combine, + tW: hash, + uN: structureKeys, + yT: random +}); + + +}, +"./node_modules/effect/dist/Inspectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/** + * Controls how values appear in logs and debugging output. + * + * Effect data types use `Inspectable` to provide stable string, JSON, and + * Node.js inspection output. This keeps custom values readable in logs, REPLs, + * test failures, and diagnostics. This module defines the Node inspect symbol, + * the `Inspectable` interface, safe conversion helpers, and shared prototype or + * class implementations for custom values. + * + * @since 2.0.0 + */ + + + +/** + * 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)" + * ``` + * + * @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 + * + * @category converting + * @since 4.0.0 + */ +const toJson = input => { + try { + input = (0,_Redactable_js__rspack_import_0/* .redact */.E$)(input); + if (_Predicate_js__rspack_import_1/* .hasProperty */.i5(input, "toJSON") && _Predicate_js__rspack_import_1/* .isFunction */.Tn(input["toJSON"]) && input["toJSON"].length === 0) { + return input.toJSON(); + } else if (Array.isArray(input)) { + return input.map(toJson); + } + return input; + } catch { + return "[toJSON threw]"; + } +}; +/** + * Converts an unknown value to a string for diagnostics. + * + * **When to use** + * + * Use to produce a diagnostic string from a value whose runtime type is unknown. + * + * **Details** + * + * Strings are returned unchanged. Objects are formatted as JSON using the + * provided whitespace setting when possible, and values that cannot be + * formatted are converted with `String`. + * + * @category converting + * @since 2.0.0 + */ +const toStringUnknown = (u, whitespace = 2) => { + if (typeof u === "string") { + return u; + } + try { + return typeof u === "object" ? (0,_Formatter_js__rspack_import_2/* .formatJson */.IB)(u, { + space: whitespace + }) : (0,_Formatter_js__rspack_import_2/* .format */.GP)(u, { + space: whitespace + }); + } catch { + return String(u); + } +}; +/** + * A base prototype object that implements the {@link Inspectable} interface. + * + * **When to use** + * + * Use as a prototype for plain objects that should share standard inspectable behavior. + * + * **Details** + * + * This object provides default implementations for the {@link Inspectable} methods. + * It can be used as a prototype for objects that want to be inspectable, + * or as a mixin to add inspection capabilities to existing objects. + * + * **Example** (Using the base inspectable prototype) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * // Use as prototype + * const myObject = Object.create(Inspectable.BaseProto) + * myObject.name = "example" + * myObject.value = 42 + * + * myObject.toString() // => "\"[toJSON threw]\"" + * + * // Or extend in a constructor + * function MyClass(this: any, name: string) { + * this.name = name + * } + * MyClass.prototype = Object.create(Inspectable.BaseProto) + * MyClass.prototype.constructor = MyClass + * ``` + * + * @category prototypes + * @since 2.0.0 + */ +const BaseProto = (/* unused pure expression or super */ null && ({ + toJSON() { + return toJson(this); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + }, + toString() { + return format(this.toJSON()); + } +})); +/** + * Provides an abstract base class that implements the Inspectable interface. + * + * **When to use** + * + * Use as a base class for inspectable objects that define their own JSON representation. + * + * **Details** + * + * This class provides a convenient way to create inspectable objects by extending it. + * Subclasses only need to implement the `toJSON()` method, and they automatically + * get proper `toString()` and Node.js inspection support. + * + * **Example** (Extending the inspectable base class) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * class User extends Inspectable.Class { + * constructor( + * public readonly id: number, + * public readonly name: string, + * public readonly email: string + * ) { + * super() + * } + * + * toJSON() { + * return { + * _tag: "User", + * id: this.id, + * name: this.name, + * email: this.email + * } + * } + * } + * + * const user = new User(1, "Alice", "alice@example.com") + * user.toString() // => "{\"_tag\":\"User\",\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\"}" + * user[Inspectable.NodeInspectSymbol]() // => { _tag: "User", id: 1, name: "Alice", email: "alice@example.com" } + * ``` + * + * @category models + * @since 2.0.0 + */ +class Class { + /** + * Node.js custom inspection method. + * + * **When to use** + * + * Use to expose the class JSON representation to Node.js inspection. + * + * @since 2.0.0 + */ + [NodeInspectSymbol]() { + return this.toJSON(); + } + /** + * Returns a formatted string representation of this object. + * + * **When to use** + * + * Use to format the class JSON representation as a string. + * + * @since 2.0.0 + */ + toString() { + return format(this.toJSON()); + } +} +//# sourceMappingURL=Inspectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + FX: NodeInspectSymbol, + ZK: toStringUnknown, + aB: toJson +}); + + +}, +"./node_modules/effect/dist/Iterable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Works with JavaScript values that implement `[Symbol.iterator]`. + * + * Iterables include arrays, strings, generators, sets, and custom lazy + * sequences. The helpers in this module let code transform, search, group, and + * fold iterable values while preserving the input as an iterable instead of + * forcing an array first. + * + * @since 2.0.0 + */ + + + + + + + +/** + * Creates an iterable by applying a function to consecutive integers. + * + * **Details** + * + * The function is called with each index starting from `0`. If no length is + * specified, the iterable is infinite. This is useful for generating + * sequences, patterns, or any indexed data. + * + * **Example** (Generating values by index) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Generate first 5 even numbers + * const evens = Iterable.makeBy((n) => n * 2, { length: 5 }) + * Array.from(evens) // => [0, 2, 4, 6, 8] + * + * // Generate squares + * const squares = Iterable.makeBy((n) => n * n, { length: 4 }) + * Array.from(squares) // => [0, 1, 4, 9] + * + * // Infinite sequence (be careful when consuming!) + * const naturals = Iterable.makeBy((n) => n) + * const first10 = Iterable.take(naturals, 10) + * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeBy = (f, options) => { + const max = options?.length !== undefined ? Math.max(1, Math.floor(options.length)) : Infinity; + return { + [Symbol.iterator]() { + let i = 0; + return { + next() { + if (i < max) { + return { + value: f(i++), + done: false + }; + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns an iterable of integers starting at `start` and increasing by `1`. + * + * **Details** + * + * When `end` is provided and `start <= end`, both endpoints are included. When + * `end` is omitted, the iterable is unbounded. When `start > end`, the + * iterable contains only `start`. + * + * **Example** (Creating a range) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.range(1, 3)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const range = (start, end) => { + if (end === undefined) { + return makeBy(i => start + i); + } + return makeBy(i => start + i, { + length: start <= end ? end - start + 1 : 1 + }); +}; +/** + * Returns a `Iterable` containing a value repeated the specified number of times. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Repeating a value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.replicate("a", 3)) // => ["a", "a", "a"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const replicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (a, n) => makeBy(() => a, { + length: n +})))); +/** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value + * @category constructors + * @since 4.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => flatten(makeBy(() => self, { + length: n +}))))); +/** + * Repeats an iterable without an upper bound. + * + * **When to use** + * + * Use to cycle a reusable iterable without an upper bound when a downstream + * consumer controls how many values are taken. + * + * **Gotchas** + * + * The returned iterable is lazy and should usually be bounded with `take` or + * another terminating consumer before materializing it. + * + * @see {@link repeat} for repeating an iterable a specific number of times + * @see {@link take} for bounding the unbounded result before materializing it + * + * @category constructors + * @since 4.0.0 + */ +const forever = self => repeat(self, Infinity); +/** + * Takes a record and returns an Iterable of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Array.from(Iterable.fromRecord(x)) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = self => ({ + *[Symbol.iterator]() { + for (const key in self) { + if (Object.hasOwn(self, key)) { + yield [key, self[key]]; + } + } + } +}); +/** + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 3, 4] + * const withOne = Iterable.prepend(numbers, 1) + * Array.from(withOne) // => [1, 2, 3, 4] + * + * // Works with any iterable + * const letters = "abc" + * const withZ = Iterable.prepend(letters, "z") + * Array.from(withZ) // => ["z", "a", "b", "c"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => prependAll(self, [head])))); +/** + * Prepends the specified prefix iterable to the beginning of the specified iterable. + * + * **Example** (Prepending another iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.prependAll([1, 2], ["a", "b"])) // => ["a", "b", 1, 2] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => appendAll(that, self)))); +/** + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => appendAll(self, [last])))); +/** + * Concatenates two iterables, combining their elements. + * + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6] + * + * // Works with different iterable types + * const numbers = [1, 2] + * const letters = "abc" + * const mixed = Iterable.appendAll(numbers, letters) + * Array.from(mixed) // => [1, 2, "a", "b", "c"] + * + * // Lazy evaluation - only consumes what's needed + * const infinite = Iterable.range(1) + * const finite = [0, -1, -2] + * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2] + * ``` + * + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => ({ + [Symbol.iterator]() { + const iterA = self[Symbol.iterator](); + let doneA = false; + let iterB; + return { + next() { + if (!doneA) { + const r = iterA.next(); + if (r.done) { + doneA = true; + iterB = that[Symbol.iterator](); + return iterB.next(); + } + return r; + } + return iterB.next(); + } + }; + } +})))); +/** + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Running sum of numbers + * const numbers = [1, 2, 3, 4, 5] + * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n) + * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15] + * + * // Build strings progressively + * const letters = ["a", "b", "c"] + * const progressive = Iterable.scan(letters, "", (acc, letter) => acc + letter) + * Array.from(progressive) // => ["", "a", "ab", "abc"] + * + * // Track maximum values seen so far + * const values = [3, 1, 4, 1, 5, 9, 2] + * const runningMax = Iterable.scan(values, -Infinity, Math.max) + * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => ({ + [Symbol.iterator]() { + let acc = b; + let iterator; + function next() { + if (iterator === undefined) { + iterator = self[Symbol.iterator](); + return { + done: false, + value: acc + }; + } + const result = iterator.next(); + if (result.done) { + return result; + } + acc = f(acc, result.value); + return { + done: false, + value: acc + }; + } + return { + next + }; + } +})))); +/** + * Checks whether an `Iterable` is empty. + * + * **Example** (Checking for emptiness) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.isEmpty([]) // => true + * Iterable.isEmpty([1, 2, 3]) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmpty = self => { + const iterator = self[Symbol.iterator](); + return iterator.next().done === true; +}; +/** + * Returns the number of elements in a `Iterable`. + * + * **Example** (Counting iterable elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.size(numbers) // => 5 + * + * const empty = Iterable.empty() + * Iterable.size(empty) // => 0 + * + * // Works with any iterable + * const letters = "hello" + * Iterable.size(letters) // => 5 + * + * // Note: This consumes the entire iterable + * const range = Iterable.range(1, 100) + * Iterable.size(range) // => 100 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => { + const iterator = self[Symbol.iterator](); + let count = 0; + while (!iterator.next().done) { + count++; + } + return count; +}; +/** + * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.head(numbers) // => Option.some(1) + * + * const empty = Iterable.empty() + * Iterable.head(empty) // => Option.none() + * + * // Safe way to get first element + * const firstEven = Iterable.head( + * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0) + * ) + * firstEven // => Option.some(4) + * + * // Use with Option methods + * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2) + * doubled // => Option.some(10) + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + return result.done ? O.none() : O.some(result.value); +}; +/** + * Gets the first element of an `Iterable` without returning an `Option`. + * + * **When to use** + * + * Use when the `Iterable` is known to be non-empty and direct access to the + * first element is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the `Iterable` is empty. + * + * **Example** (Getting the first element unsafely) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.headUnsafe(numbers) // => 1 + * + * const letters = "hello" + * Iterable.headUnsafe(letters) // => "h" + * + * // Iterable.headUnsafe(Iterable.empty()) + * // throws Error: "headUnsafe: empty iterable" + * + * // Use only when you're certain the iterable is non-empty + * const nonEmpty = Iterable.range(1, 10) + * Iterable.headUnsafe(nonEmpty) // => 1 + * ``` + * + * @category getters + * @since 4.0.0 + */ +const headUnsafe = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + if (result.done) throw new Error("headUnsafe: empty iterable"); + return result.value; +}; +/** + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const firstThree = Iterable.take(numbers, 3) + * Array.from(firstThree) // => [1, 2, 3] + * + * // Taking more than available returns all elements + * const firstTen = Iterable.take(numbers, 10) + * Array.from(firstTen) // => [1, 2, 3, 4, 5] + * + * // Taking 0 or negative returns empty + * const none = Iterable.take(numbers, 0) + * Array.from(none) // => [] + * + * // Useful with infinite iterables + * const naturals = Iterable.range(1) + * const firstFive = Iterable.take(naturals, 5) + * Array.from(firstFive) // => [1, 2, 3, 4, 5] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + let i = 0; + const iterator = self[Symbol.iterator](); + return { + next() { + if (i < n) { + i++; + return iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 4, 6, 8, 3, 10, 12] + * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0) + * Array.from(evenPrefix) // => [2, 4, 6, 8] + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3) + * Array.from(firstThreeByIndex) // => ["a", "b", "c"] + * + * // Stops at first non-matching element + * const mixed = [1, 3, 5, 4, 7, 9] + * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1) + * Array.from(oddPrefix) // => [1, 3, 5] + * + * // Type refinement + * const values: Array = ["a", "b", "c", 1, "d"] + * const stringPrefix = Iterable.takeWhile( + * values, + * (x): x is string => typeof x === "string" + * ) + * Array.from(stringPrefix) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done || !predicate(result.value, i++)) { + return { + done: true, + value: undefined + }; + } + return result; + } + }; + } +})))); +/** + * Drops a max number of elements from the start of an `Iterable` + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const withoutFirstTwo = Iterable.drop(numbers, 2) + * Array.from(withoutFirstTwo) // => [3, 4, 5] + * + * // Dropping more than available returns empty + * const withoutFirstTen = Iterable.drop(numbers, 10) + * Array.from(withoutFirstTen) // => [] + * + * // Dropping 0 or negative returns all elements + * const all = Iterable.drop(numbers, 0) + * Array.from(all) // => [1, 2, 3, 4, 5] + * + * // Combine with take for slicing + * const slice = Iterable.take(Iterable.drop(numbers, 1), 3) + * Array.from(slice) // => [2, 3, 4] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + while (i < n) { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + i++; + } + return iterator.next(); + } + }; + } +})))); +/** + * Returns the first element that satisfies the specified + * predicate, or `None` if no such element exists. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8] + * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) + * firstEven // => Option.some(4) + * + * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10) + * firstGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d"] + * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0) + * atEvenIndex // => Option.some("a") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world"] + * const firstString = Iterable.findFirst( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * firstString // => Option.some("hello") + * + * // Transform during search + * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => { + * const sqrt = Math.sqrt(x) + * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none() + * }) + * findSquareRoot // => Option.some(1) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if ((0,_Predicate_js__rspack_import_1/* .isBoolean */.Lm)(o)) { + if (o) { + return _Option_js__rspack_import_2.some(a); + } + } else { + if (_Option_js__rspack_import_2.isSome(o)) { + return o; + } + } + i++; + } + return _Option_js__rspack_import_2.none(); +}); +/** + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8, 2] + * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0) + * lastEven // => Option.some(2) + * + * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10) + * lastGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0) + * lastAtEvenIndex // => Option.some("e") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world", 3] + * const lastString = Iterable.findLast( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * lastString // => Option.some("world") + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + let last = O.none(); + for (const a of self) { + const o = f(a, i); + if (isBoolean(o)) { + if (o) { + last = O.some(a); + } + } else { + if (O.isSome(o)) { + last = o; + } + } + i++; + } + return last; +}))); +/** + * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. + * + * **Example** (Zipping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * const letters = ["a", "b", "c"] + * const zipped = Iterable.zip(numbers, letters) + * Array.from(zipped) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Different lengths - shorter one determines result length + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const partial = Iterable.zip(short, long) + * Array.from(partial) // => [[1, "a"], [2, "b"]] + * + * // Works with any iterables + * const range = Iterable.range(1, 3) + * const word = "abc" + * const mixed = Iterable.zip(range, word) + * Array.from(mixed) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Create indexed pairs + * const values = ["apple", "banana", "cherry"] + * const indices = Iterable.range(0, 2) + * const indexed = Iterable.zip(indices, values) + * Array.from(indexed) // => [[0, "apple"], [1, "banana"], [2, "cherry"]] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. + * + * **Example** (Zipping with a combining function) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Add corresponding elements + * const a = [1, 2, 3, 4] + * const b = [10, 20, 30, 40] + * const sums = Iterable.zipWith(a, b, (x, y) => x + y) + * Array.from(sums) // => [11, 22, 33, 44] + * + * // Combine strings + * const firstNames = ["John", "Jane", "Bob"] + * const lastNames = ["Doe", "Smith", "Johnson"] + * const fullNames = Iterable.zipWith( + * firstNames, + * lastNames, + * (first, last) => `${first} ${last}` + * ) + * Array.from(fullNames) // => ["John Doe", "Jane Smith", "Bob Johnson"] + * + * // Different lengths - stops at shorter + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const combined = Iterable.zipWith( + * short, + * long, + * (num, letter) => `${num}${letter}` + * ) + * Array.from(combined) // => ["1a", "2b"] + * + * // Complex transformations + * const prices = [10.99, 25.50, 5.00] + * const quantities = [2, 1, 3] + * const totals = Iterable.zipWith(prices, quantities, (price, qty) => { + * return Math.round(price * qty * 100) / 100 // round to 2 decimal places + * }) + * Array.from(totals) // => [21.98, 25.5, 15] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const selfIterator = self[Symbol.iterator](); + const thatIterator = that[Symbol.iterator](); + return { + next() { + const selfResult = selfIterator.next(); + const thatResult = thatIterator.next(); + if (selfResult.done || thatResult.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(selfResult.value, thatResult.value) + }; + } + }; + } +})))); +/** + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * + * If the input is a non-empty array, the result is also a non-empty array. + * + * **Example** (Interspersing separators) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Join numbers with separator + * const numbers = [1, 2, 3, 4] + * const withCommas = Iterable.intersperse(numbers, ",") + * Array.from(withCommas) // => [1, ",", 2, ",", 3, ",", 4] + * + * // Join words with spaces + * const words = ["hello", "world", "from", "effect"] + * const sentence = Iterable.intersperse(words, " ") + * Array.from(sentence).join("") // => "hello world from effect" + * + * // Empty iterable remains empty + * const empty = Iterable.empty() + * const stillEmpty = Iterable.intersperse(empty, "-") + * Array.from(stillEmpty) // => [] + * + * // Single element has no separators added + * const single = [42] + * const noSeparator = Iterable.intersperse(single, "|") + * Array.from(noSeparator) // => [42] + * + * // Build CSS-like strings + * const styles = ["color: red", "font-size: 14px", "margin: 10px"] + * const css = Iterable.intersperse(styles, "; ") + * Array.from(css).join("") // => "color: red; font-size: 14px; margin: 10px" + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let next = iterator.next(); + let emitted = false; + return { + next() { + if (next.done) { + return next; + } else if (emitted) { + emitted = false; + return { + done: false, + value: middle + }; + } + emitted = true; + const result = next; + next = iterator.next(); + return result; + } + }; + } +})))); +/** + * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function. + * + * **Example** (Checking membership with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Custom equivalence for objects + * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id + * const containsById = Iterable.containsWith(byId) + * + * const users = [{ id: 1 }, { id: 2 }] + * const hasUser1 = containsById(users, { id: 1 }) + * hasUser1 // => true + * + * // Case-insensitive string comparison + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive) + * + * const words = ["Hello", "World"] + * const hasHello = containsCaseInsensitive(words, "hello") + * hasHello // => true + * + * // Approximate number comparison + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const containsApprox = Iterable.containsWith(approxEqual) + * + * const values = [1.0, 2.0, 3.0] + * const hasAlmostTwo = containsApprox(values, 2.05) + * hasAlmostTwo // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.contains(numbers, 3) // => true + * Iterable.contains(numbers, 6) // => false + * + * const letters = "hello" + * Iterable.contains(letters, "l") // => true + * Iterable.contains(letters, "x") // => false + * + * // Works with any iterable + * const range = Iterable.range(1, 100) + * Iterable.contains(range, 50) // => true + * Iterable.contains(range, 150) // => false + * + * // Curried version + * const containsThree = Iterable.contains(3) + * containsThree([1, 2, 3]) // => true + * containsThree([4, 5, 6]) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of + * the `Iterable`. + * + * **Example** (Chunking an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + * const chunks = Iterable.chunksOf(numbers, 3) + * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + * + * // Last chunk can be shorter + * const uneven = [1, 2, 3, 4, 5, 6, 7] + * const chunks2 = Iterable.chunksOf(uneven, 3) + * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]] + * + * // Chunk size larger than iterable + * const small = [1, 2] + * const chunks3 = Iterable.chunksOf(small, 5) + * Array.from(chunks3) // => [[1, 2]] + * + * // Process data in batches + * const data = Iterable.range(1, 100) + * const batches = Iterable.chunksOf(data, 10) + * const batchSums = Iterable.map( + * batches, + * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n) + * ) + * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255] + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const safeN = Math.max(1, Math.floor(n)); + return { + [Symbol.iterator]() { + let iterator = self[Symbol.iterator](); + return { + next() { + if (iterator === undefined) { + return { + done: true, + value: undefined + }; + } + const chunk = []; + for (let i = 0; i < safeN; i++) { + const result = iterator.next(); + if (result.done) { + iterator = undefined; + return chunk.length === 0 ? { + done: true, + value: undefined + } : { + done: false, + value: chunk + }; + } + chunk.push(result.value); + } + return { + done: false, + value: chunk + }; + } + }; + } + }; +}))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group consecutive equal numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.groupWith(numbers, (a, b) => a === b) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * // Case-insensitive grouping of strings + * const words = ["Apple", "APPLE", "banana", "Banana", "cherry"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const groupedWords = Iterable.groupWith(words, caseInsensitive) + * Array.from(groupedWords) // => [["Apple", "APPLE"], ["banana", "Banana"], ["cherry"]] + * + * // Group by approximate equality + * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2 + * const groupedFloats = Iterable.groupWith(floats, approxEqual) + * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]] + * + * // Only groups consecutive elements + * const scattered = [1, 2, 1, 2, 1] + * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b) + * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]] + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let nextResult; + return { + next() { + let result; + if (nextResult !== undefined) { + if (nextResult.done) { + return { + done: true, + value: undefined + }; + } + result = nextResult; + nextResult = undefined; + } else { + result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + } + const chunk = [result.value]; + while (true) { + const next = iterator.next(); + if (next.done || !isEquivalent(result.value, next.value)) { + nextResult = next; + return { + done: false, + value: chunk + }; + } + chunk.push(next.value); + } + } + }; + } +})))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s. + * + * **Example** (Grouping consecutive elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.group(numbers) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * const letters = "aabbccaa" + * const groupedLetters = Iterable.group(letters) + * Array.from(groupedLetters) // => [["a", "a"], ["b", "b"], ["c", "c"], ["a", "a"]] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A", value: 1 }, + * { type: "A", value: 1 }, + * { type: "B", value: 2 }, + * { type: "A", value: 1 } + * ] + * const groupedObjects = Iterable.group(objects) + * Array.from(groupedObjects).length // => 3 + * // Note: Only consecutive equal objects are grouped together + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a key) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group by string length + * const words = ["a", "bb", "ccc", "dd", "eee", "f"] + * const byLength = Iterable.groupBy(words, (word) => word.length.toString()) + * byLength // => { "1": ["a", "f"], "2": ["bb", "dd"], "3": ["ccc", "eee"] } + * + * // Group by first letter + * const names = ["Alice", "Bob", "Charlie", "David", "Anna", "Betty"] + * const byFirstLetter = Iterable.groupBy(names, (name) => name[0]) + * byFirstLetter // => { A: ["Alice", "Anna"], B: ["Bob", "Betty"], C: ["Charlie"], D: ["David"] } + * + * // Group by category + * const items = [ + * { name: "apple", category: "fruit" }, + * { name: "carrot", category: "vegetable" }, + * { name: "banana", category: "fruit" }, + * { name: "broccoli", category: "vegetable" } + * ] + * const byCategory = Iterable.groupBy(items, (item) => item.category) + * Object.keys(byCategory) // => ["fruit", "vegetable"] + * + * // Group numbers by even/odd + * const numbers = [1, 2, 3, 4, 5, 6] + * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? "even" : "odd") + * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] } + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const constEmpty = { + [Symbol.iterator]() { + return constEmptyIterator; + } +}; +const constEmptyIterator = { + next() { + return { + done: true, + value: undefined + }; + } +}; +/** + * Creates an empty iterable that yields no elements. + * + * **When to use** + * + * Use when you need an empty iterable as a typed "no data" value or a base + * case for iterable operations. + * + * **Example** (Creating an empty iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.empty()) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => constEmpty; +/** + * Creates an iterable containing a single element. + * + * **When to use** + * + * Use to wrap a single value in an iterable context so it can be combined + * with other iterable operations. + * + * **Example** (Wrapping a single value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const single = Iterable.of(42) + * Array.from(single) // => [42] + * + * // Useful for creating homogeneous sequences + * const sequences = [ + * Iterable.of("hello"), + * Iterable.range(1, 3), + * Iterable.empty() + * ] + * + * // Can be used with flatMap for conditional inclusion + * const numbers = [1, 2, 3, 4, 5] + * const evensOnly = Iterable.flatMap( + * numbers, + * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty() + * ) + * Array.from(evensOnly) // => [2, 4] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element of an iterable using a function. + * + * **Details** + * + * This is one of the most fundamental operations for working with iterables. + * It applies a transformation function to each element, creating a new iterable + * with the transformed values. The operation is lazy, so elements are only + * transformed when the iterable is consumed. + * + * **Example** (Mapping elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Transform numbers to their squares + * const numbers = [1, 2, 3, 4, 5] + * const squares = Iterable.map(numbers, (x) => x * x) + * Array.from(squares) // => [1, 4, 9, 16, 25] + * + * // Use index in transformation + * const indexed = Iterable.map(["a", "b", "c"], (char, i) => `${i}: ${char}`) + * Array.from(indexed) // => ["0: a", "1: b", "2: c"] + * + * Array.from(Iterable.map( + * Iterable.map([1, 2, 3], (x) => x * 2), + * (x) => x + 1 + * )) // => [3, 5, 7] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(result.value, i++) + }; + } + }; + } +})))); +/** + * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. + * + * **Example** (Flat mapping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Expand each number to a range + * const numbers = [1, 2, 3] + * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n)) + * Array.from(expanded) // => [1, 1, 2, 1, 2, 3] + * + * // Split strings into characters + * const words = ["hi", "bye"] + * const chars = Iterable.flatMap(words, (word) => word) + * Array.from(chars) // => ["h", "i", "b", "y", "e"] + * + * // Conditional expansion with empty iterables + * const values = [1, 2, 3, 4, 5] + * const evenMultiples = Iterable.flatMap( + * values, + * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : [] + * ) + * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12] + * + * // Use index in transformation + * const letters = ["a", "b", "c"] + * const indexed = Iterable.flatMap( + * letters, + * (letter, i) => Iterable.replicate(letter, i + 1) + * ) + * Array.from(indexed) // => ["a", "b", "b", "c", "c", "c"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatten(map(self, f))))); +/** + * Flattens an Iterable of Iterables into a single Iterable + * + * **Example** (Flattening nested iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Flatten nested arrays + * const nested = [[1, 2], [3, 4], [5, 6]] + * const flat = Iterable.flatten(nested) + * Array.from(flat) // => [1, 2, 3, 4, 5, 6] + * + * // Flatten different iterable types + * const mixed: Array> = ["ab", "cd"] + * const flatMixed = Iterable.flatten(mixed) + * Array.from(flatMixed) // => ["a", "b", "c", "d"] + * + * // Flatten deeply nested (only one level) + * const deepNested = [[[1, 2]], [[3, 4]]] + * const oneLevelFlat = Iterable.flatten(deepNested) + * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]] + * // [[1, 2], [3, 4]] (still contains arrays) + * + * // Empty iterables are handled correctly + * const withEmpty = [[1, 2], [], [3, 4], []] + * const flatWithEmpty = Iterable.flatten(withEmpty) + * Array.from(flatWithEmpty) // => [1, 2, 3, 4] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = self => ({ + [Symbol.iterator]() { + const outerIterator = self[Symbol.iterator](); + let innerIterator; + function next() { + while (true) { + if (innerIterator === undefined) { + const next = outerIterator.next(); + if (next.done) { + return next; + } + innerIterator = next.value[Symbol.iterator](); + } + const result = innerIterator.next(); + if (!result.done) { + return result; + } + innerIterator = undefined; + } + } + return { + next + }; + } +}); +/** + * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. + * + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse strings to numbers, keeping only valid ones + * const strings = ["1", "2", "invalid", "4", "not-a-number"] + * const numbers = Iterable.filterMap(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 4] + * + * // Extract specific properties from objects + * const users = [ + * { name: "Alice", age: 25, email: "alice@example.com" }, + * { name: "Bob", age: 17, email: undefined }, + * { name: "Charlie", age: 30, email: "charlie@example.com" }, + * { name: "David", age: 16, email: undefined } + * ] + * const adultEmails = Iterable.filterMap( + * users, + * (user) => + * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid + * ) + * Array.from(adultEmails) // => ["alice@example.com", "charlie@example.com"] + * + * // Use index in transformation + * const items = ["a", "b", "c", "d", "e"] + * const evenIndexItems = Iterable.filterMap( + * items, + * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid + * ) + * Array.from(evenIndexItems) // => ["0: a", "2: c", "4: e"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Transforms all elements of the `Iterable` for as long as the specified function succeeds. + * + * **Example** (Filtering and transforming until failure) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse numbers until we hit an invalid one + * const strings = ["1", "2", "3", "invalid", "4", "5"] + * const numbers = Iterable.filterMapWhile(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 3] + * + * // Take elements while they meet a condition and transform them + * const values = [2, 4, 6, 7, 8, 10] + * const doubledEvens = Iterable.filterMapWhile( + * values, + * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid + * ) + * Array.from(doubledEvens) // => [4, 8, 12] + * + * // Process with index until condition fails + * const letters = ["a", "b", "c", "d", "e"] + * const indexedUntilC = Iterable.filterMapWhile( + * letters, + * (letter, i) => letter !== "c" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid + * ) + * Array.from(indexedUntilC) // => ["0: a", "1: b"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMapWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Retrieves the `Some` values from an `Iterable` of `Option`s. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (O.isSome(result.value)) { + return { + done: false, + value: result.value.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the failure values from an iterable of + * `Result`s, skipping successful results. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getFailures([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => ["err"] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isFailure(result.value)) { + return { + done: false, + value: result.value.failure + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the success values from an iterable of + * `Result`s, skipping failed results. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getSuccesses([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => [1, 2] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isSuccess(result.value)) { + return { + done: false, + value: result.value.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Filters an iterable to only include elements that match a predicate. + * + * **Details** + * + * This function creates a new iterable containing only the elements for which + * the predicate function returns true. Like map, this operation is lazy and + * elements are only tested when the iterable is consumed. + * + * **Example** (Filtering elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Filter even numbers + * const numbers = [1, 2, 3, 4, 5, 6] + * const evens = Iterable.filter(numbers, (x) => x % 2 === 0) + * Array.from(evens) // => [2, 4, 6] + * + * // Filter with index + * const items = ["a", "b", "c", "d"] + * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1) + * Array.from(oddPositions) // => ["b", "d"] + * + * // Type refinement + * const mixed: Array = ["hello", 42, "world", 100] + * const onlyStrings = Iterable.filter( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * Array.from(onlyStrings) // => ["hello", "world"] + * + * // Combine with map + * const processed = Iterable.map( + * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2), + * (x) => x * 10 + * ) + * Array.from(processed) // => [30, 40, 50] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (predicate(result.value, i++)) { + return { + done: false, + value: result.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})); +/** + * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. + * + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (Flat mapping nullable results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Extract valid elements from nullable function results + * const data = ["1", "2", "invalid", "4"] + * const parsed = Iterable.flatMapNullishOr(data, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? null : num * 2 + * }) + * Array.from(parsed) // => [2, 4, 8] + * + * // Safe property access + * const objects = [ + * { nested: { value: 10 } }, + * { nested: null }, + * { nested: { value: 20 } }, + * {} + * ] + * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value) + * Array.from(values) // => [10, 20] + * + * // Working with Map.get (returns undefined for missing keys) + * const map = new Map([ + * ["a", 1], + * ["b", 2], + * ["c", 3] + * ]) + * const keys = ["a", "x", "b", "y", "c"] + * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key)) + * Array.from(foundValues) // => [1, 2, 3] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => filterMap(self, a => { + const b = f(a); + return b == null ? R.failVoid : R.succeed(b); +})))); +/** + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 3, 5, 7, 8] + * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0) + * hasEven // => true + * + * const allOdd = [1, 3, 5, 7] + * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0) + * hasEvenInAllOdd // => false + * + * // With index + * const letters = ["a", "b", "c"] + * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2) + * hasElementAtIndex2 // => true + * + * // Early termination - stops at first match + * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1) + * const hasEvenInInfiniteOdds = Iterable.some( + * Iterable.take(infiniteOdds, 1000), + * (x) => x % 2 === 0 + * ) + * hasEvenInInfiniteOdds // => false + * + * // Type guard usage + * const mixed: Array = [1, 2, "hello"] + * const hasString = Iterable.some( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * hasString // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i++)) { + return true; + } + } + return false; +}))); +/** + * Generates an iterable by repeatedly applying a function that produces the + * next element and state. + * + * **Details** + * + * This is useful for creating iterables from a generating function that + * maintains state. The function should return `Option.some([value, nextState])` + * to continue or `Option.none()` to stop. + * + * **Example** (Unfolding state into values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * // Generate Fibonacci sequence + * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]])) + * const first10Fib = Iterable.take(fibonacci, 10) + * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + * + * // Generate powers of 2 up to a limit + * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none()) + * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + * + * // Generate countdown + * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none()) + * Array.from(countdown) // => [5, 4, 3, 2, 1] + * + * // Generate collatz sequence + * const collatz = Iterable.unfold(7, (n) => { + * if (n === 1) return Option.none() + * const next = n % 2 === 0 ? n / 2 : n * 3 + 1 + * return Option.some([n, next]) + * }) + * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => ({ + [Symbol.iterator]() { + let next = b; + return { + next() { + const ab = f(next); + if (O.isNone(ab)) { + return { + done: true, + value: undefined + }; + } + const [a, b] = ab.value; + next = b; + return { + done: false, + value: a + }; + } + }; + } +}); +/** + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Collect each visited element + * const numbers = [1, 2, 3, 4, 5] + * const visited: Array = [] + * Iterable.forEach(numbers, (n) => visited.push(n)) + * visited // => [1, 2, 3, 4, 5] + * + * // Use index in the callback + * const letters = ["a", "b", "c"] + * const indexed: Array = [] + * Iterable.forEach(letters, (letter, i) => { + * indexed.push(`${i}: ${letter}`) + * }) + * indexed // => ["0: a", "1: b", "2: c"] + * + * // Side effects with any iterable + * const results: Array = [] + * Iterable.forEach(Iterable.range(1, 5), (n) => { + * results.push(n * n) + * }) + * results // => [1, 4, 9, 16, 25] + * + * // Process in chunks + * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2) + * const processed: Array> = [] + * Iterable.forEach(data, (chunk) => { + * processed.push(Array.from(chunk)) + * }) + * processed // => [[1, 2], [3, 4], [5, 6]] + * ``` + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + f(a, i++); + } +}))); +/** + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** + * + * This function applies a reducing function against an accumulator and each element + * of the iterable (from left to right) to reduce it to a single value. + * + * **Example** (Reducing an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Sum all numbers + * const numbers = [1, 2, 3, 4, 5] + * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n) + * sum // => 15 + * + * // Find maximum value + * const values = [3, 1, 4, 1, 5, 9, 2] + * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9 + * + * // Build an object from key-value pairs + * const pairs = [["a", 1], ["b", 2], ["c", 3]] as const + * const obj = Iterable.reduce( + * pairs, + * {} as Record, + * (acc, [key, value]) => { + * acc[key] = value + * return acc + * } + * ) + * obj // => { a: 1, b: 2, c: 3 } + * + * // Use index in the reducer + * const letters = ["a", "b", "c"] + * const indexed = Iterable.reduce( + * letters, + * [] as Array, + * (acc, letter, i) => { + * acc.push(`${i}: ${letter}`) + * return acc + * } + * ) + * indexed // => ["0: a", "1: b", "2: c"] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + if (Array.isArray(self)) { + return self.reduce(f, b); + } + let i = 0; + let result = b; + for (const n of self) { + result = f(result, n, i++); + } + return result; +}))); +/** + * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. + * + * **Example** (Deduplicating adjacent elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicates with custom equality + * const numbers = [1, 1, 2, 2, 3, 1, 1] + * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b) + * Array.from(dedupedNumbers) // => [1, 2, 3, 1] + * + * // Case-insensitive deduplication + * const words = ["Hello", "HELLO", "world", "World", "test"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive) + * Array.from(dedupedWords) // => ["Hello", "world", "test"] + * + * // Deduplication by object property + * const users = [ + * { id: 1, name: "Alice" }, + * { id: 1, name: "Alice Updated" }, // different name, same id + * { id: 2, name: "Bob" }, + * { id: 2, name: "Bob" }, + * { id: 3, name: "Charlie" } + * ] + * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id + * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId) + * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3] + * + * // Approximate numeric equality + * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual) + * Array.from(dedupedFloats) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let first = true; + let last; + function next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + if (first) { + first = false; + last = result.value; + return result; + } + const current = result.value; + if (isEquivalent(last, current)) { + return next(); + } + last = current; + return result; + } + return { + next + }; + } +})))); +/** + * Deduplicates adjacent elements that are identical. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicate numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const deduped = Iterable.dedupeAdjacent(numbers) + * Array.from(deduped) // => [1, 2, 3, 1] + * + * // Remove adjacent duplicate characters + * const letters = "aabbccaa" + * const dedupedLetters = Iterable.dedupeAdjacent(letters) + * Array.from(dedupedLetters) // => ["a", "b", "c", "a"] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A" }, + * { type: "A" }, + * { type: "B" }, + * { type: "B" }, + * { type: "A" } + * ] + * const dedupedObjects = Iterable.dedupeAdjacent(objects) + * Array.from(dedupedObjects, (object) => object.type) // => ["A", "B", "A"] + * + * // Clean up streaming data + * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100] + * const cleanedData = Iterable.dedupeAdjacent(sensorData) + * Array.from(cleanedData) // => [100, 101, 102, 100] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Zips this Iterable crosswise with the specified Iterable using the specified combiner. + * + * **Example** (Combining cartesian products) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Create coordinate pairs + * const xs = [1, 2] + * const ys = ["a", "b", "c"] + * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`) + * Array.from(coordinates) // => ["(1,a)", "(1,b)", "(1,c)", "(2,a)", "(2,b)", "(2,c)"] + * + * // Generate all combinations of options + * const sizes = ["S", "M", "L"] + * const colors = ["red", "blue"] + * const products = Iterable.cartesianWith( + * sizes, + * colors, + * (size, color) => ({ size, color }) + * ) + * Array.from(products, ({ color, size }) => `${size}:${color}`) // => ["S:red", "S:blue", "M:red", "M:blue", "L:red", "L:blue"] + * + * // Mathematical operations on all pairs + * const a = [1, 2, 3] + * const b = [10, 20] + * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y) + * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60] + * + * // Create test data combinations + * const userTypes = ["admin", "user"] + * const features = ["read", "write", "delete"] + * const testCases = Iterable.cartesianWith( + * userTypes, + * features, + * (user, feature) => `${user}_can_${feature}` + * ) + * Array.from(testCases) // => ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const cache = []; + let iterator; + let done = false; + const replay = { + [Symbol.iterator]() { + let index = 0; + return { + next() { + if (index < cache.length) { + return { + done: false, + value: cache[index++] + }; + } + if (done) { + return { + done: true, + value: undefined + }; + } + iterator ??= that[Symbol.iterator](); + const result = iterator.next(); + if (result.done) { + done = true; + return { + done: true, + value: undefined + }; + } + cache.push(result.value); + index++; + return result; + } + }; + } + }; + return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator](); + } +})))); +/** + * Zips this Iterable crosswise with the specified Iterable. + * + * **Example** (Generating cartesian pairs) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // All pairs of numbers and letters + * const numbers = [1, 2, 3] + * const letters = ["a", "b"] + * const pairs = Iterable.cartesian(numbers, letters) + * Array.from(pairs) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]] + * + * // Generate coordinate grid + * const x = [0, 1, 2] + * const y = [0, 1] + * const grid = Iterable.cartesian(x, y) + * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]] + * + * // All combinations for testing + * const browsers = ["chrome", "firefox"] + * const devices = ["desktop", "mobile", "tablet"] + * const testMatrix = Iterable.cartesian(browsers, devices) + * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => ["chrome:desktop", "chrome:mobile", "chrome:tablet", "firefox:desktop", "firefox:mobile", "firefox:tablet"] + * + * // Empty iterable results in empty cartesian product + * const empty = Iterable.empty() + * const withEmpty = Iterable.cartesian([1, 2], empty) + * Array.from(withEmpty) // => [] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +/** + * Computes how many elements of the iterable pass the given predicate. + * + * **Example** (Counting matching elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + let i = 0; + for (const a of self) { + if (f(a, i)) { + count++; + } + i++; + } + return count; +}))); +//# sourceMappingURL=Iterable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + BK: headUnsafe, + i8: findFirst, + pb: filter +}); + + +}, +"./node_modules/effect/dist/Latch.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + +/** + * Creates a `Latch` synchronously, outside of `Effect`. + * + * **When to use** + * + * Use when you need to allocate a `Latch` synchronously outside an Effect + * workflow. + * + * **Details** + * + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch unsafely) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Latch } from "effect" + * + * const latch = Latch.makeUnsafe(false) + * const waiter = latch.await.pipe(Effect.as("opened")) + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild(waiter) + * yield* latch.open + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "opened" + * ``` + * + * @see {@link make} for creating a latch inside Effect code + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = _internal_effect_js__rspack_import_0/* .makeLatchUnsafe */.zzk; +/** + * Creates a `Latch` inside `Effect`. + * + * **When to use** + * + * Use to create a latch for coordinating fibers inside Effect code. + * + * **Details** + * + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, Latch } from "effect" + * + * const program = Effect.gen(function*() { + * const latch = yield* Latch.make(false) + * const waiter = latch.await.pipe(Effect.as("opened")) + * + * const fiber = yield* Effect.forkChild(waiter) + * yield* latch.open + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "opened" + * ``` + * + * @see {@link makeUnsafe} for synchronous allocation outside Effect code + * + * @category constructors + * @since 4.0.0 + */ +const make = _internal_effect_js__rspack_import_0/* .makeLatch */.Fbb; +/** + * Opens the latch and releases fibers waiting on it. + * + * **When to use** + * + * Use to open a latch and release all fibers that are waiting on it. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from closed to open, or `false` if it was already open. + * + * @see {@link openUnsafe} for a synchronous variant + * @see {@link release} to release waiting fibers without opening the latch + * + * @category combinators + * @since 4.0.0 + */ +const open = self => self.open; +/** + * Opens the latch synchronously and releases fibers waiting on it. + * + * **When to use** + * + * Use when you need synchronous code to open a latch immediately and release + * the fibers waiting on it. + * + * **Details** + * + * Returns `true` when this call changed the latch from closed to open, or + * `false` if it was already open. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link open} for the effectful variant + * @see {@link release} to release waiting fibers without opening the latch + * @see {@link closeUnsafe} for the synchronous inverse operation + * + * @category unsafe + * @since 4.0.0 + */ +const openUnsafe = self => self.openUnsafe(); +/** + * Releases the fibers currently waiting on a closed latch without opening it. + * + * **When to use** + * + * Use to let the fibers currently waiting on a latch proceed while keeping the + * latch closed for future waiters. + * + * **Details** + * + * The returned effect succeeds with `true` when release was requested while + * the latch was closed, or `false` if the latch was already open. Future + * waiters still suspend until the latch is opened or released again. + * + * @see {@link open} for opening the latch for current and future waiters + * + * @category combinators + * @since 4.0.0 + */ +const release = self => self.release; +const _await = self => self.await; + +/** + * Closes the latch so future `await` and `whenOpen` calls suspend. + * + * **When to use** + * + * Use to re-enable waiting on a latch after it was opened, so later `await` + * and `whenOpen` calls suspend again. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from open to closed, or `false` if it was already closed. + * + * @see {@link closeUnsafe} for a synchronous variant + * @see {@link open} for opening the latch for current and future waiters + * + * @category combinators + * @since 4.0.0 + */ +const close = self => self.close; +/** + * Closes the latch synchronously so future `await` and `whenOpen` calls + * suspend. + * + * **When to use** + * + * Use to close a latch synchronously when the state change must happen outside + * an `Effect`. + * + * **Details** + * + * Returns `true` when this call changed the latch from open to closed, or + * `false` if it was already closed. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link close} for the effectful variant + * @see {@link openUnsafe} to synchronously open the latch and release waiting + * fibers + * + * @category unsafe + * @since 4.0.0 + */ +const closeUnsafe = self => self.closeUnsafe(); +/** + * Waits on the latch, then runs the provided effect. + * + * **When to use** + * + * Use to gate another effect so it starts only after the latch is opened or + * the current waiters are released. + * + * **Details** + * + * If the latch is open, the effect runs immediately. If it is closed, the + * returned effect suspends until the latch is opened or the current waiters are + * released. The provided effect's success, failure, and requirements are + * preserved. + * + * @see `await` for waiting without running another effect + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch + * + * @category combinators + * @since 4.0.0 + */ +const whenOpen = (...args) => { + if (args.length === 1) { + const [self] = args; + return effect => self.whenOpen(effect); + } + const [self, effect] = args; + return self.whenOpen(effect); +}; +/** + * Checks whether the latch is currently open or closed. + * + * **When to use** + * + * Use to check the state of the latch without suspending or changing its state. + * + * @category predicates + * @since 4.0.0 + */ +const isOpen = self => self.isOpen(); +//# sourceMappingURL=Latch.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L8: make, + LZ: makeUnsafe +}); + + +}, +"./node_modules/effect/dist/Layer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Deferred_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Deferred.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Scope_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Scope.js"); + + + + + + + + + + + + +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const memoMapReuse = (entry, scope) => { + entry.observers++; + return _internal_effect_js__rspack_import_0/* .andThen */.hgn(_internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, exit => entry.finalizer(exit)), entry.effect); +}; +/** + * Returns `true` if the specified value is a `Layer`, `false` otherwise. + * + * **Example** (Checking whether a value is a layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * const notALayer = { someProperty: "value" } + * + * Layer.isLayer(dbLayer) // => true + * Layer.isLayer(notALayer) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isLayer = u => hasProperty(u, TypeId); +const LayerProto = { + [TypeId]: { + _ROut: _Function_js__rspack_import_1/* .identity */.D_, + _E: _Function_js__rspack_import_1/* .identity */.D_, + _RIn: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_2/* .pipeArguments */.tT)(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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuild = build => fromBuildUnsafe((memoMap, scope) => { + const layerScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope); + return _internal_effect_js__rspack_import_0/* .onExit */.cfM(build(memoMap, layerScope), exit => exit._tag === "Failure" ? _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit) : _internal_effect_js__rspack_import_0/* ["void"] */.rIH); +}); +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuildMemo = build => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +const memoMapBuild = (memoMap, layer, scope, build) => { + const layerScope = _Scope_js__rspack_import_3/* .makeUnsafe */.LZ(); + const deferred = _Deferred_js__rspack_import_4/* .makeUnsafe */.LZ(); + const entry = { + observers: 1, + effect: _Deferred_js__rspack_import_4/* ["await"] */.Tx(deferred), + finalizer: exit => _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + entry.observers--; + if (entry.observers === 0) { + memoMap.map.delete(layer); + return _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit); + } + return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + }) + }; + memoMap.map.set(layer, entry); + return _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, entry.finalizer).pipe(_internal_effect_js__rspack_import_0/* .flatMap */.qIB(() => build(memoMap, layerScope)), _internal_effect_js__rspack_import_0/* .onExit */.cfM(exit => { + entry.effect = exit; + return _Deferred_js__rspack_import_4/* .done */.Vw(deferred, exit); + })); +}; +class MemoMapImpl { + 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) { + return memoMapReuse(local, scope); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + const existing = this.get(layer, scope); + if (existing) { + return existing; + } + return memoMapBuild(this, layer, scope, build); + }); + } +} +/** + * 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" + * ``` + * + * @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 + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMapUnsafe = parent => new MemoMapImpl(parent); +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a memo map safely within an Effect + * const program = Effect.gen(function*() { + * const memoMap = yield* Layer.makeMemoMap + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeMemoMap = /*#__PURE__*/(/* unused pure expression or super */ null && (internalEffect.sync(makeMemoMapUnsafe))); +/** + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. + * + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMap = parent => internalEffect.sync(() => forkMemoMapUnsafe(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 + * + * @category services + * @since 3.13.0 + */ +class CurrentMemoMap extends /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl()("effect/Layer/CurrentMemoMap") { + static forkOrCreate(self) { + const current = _Context_js__rspack_import_5/* .getOrUndefined */.Y6(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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithMemoMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, memoMap, scope) => _internal_effect_js__rspack_import_0/* .provideService */.PfK(_internal_effect_js__rspack_import_0/* .map */.TjK(self.build(memoMap, scope), _Context_js__rspack_import_5/* .add */.WQ(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** + * Builds a layer into a scoped value. + * + * **Example** (Building a layer into a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Build a layer to get its services + * const program = Effect.gen(function*() { + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * + * // Build the layer into Context - automatically manages scope and memoization + * const context = yield* Layer.build(dbLayer) + * + * // Extract the specific service from the built layer + * const database = Context.get(context, Database) + * + * return yield* database.query("SELECT * FROM users") + * }) + * + * Effect.runSync(Effect.scoped(program)) // => "result" + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const build = self => core.withFiber(fiber => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), Context.getUnsafe(fiber.context, Scope.Scope))); +/** + * 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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithScope = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, scope) => _internal_core_js__rspack_import_6/* .withFiber */.R6(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 + * + * @category constructors + * @since 2.0.0 + */ +const succeed = function () { + if (arguments.length === 1) { + return resource => succeedContext(Context.make(arguments[0], resource)); + } + return succeedContext(Context.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 + * + * @category constructors + * @since 2.0.0 + */ +const succeedContext = context => fromBuildUnsafe(constant(internalEffect.succeed(context))); +/** + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. + * + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. + * + * **Example** (Disabling optional lifecycle work) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Option } from "effect" + * + * const Service = Context.Service("Service") + * const context = Effect.runSync(Effect.scoped(Layer.build(Layer.empty))) + * Context.getOption(context, Service) // => Option.none() + * ``` + * + * @see {@link effectDiscard} for running an effect while providing no services + * + * @category constructors + * @since 2.0.0 + */ +const empty = /*#__PURE__*/(/* unused pure expression or super */ null && (succeedContext(/*#__PURE__*/Context.empty()))); +/** + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeed` where the service value is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.sync(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 succeed} for constructing layers from static values + * + * @category constructors + * @since 2.0.0 + */ +const sync = function () { + if (arguments.length === 1) { + return evaluate => syncContext(() => Context.make(arguments[0], evaluate())); + } + return syncContext(() => Context.make(arguments[0], arguments[1]())); +}; +/** + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeedContext` where the `Context` is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.syncContext(() => + * 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 sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * + * @category constructors + * @since 2.0.0 + */ +const syncContext = evaluate => fromBuildMemo(constant(internalEffect.sync(evaluate))); +/** + * 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 + * + * @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(internalEffect.map(effect, value => Context.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 + * + * @category constructors + * @since 2.0.0 + */ +const effectContext = effect => fromBuildMemo((_, scope) => Scope.provide(effect, scope)); +/** + * Constructs a layer from an effect, discarding its value and providing no + * services. + * + * **When to use** + * + * Use when layer construction should run an Effect for its side effects while providing no + * services. + * + * **Example** (Running an effect during layer construction) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const logs: Array = [] + * const initLayer = Layer.effectDiscard( + * Effect.sync(() => { + * logs.push("Initializing application...") + * }) + * ) + * Effect.runSync(Effect.scoped(Layer.build(initLayer))) + * logs // => ["Initializing application..."] + * ``` + * + * @see {@link empty} for a no-op layer that performs no construction work + * + * @category constructors + * @since 2.0.0 + */ +const effectDiscard = effect => effectContext(internalEffect.as(effect, Context.empty())); +/** + * Constructs a layer lazily using the specified factory. + * + * **Details** + * + * The factory is evaluated only when the suspended layer is first built, and + * the result is memoized with normal layer sharing semantics. + * + * **Example** (Choosing a layer lazily) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const useProd = true + * + * const layer = Layer.suspend(() => + * useProd + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") + * ) + * Effect.runSync(Effect.provide(Config, layer)) // => "https://api.example.com" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = evaluate => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope))); +/** + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** + * + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. + * + * **Example** (Unwrapping an effectful layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layerEffect = Effect.succeed( + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * ) + * + * const unwrappedLayer = Layer.unwrap(layerEffect) + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, unwrappedLayer)) // => "result" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const unwrap = self => { + const service = Context.Service("effect/Layer/unwrap"); + return flatMap(effect(service)(self), Context.get(service)); +}; +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope, "parallel"); + return _internal_effect_js__rspack_import_0/* .forEach */.jJl(layers, layer => layer.build(memoMap, _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(parentScope, "sequential")), { + concurrency: layers.length + }).pipe(_internal_effect_js__rspack_import_0/* .map */.TjK(context => _Context_js__rspack_import_5/* .mergeAll */.Um(...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 + * + * @category zipping + * @since 2.0.0 + */ +const mergeAll = (...layers) => fromBuild((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 + * + * @category zipping + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => mergeAll(self, ...(Array.isArray(that) ? that : [that]))))); +const provideWith = (self, that, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), context => self.build(memoMap, scope).pipe(internalEffect.provideContext(context), internalEffect.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 + * + * @category providing services + * @since 2.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, identity)))); +/** + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) + * + * ```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") {} + * + * class UserService extends Context.Service Effect.Effect<{ + * id: string + * name: string + * }> + * }>()("UserService") {} + * + * // 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 and merge all services together + * const allServicesLayer = userServiceLayer.pipe( + * Layer.provideMerge(Layer.mergeAll(databaseLayer, loggerLayer)) + * ) + * + * // Now the resulting layer provides UserService, Database, AND Logger + * const program = Effect.gen(function*() { + * const userService = yield* UserService + * const logger = yield* Logger // Still available! + * const database = yield* Database // Still available! + * + * const user = yield* userService.getUser("123") + * yield* logger.log(`Found user: ${user.name}`) + * + * return user + * }).pipe( + * Effect.provide(allServicesLayer) + * ) + * Effect.runSync(program) // => { id: "123", name: "DB: SELECT * FROM users WHERE id = 123" } + * logs // => ["[LOG] Looking up user 123", "[LOG] Found user: DB: SELECT * FROM users WHERE id = 123"] + * ``` + * + * @see {@link provide} for keeping dependency services private + * + * @category providing services + * @since 2.0.0 + */ +const provideMerge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, (self, that) => Context.merge(that, self))))); +/** + * Constructs a layer dynamically based on the output of this layer. + * + * **Example** (Creating services from layer output) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Logger extends Context.Service Effect.Effect + * }>()("Logger") {} + * + * const logs: Array = [] + * + * // Base config layer + * const configLayer = Layer.succeed(Config, { + * dbUrl: "postgres://localhost:5432/mydb", + * logLevel: "debug" + * }) + * + * // Dynamically create services based on config + * const dynamicServiceLayer = configLayer.pipe( + * Layer.flatMap((context) => { + * const config = Context.get(context, Config) + * + * // Create database layer based on config + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => + * Effect.succeed( + * `Querying ${config.dbUrl}: ${sql}` + * )) + * }) + * + * // Create logger layer based on config + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => + * config.logLevel === "debug" + * ? Effect.sync(() => logs.push(`[DEBUG] ${msg}`)) + * : Effect.sync(() => logs.push(msg)) + * ) + * }) + * + * // Return combined layer + * return Layer.mergeAll(dbLayer, loggerLayer) + * }) + * ) + * + * // Use the dynamic services + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Starting database query") + * const result = yield* database.query("SELECT * FROM users") + * + * return result + * }).pipe( + * Effect.provide(dynamicServiceLayer) + * ) + * Effect.runSync(program) // => "Querying postgres://localhost:5432/mydb: SELECT * FROM users" + * logs // => ["[DEBUG] Starting database query"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => f(context).build(memoMap, scope)))))); +/** + * Performs the specified effect if this layer succeeds. + * + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => Scope.provide(internalEffect.as(f(context), context), scope)))))); +/** + * Performs the specified effect if this layer fails. + * + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), error => Scope.provide(internalEffect.andThen(f(error), internalEffect.fail(error)), scope)))))); +/** + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** + * + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. + * + * **Details** + * + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => Scope.provide(internalEffect.andThen(f(cause), internalEffect.failCause(cause)), scope)))))); +/** + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Exit, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Layer that can fail during construction + * const error = new DatabaseError({ message: "Connection failed" }) + * const flakyDatabaseLayer = Layer.effect( + * Database, + * Effect.fail(error) + * ) + * + * // Convert failures to fiber death - removes error from type + * const reliableDatabaseLayer = flakyDatabaseLayer.pipe(Layer.orDie) + * + * // Now the layer type is Layer - no error in type + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(reliableDatabaseLayer) + * ) + * + * Effect.runSync(Effect.exit(program)) // => Exit.die(error) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), e => onError(e).build(memoMap, scope)))))); + +/** + * Recovers from specific tagged errors. + * + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class ConfigError extends Data.TaggedError("ConfigError") {} + * + * class Config extends Context.Service()("Config") {} + * + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) + * + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) + * + * const recovered = configLayer.pipe( + * Layer.catchTag("ConfigError", () => fallbackLayer) + * ) + * const program = Config.useSync((config) => config.apiUrl) + * Effect.runSync(Effect.provide(program, recovered)) // => "http://localhost" + * ``` + * + * @see {@link catchCause} for recovering with access to the full cause + * + * @category error handling + * @since 4.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, k, f) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchTag(self.build(memoMap, scope), k, error => f(error).build(memoMap, scope)))))); +/** + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) + * + * const databaseWithFallback = primaryDatabaseLayer.pipe( + * Layer.catchCause(() => { + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(databaseWithFallback) + * ) + * + * await Effect.runPromise(program) // => "Memory: SELECT * FROM users" + * ``` + * + * @see {@link catchTag} for recovering from specific tagged errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => onError(cause).build(memoMap, scope)))))); +/** + * Updates a service in the context with a new implementation. + * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * + * **Details** + * + * This function modifies the existing implementation of a service in the + * context. It retrieves the current service, applies the provided + * transformation function `f`, and replaces the old service with the + * transformed one. + * + * @category providing services + * @since 3.13.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (layer, service, f) => provide(layer, effect(service, internalEffect.map(service, f)))))); +/** + * Creates a fresh version of this layer that will not be shared. + * + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Ref } from "effect" + * + * class Counter extends Context.Service()("Counter") {} + * + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const compareIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * return left.counterId === right.counterId + * }) + * + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) + * + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * return { id } + * })) + * + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * const sharedResult = yield* Effect.provide(compareIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * const freshResult = yield* Effect.provide(compareIds, fresh) + * + * return { shared: sharedResult, fresh: freshResult } + * }) + * + * await Effect.runPromise(program) // => { shared: true, fresh: false } + * ``` + * + * @category layers + * @since 2.0.0 + */ +const fresh = self => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope)); +/** + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) + * + * ```ts import.meta.vitest + * import { Context, Deferred, Effect, Fiber, Layer, Ref } from "effect" + * + * class HttpServer extends Context.Service()("HttpServer") {} + * + * const program = Effect.gen(function*() { + * const events = yield* Ref.make>([]) + * const started = yield* Deferred.make() + * + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { + * yield* Ref.update(events, (events) => [...events, "Starting HTTP server..."]) + * yield* Deferred.succeed(started, undefined) + * return { port: 3000 } + * })) + * + * const fiber = yield* Effect.forkChild(Layer.launch(serverLayer)) + * yield* Deferred.await(started) + * yield* Fiber.interrupt(fiber) + * return yield* Ref.get(events) + * }) + * + * await Effect.runPromise(program) // => ["Starting HTTP server..."] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const launch = self => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never)); +/** + * Creates a mock layer for testing purposes. You can provide a partial + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class UserService extends Context.Service Effect.Effect<{ id: string; name: string }, Error> + * readonly deleteUser: (id: string) => Effect.Effect + * readonly updateUser: ( + * id: string, + * data: object + * ) => Effect.Effect<{ id: string; name: string }, Error> + * }>()("UserService") {} + * + * // Create a partial mock - only implement what you need for testing + * const testUserLayer = Layer.mock(UserService, { + * config: { apiUrl: "https://test-api.com" }, // Required - non-Effect property + * getUser: (id: string) => Effect.succeed({ id, name: "Test User" }) // Mock implementation + * // deleteUser and updateUser are omitted - will throw UnimplementedError if called + * }) + * + * // Use in tests + * const testProgram = Effect.gen(function*() { + * const userService = yield* UserService + * + * // This works - we provided an implementation + * const user = yield* userService.getUser("123") + * + * // This would throw - we didn't implement deleteUser + * // yield* userService.deleteUser("123") // UnimplementedError + * + * return user.name + * }).pipe( + * Effect.provide(testUserLayer) + * ) + * Effect.runSync(testProgram) // => "Test User" + * ``` + * + * @category testing + * @since 3.17.0 + */ +const mock = function () { + if (arguments.length === 1) { + return implementation => mockImpl(arguments[0], implementation); + } + return mockImpl(arguments[0], arguments[1]); +}; +const mockImpl = (service, implementation) => succeed(service)(new Proxy({ + ...implementation +}, { + get(target, prop, _receiver) { + if (prop in target) { + return target[prop]; + } + const prevLimit = getStackTraceLimit(); + setStackTraceLimit(2); + const error = new Error(`${service.key}: Unimplemented method "${prop.toString()}"`); + setStackTraceLimit(prevLimit); + error.name = "UnimplementedError"; + return makeUnimplemented(error); + }, + has: constTrue +})); +const makeUnimplemented = error => { + const dead = Object.assign(internalEffect.die(error), { + [StreamTypeId]: StreamTypeId, + channel: { + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead), + pipe() { + return pipeArguments(this, arguments); + } + }, + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead) + }); + function unimplemented() { + return dead; + } + // @effect-diagnostics-next-line floatingEffect:off + Object.assign(unimplemented, dead); + Object.setPrototypeOf(unimplemented, Object.getPrototypeOf(dead)); + return unimplemented; +}; +const StreamTypeId = "~effect/Stream"; +const ChannelTypeId = "~effect/Channel"; +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the success + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) + * + * ```ts import.meta.vitest + * import { Context, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.succeed(NumberService, 42) + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Layer.satisfiesSuccessType() + * + * // This works - Layer<42, never, never> extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => layer => layer; +/** + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the error + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const typeErrorLayer = Layer.effectDiscard(Effect.fail(new TypeError("boom"))) + * + * // Define a constraint that the error type must be an Error + * const satisfiesError = Layer.satisfiesErrorType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesError(typeErrorLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => layer => layer; +/** + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.effectDiscard(Effect.asVoid(NumberService)) + * + * // Define a constraint that the service requirements must be numbers + * const satisfiesNumber = Layer.satisfiesServicesType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => layer => layer; +/** + * Constructs a new `Layer` which creates a span and registers it as the current + * parent span. + * + * **Details** + * + * This allows you to create a traced scope for layer construction, making all + * operations within the layer constructor part of the same trace span. The span + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const logs: Array = [] + * + * // Create a traced layer - all operations performed during construction of + * // the `Database` service are part of the "database-init" span + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * // These operations are traced under "database-init" span + * logs.push("Connecting to database") + * logs.push("Database connected") + * + * const parentSpan = yield* Effect.currentParentSpan + * logs.push((parentSpan as Tracer.Span).name) + * + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.provide(Layer.span("database-init", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Span ${span.name} ended with: ${exit._tag}`)) + * }))) + * + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => "Result: SELECT 1" + * logs // => ["Connecting to database", "Database connected", "database-init", "Span database-init ended with: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const span = (name, options) => { + options = internalTracer.addSpanStackTrace(options); + return effect(Tracer.ParentSpan, options?.onEnd ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options)); +}; +/** + * Constructs a layer that provides an existing span as the current parent span. + * + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Referencing an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a layer that uses an existing span as parent + * const databaseLayer = Layer.effect( + * Database, + * Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * + * return { + * spanId: parentSpan.spanId, + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * }) + * ).pipe(Layer.provide(Layer.parentSpan(Tracer.externalSpan({ + * spanId: "42", + * traceId: "000" + * })))) + * const program = Database.use((database) => + * Effect.map(database.query("SELECT 1"), (result) => ({ spanId: database.spanId, result }))) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => { spanId: "42", result: "Result: SELECT 1" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const parentSpan = span => succeedContext(Tracer.ParentSpan.context(span)); +/** + * Wraps a `Layer` with a new tracing span, making all operations in the layer + * constructor part of the named trace span. + * + * **Details** + * + * This creates a new span for the layer's construction and execution. The span + * is automatically ended when the layer's scope is closed. This is useful for + * tracking the lifecycle and performance of layer initialization. + * + * **Example** (Wrapping a layer with a span) + * + * ```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 = [] + * + * // Create layers with tracing + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.withSpan("database-initialization", { + * attributes: { dbType: "postgres" } + * })) + * + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) + * }).pipe(Layer.withSpan("logger-initialization")) + * + * // Combine traced layers + * const appLayer = Layer.mergeAll(databaseLayer, loggerLayer).pipe( + * Layer.withSpan("app-initialization", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Application initialization completed: ${exit._tag}`)) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Application ready") + * return yield* database.query("SELECT * FROM users") + * }).pipe(Effect.provide(appLayer)) + * Effect.runSync(program) // => "Result: SELECT * FROM users" + * logs // => ["Application ready", "Application initialization completed: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = internalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); + } + return self => unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); +}; +/** + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Cache extends Context.Service Effect.Effect + * }>()("Cache") {} + * + * // Create layers + * const DatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) + * } + * })) + * + * const CacheLayer = Layer.effect(Cache, Effect.gen(function*() { + * return { + * get: Effect.fn("Cache.get")((key: string) => Effect.succeed(`Cache: ${key}`)) + * } + * })) + * + * // Use with an existing parent span from Effect.withSpan + * const program = Effect.withSpan("application-startup")( + * Effect.gen(function*() { + * const parentSpan = yield* Tracer.ParentSpan + * + * // Both layers will be children of "application-startup" span + * const AppLayer = Layer.mergeAll(DatabaseLayer, CacheLayer).pipe( + * Layer.withParentSpan(parentSpan) + * ) + * + * const context = yield* Layer.build(AppLayer) + * const database = Context.get(context, Database) + * const cache = Context.get(context, Cache) + * + * const dbResult = yield* database.query("SELECT * FROM users") + * const cacheResult = yield* cache.get("user:123") + * + * return { dbResult, cacheResult } + * }) + * ) + * Effect.runSync(Effect.scoped(program)) // => { dbResult: "DB: SELECT * FROM users", cacheResult: "Cache: user:123" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = function () { + const dataFirst = isLayer(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = identity; + if (span._tag === "Span") { + options = internalTracer.addSpanStackTrace(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + const parentSpanLayer = parentSpan(span); + if (dataFirst) { + return provide(provideStackFrame(arguments[0]), parentSpanLayer); + } + return self => provide(provideStackFrame(self), parentSpanLayer); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : constUndefined; + return updateService(CurrentStackFrame, parent => ({ + name, + stack, + parent + })); +}; +//# sourceMappingURL=Layer.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + H7: buildWithMemoMap, + LT: buildWithScope, + Um: mergeAll, + j6: makeMemoMapUnsafe +}); + + +}, +"./node_modules/effect/dist/MutableList.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Mutable lists for collecting ordered values and draining them from the front. + * A `MutableList` can append values to the end, prepend values to the + * beginning, take one or more values from the front, inspect its contents as an + * array, filter values, remove values, and clear itself. All operations update + * the same list object in place and keep its `length` field current. Taking + * from an empty list returns the `Empty` symbol. + * + * @since 4.0.0 + */ + +/** + * Defines the unique symbol used to represent an empty result when taking elements from a MutableList. + * This symbol is returned by `take` when the list is empty, allowing for safe type checking. + * + * **When to use** + * + * Use to detect that `take` returned no element before handling the result as a + * list item. + * + * **Example** (Checking for empty results) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * + * MutableList.take(list) === MutableList.Empty // => true + * ``` + * + * @category symbols + * @since 4.0.0 + */ +const Empty = /*#__PURE__*/Symbol.for("effect/MutableList/Empty"); +/** + * Creates an empty MutableList. + * + * **Example** (Creating an empty mutable list) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * + * list.length // => 0 + * MutableList.append(list, "first") + * MutableList.take(list) // => "first" + * list.length // => 0 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = () => ({ + head: undefined, + tail: undefined, + length: 0 +}); +const emptyBucket = () => ({ + array: [], + mutable: true, + offset: 0, + next: undefined +}); +/** + * Appends an element to the end of the MutableList. + * This operation is optimized for high-frequency usage. + * + * **Example** (Appending elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * MutableList.append(list, 2) + * MutableList.append(list, 3) + * + * MutableList.toArray(list) // => [1, 2, 3] + * list.length // => 3 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const append = (self, message) => { + if (!self.tail) { + self.head = self.tail = emptyBucket(); + } else if (!self.tail.mutable) { + self.tail.next = emptyBucket(); + self.tail = self.tail.next; + } + self.tail.array.push(message); + self.length++; +}; +/** + * Prepends an element to the beginning of the MutableList. + * This operation is optimized for high-frequency usage. + * + * **Example** (Prepending elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, "last") + * MutableList.prepend(list, "third") + * MutableList.prepend(list, "second") + * MutableList.prepend(list, "first") + * + * MutableList.toArray(list) // => ["first", "second", "third", "last"] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const prepend = (self, message) => { + self.head = { + array: [message], + mutable: true, + offset: 0, + next: self.head + }; + if (!self.tail) self.tail = self.head; + self.length++; +}; +/** + * Prepends all elements from an iterable to the beginning of the MutableList. + * The elements are added in order, so the first element in the iterable becomes + * the new head of the list. + * + * **Example** (Prepending multiple elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 4) + * MutableList.append(list, 5) + * MutableList.prependAll(list, [1, 2, 3]) + * + * MutableList.toArray(list) // => [1, 2, 3, 4, 5] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const prependAll = (self, messages) => prependAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)); +/** + * Prepends all elements from a ReadonlyArray to the beginning of the MutableList. + * This is an optimized version that can reuse the array when mutable=true. + * + * **When to use** + * + * Use when prepending a trusted array directly is worth the optimized path and + * you can transfer ownership of the input when enabling mutation. + * + * **Gotchas** + * + * When mutable=true, ownership of the input array transfers to the list. Do not + * read or modify the array afterward. + * + * **Example** (Transferring an array when prepending) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 4) + * const items = [1, 2, 3] + * MutableList.prependAllUnsafe(list, items, true) + * + * MutableList.toArray(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const prependAllUnsafe = (self, messages, mutable = false) => { + self.head = { + array: messages, + mutable, + offset: 0, + next: self.head + }; + self.length += self.head.array.length; +}; +/** + * Appends all elements from an iterable to the end of the MutableList. + * Returns the number of elements added. + * + * **Example** (Appending multiple elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * MutableList.append(list, 2) + * + * MutableList.appendAll(list, [3, 4, 5]) // => 3 + * MutableList.toArray(list) // => [1, 2, 3, 4, 5] + * list.length // => 5 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const appendAll = (self, messages) => appendAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)); +/** + * Appends all elements from a ReadonlyArray to the end of the MutableList. + * This is an optimized version that can reuse the array when mutable=true. + * Returns the number of elements added. + * + * **When to use** + * + * Use when appending a trusted array directly is worth the optimized path and + * you can transfer ownership of the input when enabling mutation. + * + * **Gotchas** + * + * When mutable=true, ownership of the input array transfers to the list. Do not + * read or modify the array afterward. + * + * **Example** (Transferring an array when appending) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.append(list, 1) + * const items = [2, 3, 4] + * MutableList.appendAllUnsafe(list, items, true) // => 3 + * + * MutableList.toArray(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const appendAllUnsafe = (self, messages, mutable = false) => { + if (messages.length === 0) { + return 0; + } + const chunk = { + array: messages, + mutable, + offset: 0, + next: undefined + }; + if (self.head) { + self.tail = self.tail.next = chunk; + } else { + self.head = self.tail = chunk; + } + self.length += messages.length; + return messages.length; +}; +/** + * Removes all elements from the MutableList, resetting it to an empty state. + * This operation is highly optimized and releases all internal memory. + * + * **Example** (Clearing a mutable list) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5]) + * + * MutableList.clear(list) + * + * MutableList.toArray(list) // => [] + * list.length // => 0 + * MutableList.take(list) === MutableList.Empty // => true + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const clear = self => { + self.head = self.tail = undefined; + self.length = 0; +}; +/** + * Takes up to N elements from the beginning of the MutableList and returns them as an array. + * The taken elements are removed from the list. This operation is optimized for performance + * and includes zero-copy optimizations when possible. + * + * **Example** (Taking batches) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + * + * MutableList.takeN(list, 3) // => [1, 2, 3] + * MutableList.toArray(list) // => [4, 5, 6, 7, 8, 9, 10] + * list.length // => 7 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const takeN = (self, n) => { + if (n <= 0 || !self.head) return []; + n = Math.min(n, self.length); + if (n === self.length && self.head?.offset === 0 && !self.head.next) { + const array = self.head.array; + clear(self); + return array; + } + const array = new Array(n); + let index = 0; + let chunk = self.head; + while (chunk) { + while (chunk.offset < chunk.array.length) { + array[index++] = chunk.array[chunk.offset]; + if (chunk.mutable) chunk.array[chunk.offset] = undefined; + chunk.offset++; + if (index === n) { + self.head = chunk; + self.length -= n; + if (self.length === 0) clear(self); + return array; + } + } + chunk = chunk.next; + } + clear(self); + return array; +}; +/** + * Removes up to `n` elements from the beginning of the `MutableList` without + * returning them. + * + * **When to use** + * + * Use to discard a bounded number of values from the head of a `MutableList` + * when the removed values are not needed. + * + * **Details** + * + * If `n` is less than or equal to zero, or the list is empty, the list is left + * unchanged. If `n` is greater than or equal to the current length, the list is + * cleared. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * @see {@link clear} for removing every value from the list + * + * @category mutations + * @since 4.0.0 + */ +const takeNVoid = (self, n) => { + if (n <= 0 || !self.head) return; + n = Math.min(n, self.length); + if (n === self.length && self.head?.offset === 0 && !self.head.next) { + clear(self); + return; + } + let count = 0; + let chunk = self.head; + while (chunk) { + const size = chunk.array.length - chunk.offset; + if (count + size > n) { + chunk.offset += n - count; + self.head = chunk; + self.length -= n; + return; + } + count += size; + chunk = chunk.next; + } + clear(self); + return; +}; +/** + * Takes all elements from the MutableList and returns them as an array. + * The list becomes empty after this operation. This is equivalent to takeN(list, list.length). + * + * **Example** (Draining all elements) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["apple", "banana", "cherry"]) + * + * MutableList.takeAll(list) // => ["apple", "banana", "cherry"] + * list.length // => 0 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const takeAll = self => takeN(self, self.length); +/** + * Takes a single element from the beginning of the MutableList. + * Returns the element if available, or the Empty symbol if the list is empty. + * The taken element is removed from the list. + * + * **Example** (Taking one element) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["first", "second", "third"]) + * + * MutableList.take(list) // => "first" + * MutableList.toArray(list) // => ["second", "third"] + * list.length // => 2 + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const take = self => { + if (!self.head) return Empty; + const message = self.head.array[self.head.offset]; + if (self.head.mutable) self.head.array[self.head.offset] = undefined; + self.head.offset++; + self.length--; + if (self.head.offset === self.head.array.length) { + if (self.head.next) { + self.head = self.head.next; + } else { + clear(self); + } + } + return message; +}; +/** + * Copies up to `n` elements from the beginning of the `MutableList` into a new + * array without modifying the list. + * + * **When to use** + * + * Use when you need to inspect or snapshot a bounded prefix of the list without + * consuming it. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * + * @category converting + * @since 4.0.0 + */ +const toArrayN = (self, n) => { + if (n <= 0) return []; + const length = Math.min(n, self.length); + const out = new Array(length); + let index = 0; + let bucket = self.head; + while (bucket) { + for (let i = bucket.offset; i < bucket.array.length; i++) { + out[index++] = bucket.array[i]; + if (index === length) return out; + } + bucket = bucket.next; + } + return out; +}; +/** + * Copies all current elements of the `MutableList` into a new array without + * modifying the list. + * + * **When to use** + * + * Use when you need a snapshot of all current elements while keeping the list + * unchanged. + * + * @see {@link takeAll} for converting all elements to an array and clearing the list + * + * @category converting + * @since 4.0.0 + */ +const toArray = self => toArrayN(self, self.length); +/** + * Filters the MutableList in place, keeping only elements that satisfy the predicate. + * This operation modifies the list and rebuilds its internal structure for efficiency. + * + * **Example** (Filtering in place) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + * + * MutableList.filter(list, (n) => n % 2 === 0) + * + * MutableList.toArray(list) // => [2, 4, 6, 8, 10] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const filter = (self, f) => { + const array = []; + let chunk = self.head; + while (chunk) { + for (let i = chunk.offset; i < chunk.array.length; i++) { + if (f(chunk.array[i], i)) { + array.push(chunk.array[i]); + } + } + chunk = chunk.next; + } + if (array.length === 0) { + clear(self); + return; + } + self.head = self.tail = { + array, + mutable: true, + offset: 0, + next: undefined + }; + self.length = array.length; +}; +/** + * Removes all occurrences of a value from the `MutableList` using JavaScript + * strict equality semantics. + * + * **When to use** + * + * Use when in-place removal should use JavaScript identity/strict equality + * rather than Effect structural equality. + * + * **Details** + * + * The list is modified in place. + * + * **Gotchas** + * + * Values are compared with `!==`, so this does not use Effect structural + * equality. + * + * **Example** (Removing matching values) + * + * ```ts import.meta.vitest + * import { MutableList } from "effect" + * + * const list = MutableList.make() + * MutableList.appendAll(list, ["apple", "banana", "apple", "cherry", "apple"]) + * + * MutableList.remove(list, "apple") + * + * MutableList.toArray(list) // => ["banana", "cherry"] + * ``` + * + * @category mutations + * @since 4.0.0 + */ +const remove = (self, value) => filter(self, v => v !== value); +//# sourceMappingURL=MutableList.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + BC: append, + IU: clear, + L8: make, + h0: takeAll, + s: take +}); + + +}, +"./node_modules/effect/dist/MutableRef.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Inspectable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/** + * Stores synchronous mutable state in a small reference object. + * + * A `MutableRef` stores one current value and exposes it through `.current`. + * Unlike `Ref`, its operations are synchronous and update the same object in + * place. This module includes pipeable helpers for reading, setting, comparing, + * and updating the value, plus numeric increment/decrement helpers and a + * boolean toggle helper. + * + * @since 2.0.0 + */ + + + + +const TypeId = "~effect/MutableRef"; +const MutableRefProto = { + [TypeId]: TypeId, + ..._internal_core_js__rspack_import_0/* .PipeInspectableProto */.fU, + toJSON() { + return { + _id: "MutableRef", + current: (0,_Inspectable_js__rspack_import_1/* .toJson */.aB)(this.current) + }; + } +}; +/** + * Creates a new MutableRef with the specified initial value. + * + * **When to use** + * + * Use to create a synchronous `MutableRef` initialized with a value. + * + * **Example** (Creating mutable refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * // Create a counter reference + * const counter = MutableRef.make(0) + * + * MutableRef.get(counter) // => 0 + * + * // Create a configuration reference + * const config = MutableRef.make({ debug: false, timeout: 5000 }) + * + * MutableRef.get(config) // => { debug: false, timeout: 5000 } + * + * // Create a string reference + * const status = MutableRef.make("idle") + * MutableRef.set(status, "running") + * + * MutableRef.get(status) // => "running" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = value => { + const ref = Object.create(MutableRefProto); + ref.current = value; + return ref; +}; +/** + * Sets the value to newValue atomically if the current value equals oldValue. + * Returns true if the value was updated, false otherwise. + * Uses Effect's Equal interface for value comparison. + * + * **When to use** + * + * Use to replace a `MutableRef` value only when the current value still matches + * an expected value. + * + * **Example** (Comparing and setting values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const ref = MutableRef.make("initial") + * + * // Successful compare and set + * const updated = MutableRef.compareAndSet(ref, "initial", "updated") + * + * updated // => true + * MutableRef.get(ref) // => "updated" + * + * // Failed compare and set (value doesn't match) + * const failed = MutableRef.compareAndSet(ref, "initial", "failed") + * + * failed // => false + * MutableRef.get(ref) // => "updated" + * + * // Thread-safe counter increment + * const counter = MutableRef.make(5) + * let current: number + * do { + * current = MutableRef.get(counter) + * } while (!MutableRef.compareAndSet(counter, current, current + 1)) + * + * MutableRef.get(counter) // => 6 + * + * // Pipe-able version + * const casUpdate = MutableRef.compareAndSet("updated", "final") + * + * casUpdate(ref) // => true + * MutableRef.get(ref) // => "final" + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const compareAndSet = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(3, (self, oldValue, newValue) => { + if (Equal.equals(oldValue, self.current)) { + self.current = newValue; + return true; + } + return false; +}))); +/** + * Decrements a numeric MutableRef by 1 and returns the reference. + * + * **When to use** + * + * Use when you need an in-place `MutableRef` decrement that returns the same + * `MutableRef`. + * + * **Example** (Decrementing numeric refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Decrement the counter + * MutableRef.decrement(counter) + * + * MutableRef.get(counter) // => 4 + * + * // Chain operations + * MutableRef.decrement(counter) + * MutableRef.decrement(counter) + * + * MutableRef.get(counter) // => 2 + * + * // Useful for countdown scenarios + * const countdown = MutableRef.make(10) + * while (MutableRef.get(countdown) > 0) { + * MutableRef.decrement(countdown) + * } + * + * MutableRef.get(countdown) // => 0 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const decrement = self => update(self, n => n - 1); +/** + * Decrements a numeric MutableRef by 1 and returns the new value. + * + * **When to use** + * + * Use to decrement a numeric `MutableRef` and immediately read the updated + * value. + * + * **Example** (Decrementing and reading refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Decrement and get the new value + * const newValue = MutableRef.decrementAndGet(counter) + * + * newValue // => 4 + * MutableRef.get(counter) // => 4 + * + * // Use in expressions + * const lives = MutableRef.make(3) + * const message = `Lives remaining: ${MutableRef.decrementAndGet(lives)}` + * + * message // => "Lives remaining: 2" + * + * // Conditional logic based on decremented value + * const attempts = MutableRef.make(3) + * let retries = 0 + * while (MutableRef.decrementAndGet(attempts) >= 0) { + * retries += 1 + * } + * + * retries // => 3 + * MutableRef.get(attempts) // => -1 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const decrementAndGet = self => updateAndGet(self, n => n - 1); +/** + * Gets the current value of the MutableRef. + * + * **When to use** + * + * Use to read the current `MutableRef` value without mutating it. + * + * **Example** (Reading current values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const ref = MutableRef.make("hello") + * + * MutableRef.get(ref) // => "hello" + * + * MutableRef.set(ref, "world") + * + * MutableRef.get(ref) // => "world" + * + * // Reading complex objects + * const config = MutableRef.make({ port: 3000, host: "localhost" }) + * const currentConfig = MutableRef.get(config) + * + * currentConfig // => { port: 3000, host: "localhost" } + * + * // Multiple reads return the same value + * const value1 = MutableRef.get(ref) + * const value2 = MutableRef.get(ref) + * + * value1 === value2 // => true + * ``` + * + * @category getters + * @since 2.0.0 + */ +const get = self => self.current; +/** + * Decrements a numeric MutableRef by 1 and returns the previous value. + * + * **When to use** + * + * Use to read the current numeric `MutableRef` value before decrementing it. + * + * **Example** (Reading before decrementing) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Get current value and then decrement + * const previousValue = MutableRef.getAndDecrement(counter) + * + * previousValue // => 5 + * MutableRef.get(counter) // => 4 + * + * // Useful for processing where you need the original value + * const itemsLeft = MutableRef.make(10) + * const processedItems: Array = [] + * while (MutableRef.get(itemsLeft) > 0) { + * const currentItem = MutableRef.getAndDecrement(itemsLeft) + * processedItems.push(currentItem) + * } + * + * processedItems // => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] + * MutableRef.get(itemsLeft) // => 0 + * + * // Post-decrement semantics (like i-- in other languages) + * const index = MutableRef.make(3) + * const currentIndex = MutableRef.getAndDecrement(index) + * const nextIndex = MutableRef.get(index) + * + * currentIndex // => 3 + * nextIndex // => 2 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const getAndDecrement = self => getAndUpdate(self, n => n - 1); +/** + * Increments a numeric MutableRef by 1 and returns the previous value. + * + * **When to use** + * + * Use to read the current numeric `MutableRef` value before incrementing it. + * + * **Example** (Reading before incrementing) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Get current value and then increment + * const previousValue = MutableRef.getAndIncrement(counter) + * + * previousValue // => 5 + * MutableRef.get(counter) // => 6 + * + * // Useful for ID generation + * const idGenerator = MutableRef.make(0) + * const getId = () => MutableRef.getAndIncrement(idGenerator) + * const ids = [getId(), getId(), getId()] + * + * ids // => [0, 1, 2] + * + * // Post-increment semantics (like i++ in other languages) + * const position = MutableRef.make(0) + * const currentPos = MutableRef.getAndIncrement(position) + * const nextPos = MutableRef.get(position) + * + * currentPos // => 0 + * nextPos // => 1 + * + * // Useful for iteration counters + * const iterations = MutableRef.make(0) + * const visited: Array = [] + * while (MutableRef.get(iterations) < 5) { + * const iteration = MutableRef.getAndIncrement(iterations) + * visited.push(iteration) + * } + * + * visited // => [0, 1, 2, 3, 4] + * MutableRef.get(iterations) // => 5 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const getAndIncrement = self => getAndUpdate(self, n => n + 1); +/** + * Sets the MutableRef to a new value and returns the previous value. + * + * **When to use** + * + * Use to replace the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before setting) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const ref = MutableRef.make("old") + * + * // Set new value and get the previous one + * const previous = MutableRef.getAndSet(ref, "new") + * + * previous // => "old" + * MutableRef.get(ref) // => "new" + * + * // Swapping values + * const counter = MutableRef.make(5) + * const oldValue = MutableRef.getAndSet(counter, 10) + * const newValue = MutableRef.get(counter) + * + * oldValue // => 5 + * newValue // => 10 + * + * // Pipe-able version + * const setValue = MutableRef.getAndSet("final") + * const previousValue = setValue(ref) + * + * previousValue // => "new" + * MutableRef.get(ref) // => "final" + * + * // Useful for atomic swaps in algorithms + * const buffer = MutableRef.make>(["a", "b", "c"]) + * const oldBuffer = MutableRef.getAndSet(buffer, []) + * + * oldBuffer // => ["a", "b", "c"] + * MutableRef.get(buffer) // => [] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const getAndSet = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, value) => { + const ret = self.current; + self.current = value; + return ret; +}))); +/** + * Updates the MutableRef with the result of applying a function to its current value, + * and returns the previous value. + * + * **When to use** + * + * Use to transform the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before updating) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Increment and get the old value + * const oldValue = MutableRef.getAndUpdate(counter, (n) => n + 1) + * + * oldValue // => 5 + * MutableRef.get(counter) // => 6 + * + * // Double the value and get the previous one + * const previous = MutableRef.getAndUpdate(counter, (n) => n * 2) + * + * previous // => 6 + * MutableRef.get(counter) // => 12 + * + * // Transform string and get old value + * const message = MutableRef.make("hello") + * const oldMessage = MutableRef.getAndUpdate(message, (s) => s.toUpperCase()) + * + * oldMessage // => "hello" + * MutableRef.get(message) // => "HELLO" + * + * // Pipe-able version + * const addOne = MutableRef.getAndUpdate((n: number) => n + 1) + * const result = addOne(counter) + * + * result // => 12 + * MutableRef.get(counter) // => 13 + * + * // Useful for implementing atomic operations + * const list = MutableRef.make>([1, 2, 3]) + * const oldList = MutableRef.getAndUpdate(list, (arr) => [...arr, 4]) + * + * oldList // => [1, 2, 3] + * MutableRef.get(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const getAndUpdate = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, f) => getAndSet(self, f(get(self)))))); +/** + * Increments a numeric MutableRef by 1 and returns the reference. + * + * **When to use** + * + * Use when you need an in-place `MutableRef` increment that returns the same + * `MutableRef`. + * + * **Example** (Incrementing numeric refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Increment the counter + * MutableRef.increment(counter) + * + * MutableRef.get(counter) // => 6 + * + * // Chain operations + * MutableRef.increment(counter) + * MutableRef.increment(counter) + * + * MutableRef.get(counter) // => 8 + * + * // Useful for simple counting + * const visits = MutableRef.make(0) + * MutableRef.increment(visits) // User visited + * MutableRef.increment(visits) // Another visit + * + * MutableRef.get(visits) // => 2 + * + * // Returns the reference for chaining + * const result = MutableRef.increment(counter) + * + * result === counter // => true + * MutableRef.get(counter) // => 9 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const increment = self => update(self, n => n + 1); +/** + * Increments a numeric MutableRef by 1 and returns the new value. + * + * **When to use** + * + * Use to increment a numeric `MutableRef` and immediately read the updated + * value. + * + * **Example** (Incrementing and reading refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Increment and get the new value + * const newValue = MutableRef.incrementAndGet(counter) + * + * newValue // => 6 + * MutableRef.get(counter) // => 6 + * + * // Use in expressions + * const score = MutableRef.make(100) + * const message = `New score: ${MutableRef.incrementAndGet(score)}` + * + * message // => "New score: 101" + * + * // Pre-increment semantics (like ++i in other languages) + * const level = MutableRef.make(0) + * const nextLevel = MutableRef.incrementAndGet(level) + * + * nextLevel // => 1 + * + * // Conditional logic based on incremented value + * const attempts = MutableRef.make(0) + * const tooManyAttempts = MutableRef.incrementAndGet(attempts) > 3 + * + * tooManyAttempts // => false + * MutableRef.get(attempts) // => 1 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const incrementAndGet = self => updateAndGet(self, n => n + 1); +/** + * Sets the MutableRef to a new value and returns the reference. + * + * **When to use** + * + * Use when you need an in-place `MutableRef` replacement that returns the same + * `MutableRef`. + * + * **Example** (Setting values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const ref = MutableRef.make("initial") + * + * // Set a new value + * MutableRef.set(ref, "updated") + * + * MutableRef.get(ref) // => "updated" + * + * // Chain set operations (since it returns the ref) + * const result = MutableRef.set(ref, "final") + * + * result === ref // => true + * MutableRef.get(ref) // => "final" + * + * // Set complex objects + * const config = MutableRef.make({ debug: false, verbose: false }) + * MutableRef.set(config, { debug: true, verbose: true }) + * + * MutableRef.get(config) // => { debug: true, verbose: true } + * + * // Pipe-able version + * const setValue = MutableRef.set("new value") + * setValue(ref) + * + * MutableRef.get(ref) // => "new value" + * + * // Useful for state management + * const state = MutableRef.make<"idle" | "loading" | "success" | "error">("idle") + * MutableRef.set(state, "loading") + * // ... perform async operation + * MutableRef.set(state, "success") + * + * MutableRef.get(state) // => "success" + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const set = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, value) => { + self.current = value; + return self; +}))); +/** + * Sets the MutableRef to a new value and returns the new value. + * + * **When to use** + * + * Use to replace the current `MutableRef` value and immediately read the + * replacement. + * + * **Example** (Setting and reading values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const ref = MutableRef.make("old") + * + * // Set and get the new value + * const newValue = MutableRef.setAndGet(ref, "new") + * + * newValue // => "new" + * MutableRef.get(ref) // => "new" + * + * // Useful for assignments that need the value + * const counter = MutableRef.make(0) + * const currentValue = MutableRef.setAndGet(counter, 42) + * + * currentValue // => 42 + * + * // Pipe-able version + * const setValue = MutableRef.setAndGet("final") + * const result = setValue(ref) + * + * result // => "final" + * + * // Difference from set: returns value instead of reference + * const ref1 = MutableRef.make(1) + * const returnedRef = MutableRef.set(ref1, 2) // Returns MutableRef + * const returnedValue = MutableRef.setAndGet(ref1, 3) // Returns value + * + * returnedRef === ref1 // => true + * returnedValue // => 3 + * MutableRef.get(ref1) // => 3 + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const setAndGet = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, value) => { + self.current = value; + return self.current; +}))); +/** + * Updates the MutableRef with the result of applying a function to its current value, + * and returns the reference. + * + * **When to use** + * + * Use when you need an in-place `MutableRef` value transformation that returns + * the same `MutableRef`. + * + * **Example** (Updating values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Increment the counter + * MutableRef.update(counter, (n) => n + 1) + * + * MutableRef.get(counter) // => 6 + * + * // Chain updates (since it returns the ref) + * const result = MutableRef.update(counter, (n) => n * 2) + * + * result === counter // => true + * MutableRef.get(counter) // => 12 + * + * // Transform string + * const message = MutableRef.make("hello") + * MutableRef.update(message, (s) => s.toUpperCase()) + * + * MutableRef.get(message) // => "HELLO" + * + * // Update complex objects + * const user = MutableRef.make({ name: "Alice", age: 30 }) + * MutableRef.update(user, (u) => ({ ...u, age: u.age + 1 })) + * + * MutableRef.get(user) // => { name: "Alice", age: 31 } + * + * // Pipe-able version + * const double = MutableRef.update((n: number) => n * 2) + * double(counter) + * + * MutableRef.get(counter) // => 24 + * + * // Array operations + * const list = MutableRef.make>([1, 2, 3]) + * MutableRef.update(list, (arr) => [...arr, 4]) + * + * MutableRef.get(list) // => [1, 2, 3, 4] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const update = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, f) => set(self, f(get(self)))))); +/** + * Updates the MutableRef with the result of applying a function to its current value, + * and returns the new value. + * + * **When to use** + * + * Use to transform the current `MutableRef` value and immediately read the + * updated value. + * + * **Example** (Updating and reading values) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const counter = MutableRef.make(5) + * + * // Increment and get the new value + * const newValue = MutableRef.updateAndGet(counter, (n) => n + 1) + * + * newValue // => 6 + * MutableRef.get(counter) // => 6 + * + * // Double the value and get the result + * const doubled = MutableRef.updateAndGet(counter, (n) => n * 2) + * + * doubled // => 12 + * + * // Transform string and get result + * const message = MutableRef.make("hello") + * const upperCase = MutableRef.updateAndGet(message, (s) => s.toUpperCase()) + * + * upperCase // => "HELLO" + * + * // Pipe-able version + * const increment = MutableRef.updateAndGet((n: number) => n + 1) + * const result = increment(counter) + * + * result // => 13 + * + * // Useful for calculations that need the result + * const score = MutableRef.make(100) + * const bonus = 50 + * const newScore = MutableRef.updateAndGet(score, (s) => s + bonus) + * + * newScore // => 150 + * + * // Array transformations + * const list = MutableRef.make>([1, 2, 3]) + * const newList = MutableRef.updateAndGet(list, (arr) => arr.map((x) => x * 2)) + * + * newList // => [2, 4, 6] + * MutableRef.get(list) // => [2, 4, 6] + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const updateAndGet = /*#__PURE__*/(/* unused pure expression or super */ null && (Dual.dual(2, (self, f) => setAndGet(self, f(get(self)))))); +/** + * Switches a boolean `MutableRef` between `true` and `false`, then returns the + * reference. + * + * **When to use** + * + * Use when you need an in-place boolean `MutableRef` toggle that returns the + * same `MutableRef`. + * + * **Example** (Toggling boolean refs) + * + * ```ts import.meta.vitest + * import { MutableRef } from "effect" + * + * const flag = MutableRef.make(false) + * + * // Toggle the flag + * MutableRef.toggle(flag) + * + * MutableRef.get(flag) // => true + * + * // Toggle again + * MutableRef.toggle(flag) + * + * MutableRef.get(flag) // => false + * + * // Useful for state switches + * const isVisible = MutableRef.make(true) + * MutableRef.toggle(isVisible) // Hide + * + * MutableRef.get(isVisible) // => false + * + * // Toggle button implementation + * const darkMode = MutableRef.make(false) + * const toggleDarkMode = () => { + * MutableRef.toggle(darkMode) + * return MutableRef.get(darkMode) ? "ON" : "OFF" + * } + * + * toggleDarkMode() // => "ON" + * toggleDarkMode() // => "OFF" + * + * // Returns the reference for chaining + * const result = MutableRef.toggle(flag) + * + * result === flag // => true + * MutableRef.get(flag) // => true + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const toggle = self => update(self, _ => !_); +//# sourceMappingURL=MutableRef.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L8: make +}); + + +}, +"./node_modules/effect/dist/Option.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var _Combiner_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Combiner.js"); +/* import */ var _Equal_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Equivalence_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equivalence.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_doNotation_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _internal_option_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_record_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _internal_result_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/* import */ var _Order_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Predicate_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Reducer_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Reducer.js"); +/** + * Models a value that may be present or absent. + * + * An `Option` is `Some` when a value is available and `None` when it is + * not. This lets code handle missing values explicitly instead of relying on + * `null` or `undefined`. The module includes helpers for creating, checking, + * transforming, combining, and extracting optional values, plus conversions to + * and from common nullable or result-like shapes. It also includes `Option.gen` + * for writing small generator-based computations that stop at the first `None`. + * + * @since 2.0.0 + */ + + + + + + + + + + + +const TypeId = "~effect/data/Option"; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const none = () => _internal_option_js__rspack_import_0/* .none */.dv; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const some = _internal_option_js__rspack_import_0/* .some */.zN; +/** + * Determines whether the given value is an `Option`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries, such as type-narrowing + * in union types. + * + * **Details** + * + * - Returns `true` for both `Some` and `None` instances + * - Acts as a type guard, narrowing the input to `Option` + * + * **Example** (Checking if a value is an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isOption(Option.some(1)) // => true + * Option.isOption(Option.none()) // => true + * Option.isOption({}) // => false + * ``` + * + * @see {@link isNone} to check for `None` specifically + * @see {@link isSome} to check for `Some` specifically + * + * @category guards + * @since 2.0.0 + */ +const isOption = _internal_option_js__rspack_import_0/* .isOption */.oL; +/** + * 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. + * + * @category guards + * @since 2.0.0 + */ +const isNone = _internal_option_js__rspack_import_0/* .isNone */.$I; +/** + * Checks whether an `Option` contains a value (`Some`). + * + * **When to use** + * + * Use when you need to branch on a present `Option` before accessing `.value`. + * + * **Details** + * + * - Acts as a type guard, narrowing to `Some` + * + * **Example** (Checking for Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isSome(Option.some(1)) // => true + * Option.isSome(Option.none()) // => false + * ``` + * + * @see {@link isNone} for the opposite check. + * + * @category guards + * @since 2.0.0 + */ +const isSome = _internal_option_js__rspack_import_0/* .isSome */.Ru; +/** + * Pattern-matches on an `Option`, handling both `None` and `Some` cases. + * + * **When to use** + * + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. + * + * **Details** + * + * - If `None`, calls `onNone` and returns its result + * - If `Some`, calls `onSome` with the value and returns its result + * - Supports the `dual` API (data-last and data-first) + * + * **Example** (Matching on an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.match(Option.some(1), { + * onNone: () => "Option is empty", + * onSome: (value) => `Option has a value: ${value}` + * }) // => "Option has a value: 1" + * ``` + * + * @see {@link getOrElse} for unwrapping with a default + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onNone, + onSome +}) => isNone(self) ? onNone() : onSome(self.value)); +/** + * Converts an `Option`-returning function into a type guard (refinement). + * + * **When to use** + * + * Use when you need to turn an `Option`-returning parser into a type-narrowing + * predicate, such as for `Array.prototype.filter`. + * + * **Details** + * + * - Returns `true` when the original function returns `Some` + * - Returns `false` when the original function returns `None` + * - Narrows the input type to `B` on success + * + * **Example** (Converting a parser to a type guard) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * type MyData = string | number + * + * const parseString = (data: MyData): Option.Option => + * typeof data === "string" ? Option.some(data) : Option.none() + * + * // ┌─── (a: MyData) => a is string + * // ▼ + * const isString = Option.toRefinement(parseString) + * + * isString("a") // => true + * isString(1) // => false + * ``` + * + * @see {@link liftPredicate} for the reverse direction + * + * @category converting + * @since 2.0.0 + */ +const toRefinement = f => a => isSome(f(a)); +/** + * Wraps the first element of an `Iterable` in a `Some`, or returns `None` if + * the iterable is empty. + * + * **When to use** + * + * Use when you need to safely extract the head of a collection, including + * generators or lazy iterables. + * + * **Details** + * + * - Only consumes the first element; does not iterate the rest + * - Returns `None` for empty iterables + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromIterable([1, 2, 3]) // => Option.some(1) + * Option.fromIterable([]) // => Option.none() + * ``` + * + * @see {@link toArray} for the inverse direction + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = collection => { + for (const a of collection) { + return some(a); + } + return none(); +}; +/** + * Converts a `Result` into an `Option`, keeping only the success value. + * + * **When to use** + * + * Use when you need to discard a `Result` failure and keep only the success + * value as an `Option`. + * + * **Details** + * + * - `Success` becomes `Some` with the success value + * - `Failure` becomes `None` and the failure value is discarded + * + * **Example** (Extracting the success side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * Option.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_2/* .getSuccess */.Oz; +/** + * Converts a `Result` into an `Option`, keeping only the failure value. + * + * **When to use** + * + * Use when you need to discard a `Result` success and keep only the failure + * value as an `Option`. + * + * **Details** + * + * - `Failure` becomes `Some` with the failure value + * - `Success` becomes `None` and the success value is discarded + * + * **Example** (Extracting the failure side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getFailure(Result.succeed("ok")) // => Option.none() + * Option.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_2/* .getFailure */.L8; +/** + * Extracts the value from a `Some`, or evaluates a fallback thunk on `None`. + * + * **When to use** + * + * Use when providing a default value for an absent `Option` + * - Unwrapping with lazy evaluation of the fallback + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → calls `onNone()` and returns its result + * - `onNone` is only called when needed (lazy) + * + * **Example** (Unwrapping with a fallback) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(1).pipe(Option.getOrElse(() => 0)) // => 1 + * Option.none().pipe(Option.getOrElse(() => 0)) // => 0 + * ``` + * + * @see {@link getOrNull} to fall back to `null` + * @see {@link getOrUndefined} to fall back to `undefined` + * @see {@link getOrThrow} to throw on `None` + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? onNone() : self.value); +/** + * Returns the fallback `Option` if `self` is `None`; otherwise returns `self`. + * + * **When to use** + * + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → evaluates and returns `that()` + * - `that` is lazily evaluated + * + * **Example** (Providing a fallback Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElse(() => Option.some("b"))) // => Option.some("b") + * Option.some("a").pipe(Option.orElse(() => Option.some("b"))) // => Option.some("a") + * ``` + * + * @see {@link orElseSome} to wrap the fallback value in `Some` automatically + * @see {@link firstSomeOf} to pick the first `Some` from a collection + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? that() : self); +/** + * Returns `Some` of the fallback value if `self` is `None`; otherwise returns + * `self`. + * + * **When to use** + * + * Use when providing a default plain value (not an `Option`) as fallback + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → calls `onNone()`, wraps result in `Some`, and returns it + * + * **Example** (Providing a fallback value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElseSome(() => "b")) // => Option.some("b") + * Option.some("a").pipe(Option.orElseSome(() => "b")) // => Option.some("a") + * ``` + * + * @see {@link orElse} when the fallback is itself an `Option` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSome = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? some(onNone()) : self); +/** + * Returns the first available value and marks whether it came from the fallback. + * + * **When to use** + * + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. + * + * **Details** + * + * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) + * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) + * - Both `None` → `None` + * + * **Example** (Tracking value source) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const fallback = () => Option.some("fallback") + * + * Option.orElseResult(Option.some("primary"), fallback) // => Option.some(Result.fail("primary")) + * Option.orElseResult(Option.none(), fallback) // => Option.some(Result.succeed("fallback")) + * ``` + * + * @see {@link orElse} for the simpler variant without source tracking + * + * @category error handling + * @since 4.0.0 + */ +const orElseResult = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? map(that(), _internal_result_js__rspack_import_2/* .succeed */.Py) : map(self, _internal_result_js__rspack_import_2/* .fail */.fJ)); +/** + * Returns the first `Some` found in an iterable of `Option`s, or `None` if + * all are `None`. + * + * **When to use** + * + * Use when you need the first available `Some` value from a priority list. + * + * **Details** + * + * - Short-circuits on the first `Some` + * - Returns `None` only when every element is `None` + * + * **Example** (Finding the first Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.firstSomeOf([ + * Option.none(), + * Option.some(1), + * Option.some(2) + * ]) // => Option.some(1) + * ``` + * + * @see {@link orElse} for a two-option fallback + * + * @category error handling + * @since 2.0.0 + */ +const firstSomeOf = collection => { + let out = none(); + for (out of collection) { + if (isSome(out)) { + return out; + } + } + return out; +}; +/** + * Converts a nullable value (`null` or `undefined`) into an `Option`. + * + * **When to use** + * + * Use when you need JavaScript nullish values to become absence at an API + * boundary while all other values, including falsy ones, remain present. + * + * **Details** + * + * - `null` or `undefined` → `None` + * - Any other value → `Some` (typed as `NonNullable`) + * + * **Example** (Converting nullable values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullishOr(undefined) // => Option.none() + * Option.fromNullishOr(null) // => Option.none() + * Option.fromNullishOr(1) // => Option.some(1) + * ``` + * + * @see {@link fromNullOr} to only treat `null` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * @see {@link liftNullishOr} to lift a nullable-returning function + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? none() : some(a); +/** + * Converts a possibly `undefined` value into an `Option`, leaving `null` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `undefined` as absent while preserving `null` + * as a meaningful value. + * + * **Details** + * + * - `undefined` → `None` + * - Any other value (including `null`) → `Some` + * + * **Example** (Converting possibly undefined values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromUndefinedOr(undefined) // => Option.none() + * Option.fromUndefinedOr(null) // => Option.some(null) + * Option.fromUndefinedOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromNullOr} to only treat `null` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromUndefinedOr = a => a === undefined ? none() : some(a); +/** + * Converts a possibly `null` value into an `Option`, leaving `undefined` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `null` as absent while preserving + * `undefined` as a meaningful value. + * + * **Details** + * + * - `null` → `None` + * - Any other value (including `undefined`) → `Some` + * + * **Example** (Converting possibly null values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullOr(null) // => Option.none() + * Option.fromNullOr(undefined) // => Option.some(undefined) + * Option.fromNullOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromNullOr = a => a === null ? none() : some(a); +/** + * Lifts a function that may return `null` or `undefined` into one that returns + * an `Option`. + * + * **When to use** + * + * Use to wrap existing nullable-returning functions for use in `Option` pipelines + * + * **Details** + * + * - Calls the original function with the given arguments + * - Wraps the result via {@link fromNullishOr} + * + * **Example** (Lifting a parser) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): number | undefined => { + * const n = parseFloat(s) + * return isNaN(n) ? undefined : n + * } + * + * const parseOption = Option.liftNullishOr(parse) + * + * parseOption("1") // => Option.some(1) + * parseOption("not a number") // => Option.none() + * ``` + * + * @see {@link fromNullishOr} for converting a single value + * @see {@link liftThrowable} for functions that throw instead + * + * @category converting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Extracts the value from a `Some`, or returns `null` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect `null`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `null` + * + * **Example** (Unwrapping to null) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrNull(Option.some(1)) // => 1 + * Option.getOrNull(Option.none()) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constNull */.XR); +/** + * Extracts the value from a `Some`, or returns `undefined` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect + * `undefined`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `undefined` + * + * **Example** (Unwrapping to undefined) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrUndefined(Option.some(1)) // => 1 + * Option.getOrUndefined(Option.none()) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constUndefined */.MN); +/** + * Lifts a function that may throw into one that returns an `Option`. + * + * **When to use** + * + * Use to wrap exception-throwing APIs (e.g. `JSON.parse`) for safe usage + * + * **Details** + * + * - If the function returns normally → `Some` with the result + * - If the function throws → `None` (exception is swallowed) + * + * **Example** (Lifting JSON.parse) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = Option.liftThrowable(JSON.parse) + * + * parse("1") // => Option.some(1) + * parse("") // => Option.none() + * ``` + * + * @see {@link liftNullishOr} for nullable-returning functions + * + * @category converting + * @since 2.0.0 + */ +const liftThrowable = f => (...a) => { + try { + return some(f(...a)); + } catch { + return none(); + } +}; +/** + * Extracts the value from a `Some`, or throws a custom error for `None`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws the value returned by `onNone()` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrowWith(Option.some(1), () => new Error("missing")) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrowWith(Option.none(), () => new Error("missing")), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "missing" + * ``` + * + * @see {@link getOrThrow} for a version with a default error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => { + if (isSome(self)) { + return self.value; + } + throw onNone(); +}); +/** + * Extracts the value from a `Some`, or throws a default `Error` for `None`. + * + * **When to use** + * + * Use when you need quick fail-fast unwrapping of an `Option` and a generic + * error is acceptable. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws `new Error("getOrThrow called on a None")` + * + * **Example** (Throwing a default error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrow(Option.some(1)) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrow(Option.none()), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "getOrThrow called on a None" + * ``` + * + * @see {@link getOrThrowWith} for a custom error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/getOrThrowWith(() => new Error("getOrThrow called on a None")); +/** + * Transforms the value inside a `Some` using the provided function, leaving + * `None` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. + * + * **Details** + * + * - `Some` → applies `f` and wraps the result in a new `Some` + * - `None` → returns `None` unchanged + * + * **Example** (Mapping over an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.map(Option.some(2), (n) => n * 2) // => Option.some(4) + * Option.map(Option.none(), (n: number) => n * 2) // => Option.none() + * ``` + * + * @see {@link flatMap} when `f` returns an `Option` + * @see {@link as} to replace the value with a constant + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : some(f(self.value))); +/** + * Replaces the value inside a `Some` with a constant, leaving `None` unchanged. + * + * **When to use** + * + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Replacing a value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.as(Option.some(42), "new value") // => Option.some("new value") + * Option.as(Option.none(), "new value") // => Option.none() + * ``` + * + * @see {@link asVoid} to replace with `undefined` + * @see {@link map} for a general transformation + * + * @category mapping + * @since 2.0.0 + */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => map(self, () => b)); +/** + * Replaces the value inside a `Some` with `void` (`undefined`), leaving `None` + * unchanged. + * + * **When to use** + * + * Use when you need to discard a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Voiding the value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.asVoid(Option.some(42)) // => Option.some(undefined) + * Option.asVoid(Option.none()) // => Option.none() + * ``` + * + * @see {@link as} to replace with a specific constant + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = /*#__PURE__*/as(undefined); +const void_ = /*#__PURE__*/some(undefined); + +/** + * Applies a function that returns an `Option` to the value of a `Some`, + * flattening the result. Returns `None` if the input is `None`. + * + * **When to use** + * + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. + * + * **Details** + * + * - `Some` → applies `f` to the value and returns its `Option` result + * - `None` → returns `None` without calling `f` + * - Equivalent to `map` followed by {@link flatten} + * + * **Example** (Chaining optional lookups) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface User { + * readonly name: string + * readonly address: Option.Option<{ readonly street: Option.Option }> + * } + * + * const user: User = { + * name: "John", + * address: Option.some({ street: Option.some("123 Main St") }) + * } + * + * user.address.pipe( + * Option.flatMap((addr) => addr.street) + * ) // => Option.some("123 Main St") + * ``` + * + * @see {@link map} when `f` returns a plain value + * @see {@link andThen} for a more flexible variant + * @see {@link flatten} to unwrap a nested `Option>` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : f(self.value)); +/** + * Chains a second computation onto an `Option`. The second value can be a + * plain value, an `Option`, or a function returning either. + * + * **When to use** + * + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. + * + * **Details** + * + * - If `self` is `None`, returns `None` immediately + * - If `f` is a function, calls it with the `Some` value + * - If `f` returns an `Option`, returns it as-is; if a plain value, wraps in `Some` + * - If `f` is not a function, uses it directly (same wrapping rules) + * + * **Example** (Chaining with andThen) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * // Chain with a function returning Option + * Option.andThen(Option.some(5), (x) => Option.some(x * 2)) // => Option.some(10) + * + * // Chain with a static value + * Option.andThen(Option.some(5), "hello") // => Option.some("hello") + * + * // Chain with None - skips + * Option.andThen(Option.none(), (x) => Option.some(x * 2)) // => Option.none() + * ``` + * + * @see {@link flatMap} for the standard monadic bind + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => { + const b = (0,_Predicate_js__rspack_import_3/* .isFunction */.Tn)(f) ? f(a) : f; + return isOption(b) ? b : some(b); +})); +/** + * Combines {@link flatMap} with {@link fromNullishOr}: applies a function that + * may return `null`/`undefined` to the value of a `Some`. + * + * **When to use** + * + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. + * + * **Details** + * + * - `None` → `None` + * - `Some` → applies `f`, then wraps via {@link fromNullishOr} + * + * **Example** (Navigating optional properties) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface Employee { + * company?: { address?: { street?: { name?: string } } } + * } + * + * const emp: Employee = { + * company: { address: { street: { name: "high street" } } } + * } + * + * Option.some(emp).pipe( + * Option.flatMapNullishOr((e) => e.company?.address?.street?.name) + * ) // => Option.some("high street") + * ``` + * + * @see {@link flatMap} when the function already returns `Option` + * @see {@link fromNullishOr} for single-value conversion + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : fromNullishOr(f(self.value))); +/** + * Flattens a nested `Option>` into `Option`. + * + * **When to use** + * + * Use when you need to remove one layer of nested `Option`. + * + * **Details** + * + * - `Some(Some(value))` → `Some(value)` + * - `Some(None)` → `None` + * - `None` → `None` + * + * **Example** (Flattening nested Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.flatten(Option.some(Option.some("value"))) // => Option.some("value") + * Option.flatten(Option.some(Option.none())) // => Option.none() + * ``` + * + * @see {@link flatMap} which is `map` + `flatten` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/flatMap(_Function_js__rspack_import_1/* .identity */.D_); +/** + * Sequences two `Option`s, keeping the value from the second if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. + * + * **Details** + * + * - Both `Some` → returns `that` + * - Either `None` → returns `None` + * + * **Example** (Keeping the second value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipRight(Option.some(1), Option.some("hello")) // => Option.some("hello") + * Option.zipRight(Option.none(), Option.some("hello")) // => Option.none() + * ``` + * + * @see {@link zipLeft} to keep the first value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipRight = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => flatMap(self, () => that)); +/** + * Sequences two `Option`s, keeping the value from the first if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. + * + * **Details** + * + * - Both `Some` → returns `self` + * - Either `None` → returns `None` + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipLeft(Option.some("hello"), Option.some(1)) // => Option.some("hello") + * Option.zipLeft(Option.some("hello"), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipRight} to keep the second value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipLeft = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => tap(self, () => that)); +/** + * Composes two `Option`-returning functions into a single function that chains + * them together. + * + * **When to use** + * + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. + * + * **Details** + * + * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value + * - Short-circuits to `None` if either function returns `None` + * + * **Example** (Composing parsers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): Option.Option => + * isNaN(Number(s)) ? Option.none() : Option.some(Number(s)) + * + * const double = (n: number): Option.Option => + * n > 0 ? Option.some(n * 2) : Option.none() + * + * const parseAndDouble = Option.composeK(parse, double) + * + * parseAndDouble("42") // => Option.some(84) + * parseAndDouble("not a number") // => Option.none() + * ``` + * + * @see {@link flatMap} for single-step chaining + * + * @category sequencing + * @since 2.0.0 + */ +const composeK = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (afb, bfc) => a => flatMap(afb(a), bfc)); +/** + * Runs a side-effecting `Option`-returning function on the value of a `Some`, + * returning the original `Option` if the function returns `Some`, or `None` + * if it returns `None`. + * + * **When to use** + * + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. + * + * **Details** + * + * - `None` → `None` + * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` + * + * **Example** (Validating without transforming) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const getInteger = (n: number) => + * Number.isInteger(n) ? Option.some(n) : Option.none() + * + * Option.tap(Option.some(1), getInteger) // => Option.some(1) + * Option.tap(Option.some(1.14), getInteger) // => Option.none() + * ``` + * + * @see {@link flatMap} when you want to transform the value + * @see {@link filter} for predicate-based filtering + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => map(f(a), () => a))); +/** + * Combines two `Option`s into a `Some` containing a tuple `[A, B]` if both + * are `Some`. + * + * **When to use** + * + * Use when you need to require two `Option` values to both be `Some` and keep + * both values as a tuple. + * + * **Details** + * + * - Both `Some` → `Some([a, b])` + * - Either `None` → `None` + * + * **Example** (Pairing two Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.product(Option.some("hello"), Option.some(42)) // => Option.some(["hello", 42]) + * Option.product(Option.none(), Option.some(42)) // => Option.none() + * ``` + * + * @see {@link zipWith} to combine with a function instead of a tuple + * @see {@link all} to combine many `Option`s + * + * @category combining + * @since 2.0.0 + */ +const product = (self, that) => isSome(self) && isSome(that) ? some([self.value, that.value]) : none(); +/** + * Combines a primary `Option` with an iterable of `Option`s into a tuple if + * all are `Some`. + * + * **When to use** + * + * Use when you need several `Option` values of the same type to all be `Some` + * and return them as a non-empty tuple. + * + * **Details** + * + * - All `Some` → `Some([self.value, ...rest])` + * - Any `None` → `None` + * + * **Example** (Combining many Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const first = Option.some(1) + * const rest = [Option.some(2), Option.some(3)] + * + * Option.productMany(first, rest) // => Option.some([1, 2, 3]) + * Option.productMany(first, [Option.some(2), Option.none()]) // => Option.none() + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link all} for tuples, structs, and iterables + * + * @category combining + * @since 2.0.0 + */ +const productMany = (self, collection) => { + if (isNone(self)) { + return none(); + } + const out = [self.value]; + for (const o of collection) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); +}; +/** + * Combines a structure of `Option`s (tuple, struct, or iterable) into a single + * `Option` containing the unwrapped structure. + * + * **When to use** + * + * Use when you need to combine multiple `Option` values into one while + * preserving the input shape, with any `None` making the result `None`. + * + * **Details** + * + * - Tuple input → `Option` of a tuple with the same length + * - Struct input → `Option` of a struct with the same keys + * - Iterable input → `Option` of an `Array` + * - Any `None` in the input → entire result is `None` + * + * **Example** (Combining a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * // ┌─── Option<[string, number]> + * // ▼ + * const tuple = Option.all([maybeName, maybeAge]) // => Option.some(["John", 25]) + * + * // ┌─── Option<{ name: string; age: number; }> + * // ▼ + * const struct = Option.all({ name: maybeName, age: maybeAge }) // => Option.some({ name: "John", age: 25 }) + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link productMany} for a homogeneous collection + * + * @category combining + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const o of input) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const o = input[key]; + if (isNone(o)) { + return none(); + } + _internal_record_js__rspack_import_4/* .assignProperty */.x(out, key, o.value); + } + return some(out); +}; +/** + * Combines two `Option`s using a provided function. + * + * **When to use** + * + * Use when you need to combine two present `Option` values into a computed + * result. + * + * **Details** + * + * - Both `Some` → applies `f(a, b)` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Combining with a function) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipWith( + * Option.some("John"), + * Option.some(25), + * (name, age) => ({ name: name.toUpperCase(), age }) + * ) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link product} to combine into a tuple instead + * @see {@link lift2} to lift a binary function + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, that, f) => map(product(self, that), ([a, b]) => f(a, b))); +/** + * Reduces an iterable of `Option`s to a single value, skipping `None` entries. + * + * **When to use** + * + * Use when you need to aggregate values from a collection where some may be + * absent. + * + * **Details** + * + * - Iterates through the collection, applying `f` only to `Some` values + * - `None` values are skipped entirely + * - Returns the accumulated result + * + * **Example** (Summing present values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * const items = [Option.some(1), Option.none(), Option.some(2), Option.none()] + * + * pipe(items, Option.reduceCompact(0, (b, a) => b + a)) // => 3 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduceCompact = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, b, f) => { + let out = b; + for (const oa of self) { + if (isSome(oa)) { + out = f(out, oa.value); + } + } + return out; +}); +/** + * Converts an `Option` into an `Array`. + * + * **When to use** + * + * Use when you need to pass an `Option` to array-based APIs or spread optional + * values into collections. + * + * **Details** + * + * - `Some` → single-element array `[value]` + * - `None` → empty array `[]` + * + * **Example** (Converting to an array) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.toArray(Option.some(1)) // => [1] + * Option.toArray(Option.none()) // => [] + * ``` + * + * @see {@link fromIterable} for the inverse direction + * + * @category converting + * @since 2.0.0 + */ +const toArray = self => isNone(self) ? [] : [self.value]; +/** + * Splits an `Option` into two `Option`s using a function that returns a `Result`. + * + * **When to use** + * + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. + * + * **Details** + * + * - `None` → `[None, None]` + * - `Some` where `f` returns `Err` → `[Some(error), None]` + * - `Some` where `f` returns `Ok` → `[None, Some(value)]` + * + * **Example** (Partitioning by Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => { + * const n = Number(s) + * return isNaN(n) ? Result.fail("Not a number") : Result.succeed(n) + * } + * + * Option.partitionMap(Option.some("42"), parseNumber) // => [Option.none(), Option.some(42)] + * Option.partitionMap(Option.some("abc"), parseNumber) // => [Option.some("Not a number"), Option.none()] + * Option.partitionMap(Option.none(), parseNumber) // => [Option.none(), Option.none()] + * ``` + * + * @see {@link filter} for simple predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const partitionMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return [none(), none()]; + } + const e = f(self.value); + return _internal_result_js__rspack_import_2/* .isFailure */.N6(e) ? [some(e.failure), none()] : [none(), some(e.success)]; +}); +/** + * Transforms and filters an `Option` using a `Filter` callback. + * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * + * The callback returns a `Result`: `Result.succeed` keeps and transforms the + * value, while `Result.fail` discards it. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.filterMap( + * Option.some(2), + * (n) => (n % 2 === 0 ? Result.succeed(`Even: ${n}`) : Result.failVoid) + * ) // => Option.some("Even: 2") + * ``` + * + * @see {@link filter} for predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return none(); + } + const next = f(self.value); + return _internal_result_js__rspack_import_2/* .isSuccess */.oJ(next) ? some(next.success) : none(); +}); +/** + * Filters an `Option` using a predicate. Returns `None` if the predicate is + * not satisfied or the input is `None`. + * + * **When to use** + * + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. + * + * **Details** + * + * - `None` → `None` + * - `Some` where `predicate(value)` is `true` → `Some(value)` + * - `Some` where `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Filtering with a predicate) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const removeEmpty = (input: Option.Option) => + * Option.filter(input, (value) => value !== "") + * + * removeEmpty(Option.some("hello")) // => Option.some("hello") + * removeEmpty(Option.some("")) // => Option.none() + * removeEmpty(Option.none()) // => Option.none() + * ``` + * + * @see {@link filterMap} to transform and filter simultaneously + * @see {@link exists} to test without filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => isNone(self) ? none() : predicate(self.value) ? some(self.value) : none()); +/** + * Creates an `Equivalence` for `Option` from an `Equivalence` for `A`. + * + * **When to use** + * + * Use when you need equality to treat two `None` values as equal and compare + * two `Some` values with a supplied equality rule. + * + * **Details** + * + * - `None` vs `None` → `true` + * - `Some` vs `None` (or vice versa) → `false` + * - `Some(a)` vs `Some(b)` → delegates to the provided `Equivalence` + * + * **Example** (Comparing Options) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const eq = Option.makeEquivalence(Equivalence.strictEqual()) + * + * eq(Option.some(1), Option.some(1)) // => true + * eq(Option.some(1), Option.some(2)) // => false + * eq(Option.none(), Option.none()) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = isEquivalent => _Equivalence_js__rspack_import_5/* .make */.L8((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value)); +/** + * Creates an `Order` for `Option` from an `Order` for `A`. + * + * **When to use** + * + * Use when you need to sort `Some` and `None` values, with `None` ordered + * before present values and present values compared by a supplied ordering + * rule. + * + * **Details** + * + * - `None` is considered less than any `Some` + * - Two `Some` values are compared using the provided `Order` + * - Two `None` values are equal (returns `0`) + * + * **Example** (Ordering Options) + * + * ```ts import.meta.vitest + * import { Number as N, Option } from "effect" + * + * const ord = Option.makeOrder(N.Order) + * + * ord(Option.none(), Option.some(1)) // => -1 + * ord(Option.some(1), Option.none()) // => 1 + * ord(Option.some(1), Option.some(2)) // => -1 + * ``` + * + * @category sorting + * @since 4.0.0 + */ +const makeOrder = O => _Order_js__rspack_import_6/* .make */.L8((self, that) => isSome(self) ? isSome(that) ? O(self.value, that.value) : 1 : -1); +/** + * Lifts a binary function to operate on two `Option` values. + * + * **When to use** + * + * Use when you need to reuse an existing binary function with two `Option` + * values. + * + * **Details** + * + * - Both `Some` → applies `f` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Lifting addition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const addOptions = Option.lift2((a: number, b: number) => a + b) + * + * addOptions(Option.some(2), Option.some(3)) // => Option.some(5) + * addOptions(Option.some(2), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipWith} for a non-lifted variant + * + * @category lifting + * @since 2.0.0 + */ +const lift2 = f => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => zipWith(self, that, f)); +/** + * Lifts a `Predicate` or `Refinement` into the `Option` context: returns + * `Some(value)` when the predicate holds, `None` otherwise. + * + * **When to use** + * + * Use to convert a boolean check into an `Option`-returning function + * - Validating input and wrapping it in `Option` + * + * **Details** + * + * - `predicate(value)` is `true` → `Some(value)` + * - `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Validating positive numbers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parsePositive = Option.liftPredicate((n: number) => n > 0) + * + * parsePositive(1) // => Option.some(1) + * parsePositive(-1) // => Option.none() + * ``` + * + * @see {@link filter} to apply a predicate to an existing `Option` + * @see {@link toRefinement} for the inverse direction + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (b, predicate) => predicate(b) ? some(b) : none()); +/** + * Checks whether an `Option` contains a value equivalent to the given one, using a + * custom `Equivalence`. + * + * **When to use** + * + * Use when you need to test whether an `Option` contains a value using a + * custom equality check. + * + * **Details** + * + * - `Some` where `isEquivalent(value, a)` is `true` → `true` + * - `Some` where not equivalent, or `None` → `false` + * + * **Example** (Checking with custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const check = Option.containsWith(Equivalence.strictEqual()) + * + * Option.some(2).pipe(check(2)) // => true + * Option.some(1).pipe(check(2)) // => false + * Option.none().pipe(check(2)) // => false + * ``` + * + * @see {@link contains} for a version using default equality + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, a) => isNone(self) ? false : isEquivalent(self.value, a)); +/** + * Checks whether an `Option` contains a value equal to the given one, using default + * structural equality. + * + * **When to use** + * + * Use when you need a quick membership test for an `Option` value using + * standard equality. + * + * **Details** + * + * - `Some` where `Equal.equals(value, a)` is `true` → `true` + * - `Some` where not equal, or `None` → `false` + * + * **Example** (Checking containment) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(2).pipe(Option.contains(2)) // => true + * Option.some(1).pipe(Option.contains(2)) // => false + * Option.none().pipe(Option.contains(2)) // => false + * ``` + * + * @see {@link containsWith} for custom equality + * @see {@link exists} to test with a predicate + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/containsWith(/*#__PURE__*/_Equal_js__rspack_import_7/* .asEquivalence */.jI()); +/** + * Checks whether the value in a `Some` satisfies a predicate or refinement. + * + * **When to use** + * + * Use to check a condition on an optional value without unwrapping + * + * **Details** + * + * - `None` → `false` + * - `Some` where `predicate(value)` is `true` → `true` + * - `Some` where `predicate(value)` is `false` → `false` + * - With a refinement, narrows the `Option` type on `true` + * + * **Example** (Testing a condition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * + * Option.some(2).pipe(Option.exists(isEven)) // => true + * Option.some(1).pipe(Option.exists(isEven)) // => false + * Option.none().pipe(Option.exists(isEven)) // => false + * ``` + * + * @see {@link filter} to keep or discard based on a predicate + * @see {@link contains} to test for a specific value + * + * @category predicates + * @since 2.0.0 + */ +const exists = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, refinement) => isNone(self) ? false : refinement(self.value)); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Gives a name to the value of an `Option`, creating a single-key record + * inside `Some`. Starting point for the do notation pipeline. + * + * **When to use** + * + * Use when you need to start an `Option` do notation chain by naming the first + * value. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.some(2), + * Option.bindTo("x"), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting with an empty record + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bindTo */.Jr(map); +const let_ = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .let_ */.zM(map); + +/** + * Adds an `Option` value to the do notation record under a given name. If the + * `Option` is `None`, the whole pipeline short-circuits to `None`. + * + * **When to use** + * + * Use when you need to sequence `Option` computations in do notation. + * + * **Example** (Binding Option values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting the chain + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bind */.oI(map, flatMap); +/** + * Provides an `Option` containing an empty record `{}`, used as the starting point for + * do notation chains. + * + * **When to use** + * + * Use when you need to start an `Option` do notation pipeline before adding + * bindings. + * + * **Example** (Building Option pipelines with do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/some({}); +/** + * Provides generator-based syntax for `Option`, similar to `async`/`await` but for + * optional values. Yielding a `None` short-circuits the generator to `None`. + * + * **When to use** + * + * Use when you need generator syntax for a sequence of `Option` steps that + * should short-circuit on `None`. + * + * **Details** + * + * - Each `yield*` unwraps a `Some` value or short-circuits to `None` + * - The return value is wrapped in `Some` + * - No `Effect` runtime is needed + * + * **Example** (Sequencing Option computations with generator syntax) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * Option.gen(function*() { + * const name = (yield* maybeName).toUpperCase() + * const age = yield* maybeAge + * return { name, age } + * }) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link Do} / {@link bind} for the do notation alternative + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isNone(current)) { + return current; + } + state = iterator.next(current.value); + } + return some(state.value); +}; +/** + * Creates a `Reducer` for `Option` that prioritizes the first non-`None` + * value and combines values when both are `Some`. + * + * **When to use** + * + * Use to build an `Option` reducer that falls back to the first available value + * when either side may be absent. + * + * **Details** + * + * - `None` + `None` → `None` + * - `Some(a)` + `None` → `Some(a)` + * - `None` + `Some(b)` → `Some(b)` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * - Initial value is `None` + * + * **Example** (Reducing with first-wins semantics) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducer(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.none(), Option.some(2)]) // => Option.some(3) + * ``` + * + * @see {@link makeReducerFailFast} for fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducer(combiner) { + return _Reducer_js__rspack_import_9/* .make */.L((self, that) => { + if (isNone(self)) return that; + if (isNone(that)) return self; + return some(combiner.combine(self.value, that.value)); + }, none()); +} +/** + * Creates a `Combiner` for `Option` with fail-fast semantics: returns `None` + * if either operand is `None`. + * + * **When to use** + * + * Use when you need an `Option` combiner that returns `None` unless both + * operands are `Some`. + * + * **Details** + * + * - `None` + anything → `None` + * - anything + `None` → `None` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * + * **Example** (Fail-fast combining) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const combiner = Option.makeCombinerFailFast(Number.ReducerSum) + * combiner.combine(Option.some(1), Option.some(2)) // => Option.some(3) + * combiner.combine(Option.some(1), Option.none()) // => Option.none() + * ``` + * + * @see {@link makeReducerFailFast} to get a full `Reducer` + * + * @category constructors + * @since 4.0.0 + */ +function makeCombinerFailFast(combiner) { + return _Combiner_js__rspack_import_10/* .make */.L8((self, that) => { + if (isNone(self) || isNone(that)) return none(); + return some(combiner.combine(self.value, that.value)); + }); +} +/** + * Creates a `Reducer` for `Option` by lifting an existing `Reducer` with + * fail-fast semantics. + * + * **When to use** + * + * Use when you need to reduce `Option` values with fail-fast semantics, where + * any `None` aborts the entire result instead of being skipped. + * + * **Details** + * + * - Initial value is `Some(reducer.initialValue)` + * - Combines only when both operands are `Some` + * - Any `None` causes the result to become `None` immediately + * + * **Example** (Fail-fast reducing) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducerFailFast(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.some(2)]) // => Option.some(3) + * reducer.combineAll([Option.some(1), Option.none()]) // => Option.none() + * ``` + * + * @see {@link makeCombinerFailFast} for just the combiner + * @see {@link makeReducer} for non-fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducerFailFast(reducer) { + const combine = makeCombinerFailFast(reducer).combine; + const initialValue = some(reducer.initialValue); + return _Reducer_js__rspack_import_9/* .make */.L(combine, initialValue, collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + if (isNone(out)) return out; + } + return out; + }); +} +//# sourceMappingURL=Option.js.map +__webpack_require__.d(__webpack_exports__, { + makeCombinerFailFast: () => (makeCombinerFailFast), + makeReducer: () => (makeReducer), + makeReducerFailFast: () => (makeReducerFailFast) +}, { + Do: Do, + all: all, + andThen: andThen, + as: as, + asVoid: asVoid, + bind: bind, + bindTo: bindTo, + composeK: composeK, + contains: contains, + containsWith: containsWith, + exists: exists, + filter: filter, + filterMap: filterMap, + firstSomeOf: firstSomeOf, + flatMap: flatMap, + flatMapNullishOr: flatMapNullishOr, + flatten: flatten, + fromIterable: fromIterable, + fromNullOr: fromNullOr, + fromNullishOr: fromNullishOr, + fromUndefinedOr: fromUndefinedOr, + gen: gen, + getFailure: getFailure, + getOrElse: getOrElse, + getOrNull: getOrNull, + getOrThrow: getOrThrow, + getOrThrowWith: getOrThrowWith, + getOrUndefined: getOrUndefined, + getSuccess: getSuccess, + isNone: isNone, + isOption: isOption, + isSome: isSome, + "let": let_, + lift2: lift2, + liftNullishOr: liftNullishOr, + liftPredicate: liftPredicate, + liftThrowable: liftThrowable, + makeEquivalence: makeEquivalence, + makeOrder: makeOrder, + map: map, + match: match, + none: none, + orElse: orElse, + orElseResult: orElseResult, + orElseSome: orElseSome, + partitionMap: partitionMap, + product: product, + productMany: productMany, + reduceCompact: reduceCompact, + some: some, + tap: tap, + toArray: toArray, + toRefinement: toRefinement, + "void": void_, + zipLeft: zipLeft, + zipRight: zipRight, + zipWith: zipWith +}); + + +}, +"./node_modules/effect/dist/Order.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/** + * Defines comparison functions for ordered values. + * + * An `Order` compares two `A` values and returns whether the first is less + * than, equal to, or greater than the second. Orders are used for sorting, + * choosing minimum or maximum values, checking ranges, and building ordered data + * structures. This module includes built-in orders, constructors for custom + * orders, tools for reversing and combining comparisons, tuple and struct + * helpers, comparison predicates, clamping, and reducer support. + * + * @since 2.0.0 + */ + + +/** + * Creates a new `Order` instance from a comparison function. + * + * **When to use** + * + * Use when you need a sorting rule not covered by the built-in orders or input + * mapping helpers, and you can provide a total comparison. + * + * **Details** + * + * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns + * `0` without calling the comparison function. The comparison function should + * return `-1`, `0`, or `1`, and the returned order satisfies total ordering + * laws when the comparison function does. + * + * **Example** (Creating an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.make<{ name: string; age: number }>((self, that) => { + * if (self.age < that.age) return -1 + * if (self.age > that.age) return 1 + * return 0 + * }) + * + * byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1 + * byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1 + * ``` + * + * @see {@link mapInput} to transform an order by mapping the input type + * @see {@link combine} to combine multiple orders + * @category constructors + * @since 2.0.0 + */ +function make(compare) { + return (self, that) => self === that ? 0 : compare(self, that); +} +/** + * Order instance for strings that compares them lexicographically using JavaScript's `<` operator. + * + * **When to use** + * + * Use when you need lexicographic string ordering. + * + * **Details** + * + * Uses lexicographic dictionary ordering. The empty string is less than any + * non-empty string, and comparisons are case-sensitive. + * + * **Example** (Ordering strings) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.String("apple", "banana") // => -1 + * Order.String("banana", "apple") // => 1 + * Order.String("apple", "apple") // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a string property + * @see {@link Struct} to combine with other orders for struct comparison + * @category instances + * @since 4.0.0 + */ +const String = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for numbers that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for numbers. + * + * **Details** + * + * `0` is considered equal to `-0`. All `NaN` values are considered equal to + * each other, and any `NaN` is considered less than any non-`NaN` number. All + * other values use standard numeric comparison. + * + * **Example** (Ordering numbers) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Number(1, 1) // => 0 + * Order.Number(1, 2) // => -1 + * Order.Number(2, 1) // => 1 + * + * Order.Number(0, -0) // => 0 + * Order.Number(NaN, 1) // => -1 + * ``` + * + * @see {@link mapInput} to compare objects by a number property + * @see {@link BigInt} for bigint comparisons + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/make((self, that) => { + if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0; + if (globalThis.Number.isNaN(self)) return -1; // NaN < any number + if (globalThis.Number.isNaN(that)) return 1; // any number > NaN + return self < that ? -1 : 1; +}); +/** + * Order instance for booleans where `false` is considered less than `true`. + * + * **When to use** + * + * Use when you need boolean ordering where `false` comes before `true`. + * + * **Details** + * + * `false` is less than `true`, and equal values return `0`. + * + * **Example** (Ordering booleans) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Boolean(false, true) // => -1 + * Order.Boolean(true, false) // => 1 + * Order.Boolean(true, true) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a boolean property + * @category instances + * @since 4.0.0 + */ +const Boolean = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for bigints that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for `bigint` values. + * + * **Details** + * + * Uses standard numeric comparison for bigint values and handles arbitrarily + * large integers. + * + * **Example** (Ordering BigInts) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.BigInt(1n, 2n) // => -1 + * Order.BigInt(2n, 1n) // => 1 + * Order.BigInt(1n, 1n) // => 0 + * ``` + * + * @see {@link Number} for regular number comparisons + * @see {@link mapInput} to compare objects by a bigint property + * @category instances + * @since 4.0.0 + */ +const BigInt = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Creates a new `Order` that reverses the comparison order of the input `Order`. + * + * **When to use** + * + * Use when you need the reverse of an existing order. + * + * **Details** + * + * Returns a new order that swaps the arguments before comparison. If the + * original order returns `-1`, the flipped order returns `1`, and vice versa. + * Equal comparisons remain `0`. + * + * **Example** (Reversing an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const flip = Order.flip(Order.Number) + * + * flip(1, 2) // => 1 + * flip(2, 1) // => -1 + * flip(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine orders for multi-criteria comparison + * @category combinators + * @since 4.0.0 + */ +function flip(O) { + return make((self, that) => O(that, self)); +} +/** + * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, + * and if the values are equal, then compares using the second `Order`. + * + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** + * + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. + * + * **Example** (Combining two Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * const byAgeAndName = Order.combine(byAge, byName) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * const person3 = { name: "Charlie", age: 25 } + * + * byAgeAndName(person1, person2) // => -1 + * byAgeAndName(person1, person3) // => 1 + * ``` + * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((a1, a2) => { + const out = self(a1, a2); + if (out !== 0) { + return out; + } + return that(a1, a2); +})))); +/** + * Creates an `Order` that considers all values as equal. + * + * **When to use** + * + * Use when you need an order that treats all values as equal. + * + * **Details** + * + * Always returns `0` regardless of input values, making it useful as a neutral + * element in order composition. + * + * **Example** (Ordering with an always-equal Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const alwaysEqualOrder = Order.alwaysEqual() + * + * alwaysEqualOrder(1, 2) // => 0 + * alwaysEqualOrder(2, 1) // => 0 + * alwaysEqualOrder(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine with other orders + * @category constructors + * @since 4.0.0 + */ +function alwaysEqual() { + return make(() => 0); +} +/** + * Combines all `Order` instances in the provided collection into a single `Order`. + * The resulting `Order` compares using each `Order` in sequence until a non-zero result is found. + * + * **When to use** + * + * Use when you need tie-breaking across a variable number of orders. + * + * **Details** + * + * Applies orders in iteration order and short-circuits on the first non-zero + * result. It returns `0` only if all orders return `0`. + * + * **Example** (Combining multiple Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * + * const combinedOrder = Order.combineAll([byAge, byName]) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * + * combinedOrder(person1, person2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link makeReducer} to create a reducer for combining orders + * @category combining + * @since 2.0.0 + */ +function combineAll(collection) { + return make((a1, a2) => { + let out = 0; + for (const O of collection) { + out = O(a1, a2); + if (out !== 0) { + return out; + } + } + return out; + }); +} +/** + * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that + * maps values of type `B` to values of type `A`. + * + * **When to use** + * + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. + * + * **Example** (Mapping Input) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byLength = Order.mapInput(Order.Number, (s: string) => s.length) + * + * byLength("a", "bb") // => -1 + * byLength("bb", "a") // => 1 + * byLength("aa", "bb") // => 0 + * ``` + * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => make((b1, b2) => self(f(b1), f(b2)))); +/** + * Order instance for `Date` objects that compares them chronologically by their timestamp. + * + * **When to use** + * + * Use when you need chronological ordering for JavaScript date values. + * + * **Details** + * + * Compares dates by their underlying timestamp in milliseconds since the epoch. + * Earlier dates are less than later dates. Invalid dates are compared through + * their `getTime()` result. + * + * **Example** (Ordering Dates) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const date1 = new Date("2023-01-01") + * const date2 = new Date("2023-01-02") + * + * Order.Date(date1, date2) // => -1 + * Order.Date(date2, date1) // => 1 + * Order.Date(date1, date1) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a date property + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, date => date.getTime()))); +/** + * Creates an `Order` for a tuple type based on orders for each element. + * + * **When to use** + * + * Use when you need fixed-length tuple ordering with per-position orders. + * + * **Details** + * + * Compares tuples element-by-element using the corresponding order and stops at + * the first non-zero comparison result. Tuples must have the same length as the + * order collection, and the result is `0` only if all elements are equal. + * + * **Example** (Ordering tuples) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const tupleOrder = Order.Tuple([Order.Number, Order.String]) + * + * tupleOrder([1, "a"], [2, "b"]) // => -1 + * tupleOrder([1, "b"], [1, "a"]) // => 1 + * tupleOrder([1, "a"], [1, "a"]) // => 0 + * ``` + * + * @see {@link Array} to compare arrays with length consideration + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + const len = elements.length; + for (let i = 0; i < len; i++) { + const o = elements[i](self[i], that[i]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * @since 4.0.0 + */ +function Array_(O) { + return make((self, that) => { + const aLen = self.length; + const bLen = that.length; + const len = Math.min(aLen, bLen); + for (let i = 0; i < len; i++) { + const o = O(self[i], that[i]); + if (o !== 0) { + return o; + } + } + return Number(aLen, bLen); + }); +} + +/** + * Creates an `Order` for structs by applying the given `Order`s to each property in sequence. + * + * **When to use** + * + * Use when you need multi-field ordering for objects with known properties. + * + * **Details** + * + * Compares structs field-by-field in the key order of the fields object and + * stops at the first non-zero comparison result. Field order matters: earlier + * fields take precedence. The result is `0` only if all fields are equal. + * + * **Example** (Ordering structs) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const personOrder = Order.Struct({ + * name: Order.String, + * age: Order.Number + * }) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 25 } + * const person3 = { name: "Alice", age: 25 } + * + * personOrder(person1, person2) // => -1 + * personOrder(person1, person3) // => 1 + * personOrder(person1, person1) // => 0 + * ``` + * + * @see {@link combine} to combine orders manually + * @see {@link mapInput} to extract and compare by a single property + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return make((self, that) => { + for (const key of keys) { + const o = fields[key](self[key], that[key]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * Checks whether one value is strictly less than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1`, meaning the first value is less + * than the second. Equal or greater values return `false`. + * + * **Example** (Checking less-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanNumber = Order.isLessThan(Order.Number) + * + * isLessThanNumber(1, 2) // => true + * isLessThanNumber(2, 1) // => false + * isLessThanNumber(1, 1) // => false + * ``` + * + * @see {@link isLessThanOrEqualTo} for non-strict less than or equal + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThan = O => dual(2, (self, that) => O(self, that) === -1); +/** + * Checks whether one value is strictly greater than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1`, meaning the first value is greater + * than the second. Equal or lesser values return `false`. + * + * **Example** (Checking greater-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanNumber = Order.isGreaterThan(Order.Number) + * + * isGreaterThanNumber(2, 1) // => true + * isGreaterThanNumber(1, 2) // => false + * isGreaterThanNumber(1, 1) // => false + * ``` + * + * @see {@link isGreaterThanOrEqualTo} for non-strict greater than or equal + * @see {@link isLessThan} for strict less than + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = O => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, that) => O(self, that) === 1); +/** + * Checks whether one value is less than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than-or-equal predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1` or `0`, and returns `false` only if + * the order returns `1`. + * + * **Example** (Checking less-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number) + * + * isLessThanOrEqualToNumber(1, 2) // => true + * isLessThanOrEqualToNumber(1, 1) // => true + * isLessThanOrEqualToNumber(2, 1) // => false + * ``` + * + * @see {@link isLessThan} for strict less than + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== 1); +/** + * Checks whether one value is greater than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than-or-equal predicate using an + * `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1` or `0`, and returns `false` only if + * the order returns `-1`. + * + * **Example** (Checking greater-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number) + * + * isGreaterThanOrEqualToNumber(2, 1) // => true + * isGreaterThanOrEqualToNumber(1, 1) // => true + * isGreaterThanOrEqualToNumber(1, 2) // => false + * ``` + * + * @see {@link isGreaterThan} for strict greater than + * @see {@link isLessThanOrEqualTo} for less than or equal + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== -1); +/** + * Returns the minimum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the smaller of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as less than or equal to the other value. If + * values are equal, the first argument is returned. + * + * **Example** (Selecting the minimum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const minNumber = Order.min(Order.Number) + * + * minNumber(1, 2) // => 1 + * minNumber(2, 1) // => 1 + * minNumber(1, 1) // => 1 + * ``` + * + * @see {@link max} for the maximum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const min = O => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that); +/** + * Returns the maximum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the larger of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as greater than or equal to the other value. + * If values are equal, the first argument is returned. + * + * **Example** (Selecting the maximum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const maxNumber = Order.max(Order.Number) + * + * maxNumber(1, 2) // => 2 + * maxNumber(2, 1) // => 2 + * maxNumber(1, 1) // => 1 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const max = O => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that); +/** + * Restricts a value between a minimum and a maximum according to the given order. + * + * **When to use** + * + * Use when you need to clamp a value to an inclusive range according to an + * `Order`. + * + * **Details** + * + * Returns the value itself when it is between minimum and maximum, inclusive. + * Values below the range return minimum, and values above the range return + * maximum. The minimum must be less than or equal to the maximum according to + * the order. + * + * **Example** (Clamping values) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const clamp = Order.clamp(Order.Number)({ minimum: 1, maximum: 5 }) + * + * clamp(3) // => 3 + * clamp(0) // => 1 + * clamp(6) // => 5 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link max} for the maximum of two values + * @see {@link isBetween} to check if a value is within a range + * @category comparisons + * @since 2.0.0 + */ +const clamp = O => dual(2, (self, options) => min(O)(options.maximum, max(O)(options.minimum, self))); +/** + * Checks whether a value is between a minimum and a maximum (inclusive) according to the given order. + * + * **When to use** + * + * Use when you need range checks that respect domain-specific ordering, such as + * dates, versions, or custom priorities, instead of JavaScript numeric + * comparison. + * + * **Details** + * + * Returns `true` when the value is greater than or equal to minimum and less + * than or equal to maximum. Values outside the range return `false`. Both + * bounds are inclusive. + * + * **Example** (Checking ranges) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const betweenNumber = Order.isBetween(Order.Number) + * + * betweenNumber(5, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(1, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(10, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(0, { minimum: 1, maximum: 10 }) // => false + * betweenNumber(11, { minimum: 1, maximum: 10 }) // => false + * ``` + * + * @see {@link clamp} to clamp a value to a range + * @see {@link isLessThanOrEqualTo} for less than or equal check + * @see {@link isGreaterThanOrEqualTo} for greater than or equal check + * @category predicates + * @since 4.0.0 + */ +const isBetween = O => dual(2, (self, options) => !isLessThan(O)(self, options.minimum) && !isGreaterThan(O)(self, options.maximum)); +/** + * Creates a `Reducer` for combining `Order` instances, useful for aggregating orders in collections. + * + * **When to use** + * + * Use when you need a reducer that combines orders. + * + * **Details** + * + * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as + * the identity element for empty collections, and uses `combineAll` for + * combining collections of orders. The reducer can be used with fold operations + * on collections. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const reducer = Order.makeReducer() + * const orders = [Order.Number, Order.flip(Order.Number)] + * + * const combined = reducer.combineAll(orders) + * combined(1, 2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link combineAll} to combine multiple orders + * @see {@link Reducer} for reducing orders as a collection operation + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => 0, combineAll); +} +//# sourceMappingURL=Order.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make), + O3: () => (Array_) +}, { + wN: Number, + yJ: isGreaterThan, + zQ: mapInput +}); + + +}, +"./node_modules/effect/dist/Pipeable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * 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. + * + * @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 + * ``` + * + * @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; + } + } +}; +/** + * Reusable prototype that implements `Pipeable.pipe`. + * + * **When to use** + * + * Use when classes or object prototypes can reuse this value when they need the + * standard pipe implementation backed by `pipeArguments`. + * + * @category prototypes + * @since 3.15.0 + */ +const Prototype = (/* unused pure expression or super */ null && ({ + pipe() { + return pipeArguments(this, arguments); + } +})); +/** + * Provides a base constructor whose instances implement the standard `Pipeable.pipe` + * method. + * + * **When to use** + * + * Use when you need to define a class that supports Effect-style method + * chaining through `.pipe(...)`. + * + * @category constructors + * @since 3.15.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function PipeableBase() {} + PipeableBase.prototype = Prototype; + return PipeableBase; +}())); +/** + * Returns a subclass of the provided class that adds the standard `pipe` + * method. + * + * **When to use** + * + * Use to add pipe support to an existing class without extending a base class + * or modifying its prototype. + * + * **Details** + * + * The original constructor and instance members are preserved, and the added + * method delegates to `pipeArguments`. + * + * @see {@link Prototype} for a reusable prototype object + * @see {@link Class} for a base constructor to extend + * @category constructors + * @since 4.0.0 + */ +const Mixin = klass => class extends klass { + pipe() { + return pipeArguments(this, arguments); + } +}; +//# sourceMappingURL=Pipeable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + tT: pipeArguments +}); + + +}, +"./node_modules/effect/dist/Predicate.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.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. + * + * @since 2.0.0 + */ + +/** + * Transforms the input of a predicate using a mapping function. + * + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. + * + * **Details** + * + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. + * + * **Example** (Checking string length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isLongerThan2 = Predicate.mapInput((s: string) => s.length)( + * (n: number) => n > 2 + * ) + * + * isLongerThan2("hello") // => true + * ``` + * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => b => self(f(b))))); +/** + * Checks whether a readonly array has exactly `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking exact length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isPair = Predicate.isTupleOf(2) + * + * isPair([1, 2]) // => true + * ``` + * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length === n))); +/** + * Checks whether a readonly array has at least `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking minimum length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAtLeast2 = Predicate.isTupleOfAtLeast(2) + * + * hasAtLeast2([1, 2, 3]) // => true + * ``` + * + * @see {@link isTupleOf} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOfAtLeast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length >= n))); +/** + * Checks whether a value is truthy. + * + * **When to use** + * + * Use when you want a predicate that mirrors JavaScript truthiness and filters + * out falsy values like `0`, `""`, and `false`. + * + * **Details** + * + * This uses `!!input` and treats `0`, `""`, `false`, `null`, and `undefined` + * as false. + * + * **Example** (Filtering truthy values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, 1, "", "ok", false] + * const truthy = values.filter(Predicate.isTruthy) // => [1, "ok"] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNullish} + * @category predicates + * @since 2.0.0 + */ +function isTruthy(input) { + return !!input; +} +/** + * Checks whether a value is a `Set`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Set` values. + * + * **Details** + * + * Uses `instanceof Set`. + * + * **Example** (Guarding a Set) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Set([1, 2]) + * + * if (Predicate.isSet(data)) { + * data.size // => 2 + * } + * ``` + * + * @see {@link isMap} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isSet(input) { + return input instanceof Set; +} +/** + * Checks whether a value is a `Map`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Map` values. + * + * **Details** + * + * Uses `instanceof Map`. + * + * **Example** (Guarding a Map) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Map([["a", 1]]) + * + * if (Predicate.isMap(data)) { + * data.size // => 1 + * } + * ``` + * + * @see {@link isSet} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isMap(input) { + return input instanceof Map; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isString(input) { + return typeof input === "string"; +} +/** + * Checks whether a value is a `number`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * number. + * + * **Details** + * + * Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`. + * + * **Example** (Guarding numbers) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 42 + * + * if (Predicate.isNumber(data)) { + * data + 1 // => 43 + * } + * ``` + * + * @see {@link isBigInt} + * @see {@link isString} + * @category guards + * @since 2.0.0 + */ +function isNumber(input) { + return typeof input === "number"; +} +/** + * Checks whether a value is a `boolean`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * boolean. + * + * **Details** + * + * Uses `typeof input === "boolean"`. + * + * **Example** (Guarding booleans) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = true + * + * if (Predicate.isBoolean(data)) { + * data ? "yes" : "no" // => "yes" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBoolean(input) { + return typeof input === "boolean"; +} +/** + * Checks whether a value is a `bigint`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * bigint. + * + * **Details** + * + * Uses `typeof input === "bigint"`. + * + * **Example** (Guarding bigints) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 1n + * + * if (Predicate.isBigInt(data)) { + * data + 2n // => 3n + * } + * ``` + * + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBigInt(input) { + return typeof input === "bigint"; +} +/** + * Checks whether a value is a `symbol`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * symbol. + * + * **Details** + * + * Uses `typeof input === "symbol"`. + * + * **Example** (Guarding symbols) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Symbol.for("id") + * + * if (Predicate.isSymbol(data)) { + * data.description // => "id" + * } + * ``` + * + * @see {@link isPropertyKey} + * @category guards + * @since 2.0.0 + */ +function isSymbol(input) { + return typeof input === "symbol"; +} +/** + * Checks whether a value is a valid `PropertyKey` (string, number, or symbol). + * + * **When to use** + * + * Use when you need a `Predicate` guard for unknown property keys before + * indexing. + * + * **Details** + * + * Uses `isString`, `isNumber`, and `isSymbol`. + * + * **Example** (Guarding property keys) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const key: unknown = "name" + * const obj: Record = { name: "Ada" } + * + * if (Predicate.isPropertyKey(key) && key in obj) { + * obj[key] // => "Ada" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @see {@link isSymbol} + * @category guards + * @since 4.0.0 + */ +function isPropertyKey(u) { + return isString(u) || isNumber(u) || isSymbol(u); +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isFunction(input) { + return typeof input === "function"; +} +/** + * Checks whether a value is `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for values that are exactly + * `undefined`. + * + * **Details** + * + * Uses `input === undefined`. + * + * **Example** (Guarding undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = undefined + * + * Predicate.isUndefined(data) // => true + * ``` + * + * @see {@link isNotUndefined} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isUndefined(input) { + return input === undefined; +} +/** + * Checks whether a value is not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `undefined` + * while preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `undefined`. + * + * **Example** (Filtering undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, undefined, 2] + * const defined = values.filter(Predicate.isNotUndefined) // => [1, 2] + * ``` + * + * @see {@link isUndefined} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotUndefined(input) { + return input !== undefined; +} +/** + * Checks whether a value is `null`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullable values. + * + * **Details** + * + * Uses `input === null`. + * + * **Example** (Guarding null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = null + * + * Predicate.isNull(data) // => true + * ``` + * + * @see {@link isNotNull} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isNull(input) { + return input === null; +} +/** + * Checks whether a value is not `null`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `null` while + * preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `null`. + * + * **Example** (Filtering null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, null, 2] + * const nonNull = values.filter(Predicate.isNotNull) // => [1, 2] + * ``` + * + * @see {@link isNull} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotNull(input) { + return input !== null; +} +/** + * Checks whether a value is `null` or `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullish values. + * + * **Details** + * + * Uses `input === null || input === undefined`. + * + * **Example** (Guarding nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const nullish = values.filter(Predicate.isNullish) // => [null, undefined] + * ``` + * + * @see {@link isNotNullish} + * @see {@link isUndefined} + * @see {@link isNull} + * @category guards + * @since 4.0.0 + */ +function isNullish(input) { + return input === null || input === undefined; +} +/** + * Checks whether a value is not `null` and not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out nullish values + * but keeps other falsy ones. + * + * **Details** + * + * Uses `input != null`. + * + * **Example** (Filtering non-nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const present = values.filter(Predicate.isNotNullish) // => [0, ""] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNull} + * @see {@link isNotUndefined} + * @category guards + * @since 4.0.0 + */ +function isNotNullish(input) { + return input != null; +} +/** + * Type guard that always returns `false`. + * + * **When to use** + * + * Use when you need a `Predicate` that never accepts, e.g. in default branches. + * + * **Example** (Matching no values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isNever("anything") // => false + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isNever(_) { + return false; +} +/** + * Type guard that always returns `true`. + * + * **When to use** + * + * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. + * + * **Example** (Matching every value) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isUnknown(123) // => true + * ``` + * + * @see {@link isNever} + * @category guards + * @since 2.0.0 + */ +function isUnknown(_) { + return true; +} +/** + * Checks whether a value is an object or an array (non-null object). + * + * **When to use** + * + * Use when you need a `Predicate` guard that accepts plain objects and arrays, + * but not `null`. + * + * **Details** + * + * Uses `typeof input === "object" && input !== null` and includes arrays. + * + * **Example** (Checking objects or arrays) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObjectOrArray([]) // => true + * ``` + * + * @see {@link isObject} + * @see {@link isObjectKeyword} + * @category guards + * @since 4.0.0 + */ +function isObjectOrArray(input) { + return typeof input === "object" && input !== null; +} +/** + * Checks whether a value is a non-null object value that is not an array. + * + * **When to use** + * + * Use to narrow unknown input to a non-null, non-array object with a + * `Predicate` guard. + * + * **Details** + * + * This is a structural runtime check using `typeof input === "object"`, so it + * also accepts object instances such as `Date`, `Map`, class instances, and + * typed arrays. It excludes `null` and arrays. + * + * **Example** (Guarding objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObject({ a: 1 }) // => true + * Predicate.isObject([1, 2]) // => false + * ``` + * + * @see {@link isObjectOrArray} + * @see {@link isReadonlyObject} + * @category guards + * @since 2.0.0 + */ +function isObject(input) { + return typeof input === "object" && input !== null && !Array.isArray(input); +} +/** + * Checks whether a value is a non-null, non-array object and narrows it to a + * readonly indexable object type. + * + * **When to use** + * + * Use to narrow unknown input to a readonly view of a non-null, non-array + * object with a `Predicate` guard. + * + * **Details** + * + * Readonly-ness is a TypeScript type-level view; it is not observable at + * runtime. This delegates to `isObject`, so class instances and built-in object + * instances are accepted. + * + * **Example** (Checking readonly objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { a: 1 } + * + * Predicate.isReadonlyObject(data) // => true + * ``` + * + * @see {@link isObject} + * @category guards + * @since 4.0.0 + */ +function isReadonlyObject(input) { + return isObject(input); +} +/** + * 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} + * @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} + * @category guards + * @since 2.0.0 + */ +const hasProperty = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, property) => isObjectKeyword(self) && property in self); +/** + * Checks whether a value has a `_tag` property equal to the given tag. + * + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. + * + * **Details** + * + * Uses `hasProperty` and strict equality on `_tag`. + * + * **Example** (Guarding tagged values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isOk = Predicate.isTagged("Ok") + * + * isOk({ _tag: "Ok", value: 1 }) // => true + * ``` + * + * @see {@link hasProperty} + * @category guards + * @since 2.0.0 + */ +const isTagged = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, tag) => hasProperty(self, "_tag") && self["_tag"] === tag); +/** + * Checks whether a value is an `Error`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for errors caught from unknown sources. + * + * **Details** + * + * Uses `instanceof Error`. + * + * **Example** (Guarding errors) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Error("boom") + * + * Predicate.isError(data) // => true + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isError(input) { + return input instanceof Error; +} +/** + * Checks whether a value is a `Uint8Array`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for binary data. + * + * **Details** + * + * Uses `instanceof Uint8Array`. + * + * **Example** (Guarding Uint8Array values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Uint8Array([1, 2]) + * + * Predicate.isUint8Array(data) // => true + * ``` + * + * @see {@link isIterable} + * @see {@link isSet} + * @category guards + * @since 2.0.0 + */ +function isUint8Array(input) { + return input instanceof Uint8Array; +} +/** + * Checks whether a value is a `Date`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for dates. + * + * **Details** + * + * Uses `instanceof Date`. + * + * **Example** (Guarding Date values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Date() + * + * Predicate.isDate(data) // => true + * ``` + * + * @see {@link isRegExp} + * @category guards + * @since 2.0.0 + */ +function isDate(input) { + return input instanceof Date; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isIterable(input) { + return hasProperty(input, Symbol.iterator) || isString(input); +} +/** + * Checks whether a value is a `Promise`-like object with `then` and `catch`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise instances across realms. + * + * **Details** + * + * Performs a structural check for `then` and `catch` functions. + * + * **Example** (Guarding promises) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Promise.resolve(1) + * + * Predicate.isPromise(data) // => true + * ``` + * + * @see {@link isPromiseLike} + * @category guards + * @since 2.0.0 + */ +function isPromise(input) { + return hasProperty(input, "then") && "catch" in input && isFunction(input.then) && isFunction(input.catch); +} +/** + * Checks whether a value is `PromiseLike` (has a `then` method). + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise-like values with a + * callable `then` method. + * + * **Details** + * + * Performs a structural check for a callable `then`. + * + * **Example** (Guarding promise-like values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { then: () => {} } + * + * Predicate.isPromiseLike(data) // => true + * ``` + * + * @see {@link isPromise} + * @category guards + * @since 2.0.0 + */ +function isPromiseLike(input) { + return hasProperty(input, "then") && isFunction(input.then); +} +/** + * Checks whether a value is a `RegExp`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for regular expressions. + * + * **Details** + * + * Uses `instanceof RegExp`. + * + * **Example** (Guarding RegExp values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = /abc/ + * + * Predicate.isRegExp(data) // => true + * ``` + * + * @see {@link isDate} + * @category guards + * @since 3.9.0 + */ +function isRegExp(input) { + return input instanceof RegExp; +} +/** + * Composes two predicates or refinements into one. + * + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. + * + * **Example** (Composing refinements) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNumber: Predicate.Refinement = (u): u is number => typeof u === "number" + * const isInteger: Predicate.Refinement = (n): n is number => Number.isInteger(n) + * + * const isIntegerNumber = Predicate.compose(isNumber, isInteger) + * + * isIntegerNumber(1) // => true + * ``` + * + * @see {@link and} + * @see {@link Refinement} + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => ab(a) && bc(a)))); +/** + * Creates a predicate for tuples by applying predicates to each element. + * + * **When to use** + * + * Use when you want to validate tuple positions independently by lifting + * element predicates into a tuple predicate. + * + * **Details** + * + * Returns a refinement if any element predicate is a refinement. Evaluation + * stops at the first failing element. + * + * **Example** (Checking tuples) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const tupleCheck = Predicate.Tuple([(n: number) => n > 0, Predicate.isString]) + * + * tupleCheck([1, "ok"]) // => true + * ``` + * + * @see {@link Struct} + * @see {@link isTupleOf} + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return as => { + for (let i = 0; i < elements.length; i++) { + if (elements[i](as[i]) === false) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate for objects by applying predicates to named properties. + * + * **When to use** + * + * Use when you want to validate a record shape at runtime by lifting property + * predicates into an object predicate. + * + * **Details** + * + * Returns a refinement if any field predicate is a refinement. Only the + * specified keys are checked, and extra keys are ignored. + * + * **Example** (Checking structs) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const userCheck = Predicate.Struct({ + * id: Predicate.isNumber, + * name: Predicate.isString + * }) + * + * userCheck({ id: 1, name: "Ada" }) // => true + * ``` + * + * @see {@link Tuple} + * @see {@link hasProperty} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return a => { + for (const key of keys) { + if (!fields[key](a[key])) { + return false; + } + } + return true; + }; +} +/** + * Negates a predicate. + * + * **When to use** + * + * Use when you want the inverse of an existing predicate. + * + * **Details** + * + * Returns a new predicate that flips the boolean result. + * + * **Example** (Negating a predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNotString = Predicate.not(Predicate.isString) + * + * isNotString(1) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +function not(self) { + return a => !self(a); +} +/** + * Creates a predicate that returns `true` if either predicate is `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. + * + * **Example** (Checking either condition) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber) + * + * isStringOrNumber("a") // => true + * ``` + * + * @see {@link and} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) || that(a)))); +/** + * Creates a predicate that returns `true` only if both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. + * + * **Example** (Checking both conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAAndB = Predicate.and( + * Predicate.hasProperty("a"), + * Predicate.hasProperty("b") + * ) + * + * const input: unknown = JSON.parse(`{"a":1,"b":"ok"}`) + * if (hasAAndB(input)) { + * // input has both properties at this point + * const a = input.a + * const b = input.b + * + * const values = [a, b] // => [1, "ok"] + * } + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const and = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) && that(a)))); +/** + * Creates a predicate that returns `true` if exactly one predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with exclusive-or semantics. + * + * **Details** + * + * Returns `true` when results differ. + * + * **Example** (Checking exclusive-or conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const isPositive = (n: number) => n > 0 + * const either = Predicate.xor(isEven, isPositive) + * + * either(-2) // => true + * ``` + * + * @see {@link or} + * @see {@link and} + * @category combinators + * @since 2.0.0 + */ +const xor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) !== that(a)))); +/** + * Creates a predicate that returns `true` when both predicates agree. + * + * **When to use** + * + * Use when you want to check equivalence of two `Predicate`s. + * + * **Details** + * + * Returns `true` when both results are equal. + * + * **Example** (Defining equivalence) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const same = Predicate.eqv(isEven, isEven) + * + * same(3) // => true + * ``` + * + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const eqv = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) === that(a)))); +/** + * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. + * + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. + * + * **Details** + * + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. + * + * **Example** (Checking implication) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isAdult = (age: number) => age >= 18 + * const canVote = (age: number) => age >= 18 + * const implies = Predicate.implies(isAdult, canVote) + * + * implies(16) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @category combinators + * @since 2.0.0 + */ +const implies = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (antecedent, consequent) => a => antecedent(a) ? consequent(a) : true))); +/** + * Creates a predicate that returns `true` when neither predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NOR semantics. + * + * **Details** + * + * Returns the negation of `or`. + * + * **Example** (Checking NOR conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const neither = Predicate.nor(Predicate.isString, Predicate.isNumber) + * + * neither(true) // => true + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) || that(a))))); +/** + * Creates a predicate that returns `true` unless both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NAND semantics. + * + * **Details** + * + * Returns the negation of `and`. + * + * **Example** (Checking NAND conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const notBoth = Predicate.nand(Predicate.isString, Predicate.isNumber) + * + * notBoth("a") // => true + * ``` + * + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nand = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) && that(a))))); +/** + * Creates a predicate that returns `true` if all predicates in the collection return `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates to apply. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking all predicates) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const allChecks = Predicate.every([Predicate.isNumber, (n: number) => n > 0]) + * + * allChecks(2) // => true + * ``` + * + * @see {@link some} + * @see {@link and} + * @category combining + * @since 2.0.0 + */ +function every(collection) { + return a => { + for (const p of collection) { + if (!p(a)) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate that returns `true` if any predicate in the collection returns `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates and only need one to pass. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking any predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const anyCheck = Predicate.some([Predicate.isString, Predicate.isNumber]) + * + * anyCheck("ok") // => true + * ``` + * + * @see {@link every} + * @see {@link or} + * @category combining + * @since 2.0.0 + */ +function some(collection) { + return a => { + for (const p of collection) { + if (p(a)) { + return true; + } + } + return false; + }; +} +//# sourceMappingURL=Predicate.js.map +__webpack_require__.d(__webpack_exports__, { + $P: () => (isDate), + Bm: () => (isSymbol), + Et: () => (isNumber), + Kg: () => (isString), + Lm: () => (isBoolean), + Tn: () => (isFunction), + sI: () => (isBigInt), + xZ: () => (isIterable) +}, { + $J: isTagged, + i5: hasProperty +}); + + +}, +"./node_modules/effect/dist/Pull.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Exit_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/** + * Models one low-level pull step for stream-like consumers. + * + * A `Pull` is an `Effect` that can produce one `A`, fail with an + * ordinary error `E`, or signal end-of-input with `Cause.Done`. The + * separate done signal lets low-level consumers distinguish normal completion + * from failure. This module includes type extractors and helpers for detecting, + * filtering, catching, converting, and matching done signals separately from + * ordinary failures. + * + * @since 4.0.0 + */ + + + + + + +// ----------------------------------------------------------------------------- +// Done +// ----------------------------------------------------------------------------- +/** + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * + * @category error handling + * @since 4.0.0 + */ +const catchDone = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (effect, f) => _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk(effect, filterDoneLeftover, l => f(l))); +/** + * Checks whether a Cause contains any done errors. + * + * **When to use** + * + * Use when you need to test whether a pull failure cause represents normal + * completion and only need a boolean result. + * + * @see {@link isDoneFailure} for checking a single `Cause.Reason` + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * @see {@link filterNoDone} for selecting causes with no done failures + * + * @category predicates + * @since 4.0.0 + */ +const isDoneCause = cause => cause.reasons.some(isDoneFailure); +/** + * Checks whether a `Cause.Reason` is a `Fail` reason whose error is a + * `Cause.Done` signal. + * + * **When to use** + * + * Use when you need to identify done completion reasons while traversing + * `cause.reasons`, before handling ordinary failures. + * + * @see {@link isDoneCause} for checking an entire `Cause` for any done reason + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * + * @category guards + * @since 4.0.0 + */ +const isDoneFailure = failure => failure._tag === "Fail" && _Cause_js__rspack_import_2/* .isDone */.$L(failure.error); +/** + * Finds a `Cause.Done` failure in a `Cause`. + * + * **When to use** + * + * Use to separate `Cause.Done` completion from ordinary causes while preserving + * the typed done value. + * + * **Details** + * + * Returns a successful `Result` with the `Cause.Done` value when the cause + * contains a done signal and no other failures besides interruptions. When the + * done signal was merged with a real failure (for example a failing + * finalizer), the `Result` fails with the remaining cause, stripped of the + * done signal. Without a done signal the `Result` fails with the original + * cause. + * + * @category filtering + * @since 4.0.0 + */ +const filterDone = cause => { + let done; + let hasFailure = false; + for (const reason of cause.reasons) { + if (isDoneFailure(reason)) { + done ??= reason.error; + } else if (reason._tag !== "Interrupt") { + hasFailure = true; + } + } + if (done === undefined) return _Result_js__rspack_import_3/* .fail */.fJ(cause); + return hasFailure ? _Result_js__rspack_import_3/* .fail */.fJ(_Cause_js__rspack_import_2/* .fromReasons */.kO(cause.reasons.filter(reason => !isDoneFailure(reason)))) : _Result_js__rspack_import_3/* .succeed */.Py(done); +}; +/** + * Finds a `Cause.Done` failure in a cause whose done value is not used. + * + * **When to use** + * + * Use to detect `Cause.Done` completion in a `Cause` when the completion value + * is not part of the downstream logic. + * + * **Details** + * + * Returns a successful `Result` with the done marker when it is the only + * failure, otherwise returns a failed `Result` with the non-done cause. + * + * @see {@link filterDone} for preserving the typed `Cause.Done` value when the done payload matters + * @see {@link filterDoneLeftover} for extracting only the done leftover value + * @see {@link filterNoDone} for the inverse filter that succeeds only when no done failure is present + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneVoid = (/* unused pure expression or super */ null && (filterDone)); +/** + * Keeps a `Cause` only when it contains no `Cause.Done` failures. + * + * **When to use** + * + * Use to select ordinary failure causes for handling while leaving `Cause.Done` + * completion causes outside that handler. + * + * **Details** + * + * Returns a successful `Result` with the cause when every failure is non-done; + * otherwise returns a failed `Result` with the original cause. + * + * @see {@link filterDone} for the inverse typed done filter + * @see {@link filterDoneVoid} for done detection when the payload is not needed + * + * @category filtering + * @since 4.0.0 + */ +const filterNoDone = /*#__PURE__*/(/* unused pure expression or super */ null && (Filter.fromPredicate(cause => cause.reasons.every(failure => !isDoneFailure(failure))))); +/** + * Filters a Cause to extract the leftover value from done errors. + * + * **When to use** + * + * Use to extract only the leftover value carried by a `Cause.Done` completion + * signal. + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneLeftover = cause => { + const done = filterDone(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(done) ? done : _Result_js__rspack_import_3/* .succeed */.Py(done.success.value); +}; +/** + * Converts a `Cause` into an `Exit`, treating `Cause.Done` as successful + * completion. + * + * **When to use** + * + * Use to produce an `Exit` for finalizing a low-level pull workflow when a + * `Cause.Done` signal should be treated as success and any remaining cause + * should fail. + * + * **Details** + * + * If the done signal is the only failure in the cause, its leftover becomes + * the successful value. Otherwise the non-done cause becomes the failure + * cause. + * + * @see {@link filterDone} for extracting the done signal without converting the cause to an `Exit` + * @see {@link matchEffect} for handling `Pull` success, failure, and done outcomes directly + * + * @category converting + * @since 4.0.0 + */ +const doneExitFromCause = cause => { + const halt = filterDone(cause); + return !_Result_js__rspack_import_3/* .isFailure */.N6(halt) ? _Exit_js__rspack_import_4/* .succeed */.Py(halt.success.value) : _Exit_js__rspack_import_4/* .failCause */.AT(halt.failure); +}; +/** + * Pattern matches on a Pull, handling success, failure, and done cases. + * + * **When to use** + * + * Use to handle all three `Pull` outcomes with effectful handlers. + * + * **Example** (Matching Pull outcomes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Pull } from "effect" + * + * const pull = Cause.done("stream ended") + * + * const result = Pull.matchEffect(pull, { + * onSuccess: (value) => Effect.succeed(`Got value: ${value}`), + * onFailure: (cause) => Effect.succeed(`Got error: ${cause}`), + * onDone: (leftover) => Effect.succeed(`Stream halted with: ${leftover}`) + * }) + * + * await Effect.runPromise(result) // => "Stream halted with: stream ended" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, options) => _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu(self, { + onSuccess: options.onSuccess, + onFailure: cause => { + const halt = filterDone(cause); + return !_Result_js__rspack_import_3/* .isFailure */.N6(halt) ? options.onDone(halt.success.value) : options.onFailure(halt.failure); + } +})); +//# sourceMappingURL=Pull.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Dc: filterDone, + Og: isDoneCause, + aU: doneExitFromCause, + m8: catchDone, + tv: matchEffect +}); + + +}, +"./node_modules/effect/dist/Queue.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _MutableList_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/MutableList.js"); +/* import */ var _Pull_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Pull.js"); +/** + * Passes values asynchronously between fibers. + * + * A `Queue` accepts values, hands each value to one consumer in offer + * order, and can complete, fail, interrupt, or shut down. Queues can be bounded + * or unbounded, and bounded queues can suspend, drop, or slide values when + * producers are faster than consumers. + * + * @since 3.8.0 + */ + + + + + + + + + +const TypeId = "~effect/Queue"; +const EnqueueTypeId = "~effect/Queue/Enqueue"; +const DequeueTypeId = "~effect/Queue/Dequeue"; +/** + * Type guard to check if a value is a Queue. + * + * **When to use** + * + * Use to narrow an unknown value to a full `Queue` before passing it to APIs + * that need both offering and taking capabilities. + * + * @see {@link isEnqueue} for checking values that only need write access + * @see {@link isDequeue} for checking values that only need read access + * + * @category guards + * @since 2.0.0 + */ +const isQueue = u => hasProperty(u, TypeId); +/** + * Type guard to check if a value is an Enqueue. + * + * **When to use** + * + * Use to narrow an unknown value before calling queue operations that require + * write-side access. + * + * **Gotchas** + * + * A full `Queue` also satisfies this guard because every queue includes the + * enqueue side. + * + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isDequeue} for checking for the read side of a queue + * @see {@link asEnqueue} for narrowing an existing `Queue` to its write-only interface + * + * @category guards + * @since 2.0.0 + */ +const isEnqueue = u => hasProperty(u, EnqueueTypeId); +/** + * Type guard to check if a value is a Dequeue. + * + * **When to use** + * + * Use to narrow an unknown value before passing it to read-side queue + * operations. + * + * @see {@link Dequeue} for the read-side queue handle checked by this guard + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isEnqueue} for checking for the write side of a queue + * @see {@link asDequeue} for narrowing an existing `Queue` to its read-only interface + * + * @category guards + * @since 2.0.0 + */ +const isDequeue = u => hasProperty(u, DequeueTypeId); +/** + * Converts a `Queue` to its write-only `Enqueue` interface. + * + * **When to use** + * + * Use to expose only the producer side of a `Queue` to code that should offer + * values or signal queue lifecycle. + * + * **Gotchas** + * + * This is a type-level capability restriction. It returns the same queue + * object, so it does not hide read operations at runtime. + * + * @see {@link asDequeue} for exposing only the read side of a `Queue` + * @see {@link Enqueue} for the write-only queue handle returned by this conversion + * + * @category converting + * @since 4.0.0 + */ +const asEnqueue = self => self; +/** + * Narrows a `Queue` to a `Dequeue`, exposing the consumer side of the queue. + * + * **When to use** + * + * Use to pass a queue to code that should consume values while keeping + * producer-side operations out of that code's TypeScript type. + * + * **Gotchas** + * + * This is a type-level narrowing operation. It returns the same queue object + * and does not create a runtime wrapper. + * + * @see {@link asEnqueue} for narrowing a queue to its producer side + * @see {@link Dequeue} for the consumer-side queue handle returned by this function + * + * @category converting + * @since 4.0.0 + */ +const asDequeue = (/* unused pure expression or super */ null && (identity)); +const variance = { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_ +}; +const QueueProto = { + [TypeId]: variance, + [EnqueueTypeId]: variance, + [DequeueTypeId]: variance, + ..._internal_core_js__rspack_import_1/* .PipeInspectableProto */.fU, + toJSON() { + return { + _id: "effect/Queue", + state: this.state._tag, + size: sizeUnsafe(this) + }; + } +}; +/** + * Creates a `Queue` with optional capacity and overflow strategy. + * + * **Details** + * + * By default the queue is unbounded and uses the `"suspend"` strategy. Provide + * `capacity` for a bounded queue and choose `"suspend"`, `"dropping"`, or + * `"sliding"` to control what happens when the queue is full. The returned + * queue can be offered to, taken from, failed, ended, interrupted, or shut down. + * + * **Example** (Creating queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.make() + * + * // add messages to the queue + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offerAll(queue, [3, 4, 5]) + * + * // take messages from the queue + * const messages = yield* Queue.takeAll(queue) + * + * // signal that the queue is done + * yield* Queue.end(queue) + * const done = yield* Effect.flip(Queue.take(queue)) + * + * // signal that another queue has failed + * const failedQueue = yield* Queue.make() + * const failed = yield* Queue.fail(failedQueue, "boom") + * return { messages, done, failed } + * }) + * + * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], done: Cause.Done(), failed: true } + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = options => _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => { + const self = Object.create(QueueProto); + self.dispatcher = fiber.currentDispatcher; + self.capacity = options?.capacity ?? Number.POSITIVE_INFINITY; + self.strategy = options?.strategy ?? "suspend"; + self.messages = _MutableList_js__rspack_import_2/* .make */.L8(); + self.scheduleRunning = false; + self.state = { + _tag: "Open", + takers: new Set(), + offers: new Set(), + awaiters: new Set() + }; + return _internal_effect_js__rspack_import_3/* .succeed */.PyW(self); +}); +/** + * Creates a bounded queue with the specified capacity that uses backpressure strategy. + * + * **Details** + * + * When the queue reaches capacity, producers will be suspended until space becomes available. + * This ensures all messages are processed but may slow down producers. + * + * **Example** (Creating bounded queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // This will succeed as queue has capacity + * yield* Queue.offer(queue, "first") + * yield* Queue.offer(queue, "second") + * + * const size = yield* Queue.size(queue) + * return size + * }) + * + * await Effect.runPromise(program) // => 2 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const bounded = capacity => make({ + capacity +}); +/** + * Creates a bounded queue with sliding strategy. When the queue reaches capacity, + * new elements are added and the oldest elements are dropped. + * + * **When to use** + * + * Use when you need producer offers not to block and can accept dropping the + * oldest messages, such as when maintaining a rolling window of recent values. + * + * **Example** (Creating sliding queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.sliding(3) + * + * // Fill the queue to capacity + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * + * // This will succeed, dropping the oldest element (1) + * yield* Queue.offer(queue, 4) + * + * const all = yield* Queue.takeAll(queue) + * return all + * }) + * + * await Effect.runPromise(program) // => [2, 3, 4] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sliding = capacity => make({ + capacity, + strategy: "sliding" +}); +/** + * Creates a bounded queue with dropping strategy. When the queue reaches capacity, + * new elements are dropped and the offer operation returns false. + * + * **When to use** + * + * Use when you need producer offers not to block while preserving existing + * queued messages, even if new messages may be dropped when the queue is full. + * + * **Example** (Creating dropping queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.dropping(2) + * + * // Fill the queue to capacity + * const success1 = yield* Queue.offer(queue, 1) + * const success2 = yield* Queue.offer(queue, 2) + * + * // This will be dropped + * const success3 = yield* Queue.offer(queue, 3) + * + * const all = yield* Queue.takeAll(queue) + * return [success1, success2, success3, all] + * }) + * + * await Effect.runPromise(program) // => [true, true, false, [1, 2]] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const dropping = capacity => make({ + capacity, + strategy: "dropping" +}); +/** + * Creates an unbounded queue that can grow to any size without blocking producers. + * + * **When to use** + * + * Use when you need producers to add messages without backpressure and accept + * unbounded memory growth. + * + * **Example** (Creating unbounded queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.unbounded() + * + * // Producers can always add messages without blocking + * yield* Queue.offer(queue, "message1") + * yield* Queue.offer(queue, "message2") + * yield* Queue.offerAll(queue, ["message3", "message4", "message5"]) + * + * // Check current size + * const size = yield* Queue.size(queue) + * + * // Take all messages + * const messages = yield* Queue.takeAll(queue) + * return { size, messages } + * }) + * + * await Effect.runPromise(program) // => { size: 5, messages: ["message1", "message2", "message3", "message4", "message5"] } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unbounded = () => make(); +/** + * Adds a message to the queue. Returns `false` if the queue is done. + * + * **Details** + * + * For bounded queues, this operation may suspend if the queue is at capacity, + * depending on the backpressure strategy. For dropping/sliding queues, it may + * return false or succeed immediately by dropping/sliding existing messages. + * + * **Example** (Offering a value) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Successfully add messages to queue + * const success1 = yield* Queue.offer(queue, 1) + * const success2 = yield* Queue.offer(queue, 2) + * + * // Queue state + * const size = yield* Queue.size(queue) + * return { offered: [success1, success2], size } + * }) + * + * await Effect.runPromise(program) // => { offered: [true, true], size: 2 } + * ``` + * + * @category offering + * @since 2.0.0 + */ +const offer = (self, message) => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (self.state._tag !== "Open") { + return exitFalse; + } else if (self.messages.length >= self.capacity) { + switch (self.strategy) { + case "dropping": + return exitFalse; + case "suspend": + if (self.capacity <= 0 && self.state.takers.size > 0) { + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + releaseTakers(self); + return exitTrue; + } + return offerRemainingSingle(self, message); + case "sliding": + _MutableList_js__rspack_import_2/* .take */.s(self.messages); + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + return exitTrue; + } + } + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, message); + scheduleReleaseTaker(self); + return exitTrue; +}); +/** + * Adds a message to the queue synchronously. Returns `false` if the queue is done. + * + * **When to use** + * + * Use when you are already in synchronous queue internals or a performance + * boundary where wrapping the mutation in `Effect` is intentionally avoided. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * Use this only when you're certain about the synchronous nature of the operation. + * + * **Example** (Offering a value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * // Create a queue effect and extract the queue for unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Add messages synchronously using unsafe API + * const success1 = Queue.offerUnsafe(queue, 1) + * const success2 = Queue.offerUnsafe(queue, 2) + * + * // Check current size + * const size = Queue.sizeUnsafe(queue) + * return { offered: [success1, success2], size } + * }) + * + * await Effect.runPromise(program) // => { offered: [true, true], size: 2 } + * ``` + * + * @category offering + * @since 4.0.0 + */ +const offerUnsafe = (self, message) => { + if (self.state._tag !== "Open") { + return false; + } else if (self.messages.length >= self.capacity) { + if (self.strategy === "sliding") { + MutableList.take(self.messages); + MutableList.append(self.messages, message); + return true; + } else if (self.capacity <= 0 && self.state.takers.size > 0) { + MutableList.append(self.messages, message); + releaseTakers(self); + return true; + } + return false; + } + MutableList.append(self.messages, message); + scheduleReleaseTaker(self); + return true; +}; +/** + * Adds multiple messages to the queue. Returns the remaining messages that + * were not added. + * + * **When to use** + * + * Use when producers can submit a batch at once and need to know which messages + * did not fit under the queue's capacity strategy. + * + * **Details** + * + * For bounded queues, this operation may suspend if the queue doesn't have + * enough capacity. The operation returns an array of messages that couldn't + * be added (empty array means all messages were successfully added). + * + * **Example** (Offering multiple values) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.dropping(3) + * + * // Try to add more messages than capacity without suspending + * const remaining1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * return remaining1 + * }) + * + * await Effect.runPromise(program) // => [4, 5] + * ``` + * + * @category offering + * @since 2.0.0 + */ +const offerAll = (self, messages) => internalEffect.suspend(() => { + if (self.state._tag !== "Open") { + return internalEffect.succeed(Arr.fromIterable(messages)); + } + const remaining = offerAllUnsafe(self, messages); + if (remaining.length === 0) { + return core.exitSucceed([]); + } else if (self.strategy === "dropping") { + return internalEffect.succeed(remaining); + } + return offerRemainingArray(self, remaining); +}); +/** + * Adds multiple messages to the queue synchronously. Returns the remaining messages that + * were not added. + * + * **When to use** + * + * Use when queue internals or a performance boundary need a synchronous batch + * offer and can handle any messages that do not fit. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Offering multiple values synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * // Create a bounded queue and use unsafe API + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Try to add 5 messages to capacity-3 queue using unsafe API + * const remaining = Queue.offerAllUnsafe(queue, [1, 2, 3, 4, 5]) + * + * // Check what's in the queue + * const size = Queue.sizeUnsafe(queue) + * return { remaining, size } + * }) + * + * await Effect.runPromise(program) // => { remaining: [4, 5], size: 3 } + * ``` + * + * @category offering + * @since 4.0.0 + */ +const offerAllUnsafe = (self, messages) => { + if (self.state._tag !== "Open") { + return Arr.fromIterable(messages); + } else if (self.capacity === Number.POSITIVE_INFINITY || self.strategy === "sliding") { + MutableList.appendAll(self.messages, messages); + if (self.strategy === "sliding") { + MutableList.takeN(self.messages, self.messages.length - self.capacity); + } + scheduleReleaseTaker(self); + return []; + } + const free = self.capacity <= 0 ? self.state.takers.size : self.capacity - self.messages.length; + if (free === 0) { + return Arr.fromIterable(messages); + } + const remaining = []; + let i = 0; + for (const message of messages) { + if (i < free) { + MutableList.append(self.messages, message); + } else { + remaining.push(message); + } + i++; + } + scheduleReleaseTaker(self); + return remaining; +}; +/** + * Fails the queue with an error. If the queue is already done, `false` is + * returned. + * + * **Example** (Failing queues with an error) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Fail the queue with an error + * const failed = yield* Queue.fail(queue, "Something went wrong") + * + * // Taking from the failed queue fails with the error + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Something went wrong")] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const fail = (self, error) => failCause(self, core.causeFail(error)); +/** + * Fails the queue with a cause. If the queue is already done, `false` is + * returned. + * + * **Example** (Failing queues with a cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create a cause and fail the queue + * const cause = Cause.fail("Queue processing failed") + * const failed = yield* Queue.failCause(queue, cause) + * + * // The queue is now done with the specified failure cause + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Queue processing failed"))] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const failCause = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, cause) => _internal_effect_js__rspack_import_3/* .sync */.OH5(() => failCauseUnsafe(self, cause))); +/** + * Fails the queue with a cause synchronously. If the queue is already done, `false` is + * returned. + * + * **When to use** + * + * Use when queue completion must be driven from synchronous internals while + * preserving the full failure `Cause`. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Failing queues with a cause synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create a cause and fail the queue synchronously + * const cause = Cause.fail("Processing error") + * const failed = Queue.failCauseUnsafe(queue, cause) + * + * // The queue is now done with the specified failure cause + * const exit = Queue.takeUnsafe(queue) + * return [failed, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Processing error"))] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const failCauseUnsafe = (self, cause) => { + if (self.state._tag !== "Open") { + return false; + } + const exit = _internal_core_js__rspack_import_1/* .exitFailCause */.cb(cause); + const fail = _internal_effect_js__rspack_import_3/* .exitZipRight */.il9(exit, exitFailDone); + if (self.state.offers.size === 0 && self.messages.length === 0) { + finalize(self, fail); + return true; + } + self.state = { + ...self.state, + _tag: "Closing", + exit: fail + }; + return true; +}; +/** + * Signals queue completion. + * + * **When to use** + * + * Use to stop accepting new offers while allowing already queued messages to be + * consumed. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Example** (Ending queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Signal completion - no more messages will be accepted + * const ended = yield* Queue.end(queue) + * + * // Trying to offer more messages will return false + * const offerResult = yield* Queue.offer(queue, 3) + * + * // But we can still take existing messages + * const message = yield* Queue.take(queue) + * return [ended, offerResult, message] + * }) + * + * await Effect.runPromise(program) // => [true, false, 1] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const end = self => failCause(self, core.causeFail(core.Done())); +/** + * Signals queue completion synchronously. + * + * **When to use** + * + * Use when implementing low-level queue integrations that must complete a queue + * without wrapping the operation in `Effect`. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Gotchas** + * + * This is an unsafe operation that directly modifies the queue without Effect wrapping. + * + * **Example** (Ending queues synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * // Create a queue and use unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * + * // End the queue synchronously + * const ended = Queue.endUnsafe(queue) + * + * // Existing messages can still be consumed while the queue is closing + * const states = [queue.state._tag] + * + * Queue.takeUnsafe(queue) + * Queue.takeUnsafe(queue) + * + * // After buffered messages are consumed, the queue is done + * states.push(queue.state._tag) + * return { ended, states } + * }) + * + * await Effect.runPromise(program) // => { ended: true, states: ["Closing", "Done"] } + * ``` + * + * @category completion + * @since 4.0.0 + */ +const endUnsafe = self => failCauseUnsafe(self, core.causeFail(core.Done())); +/** + * Interrupts the queue gracefully, transitioning it to a closing state. + * + * **Details** + * + * This operation stops accepting new offers but allows existing messages to be consumed. + * Once all messages are drained, the queue transitions to the Done state with an interrupt cause. + * + * **Example** (Interrupting queues gracefully) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Interrupt gracefully - no more offers accepted, but messages can be consumed + * const interrupted = yield* Queue.interrupt(queue) + * + * // Trying to offer more messages will return false + * const offerResult = yield* Queue.offer(queue, 3) + * + * // But we can still take existing messages + * const message1 = yield* Queue.take(queue) + * + * const message2 = yield* Queue.take(queue) + * + * // After all messages are consumed, queue is done + * const isDone = queue.state._tag === "Done" + * return { interrupted, offerResult, messages: [message1, message2], isDone } + * }) + * + * await Effect.runPromise(program) // => { interrupted: true, offerResult: false, messages: [1, 2], isDone: true } + * ``` + * + * @category completion + * @since 4.0.0 + */ +const interrupt = self => core.withFiber(fiber => failCause(self, internalEffect.causeInterrupt(fiber.id))); +/** + * Shuts down the queue immediately, discarding buffered messages and resuming + * pending operations. + * + * **Details** + * + * The operation is idempotent and returns `true`, including when the queue has + * already been shut down or completed. + * + * **Example** (Shutting down queues) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(2) + * + * // Add messages + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * + * // Shutdown clears buffered messages and prevents further offers + * const wasShutdown = yield* Queue.shutdown(queue) + * + * // Queue is now done and cleared + * const size = yield* Queue.size(queue) + * return { wasShutdown, size } + * }) + * + * await Effect.runPromise(program) // => { wasShutdown: true, size: 0 } + * ``` + * + * @category completion + * @since 2.0.0 + */ +const shutdown = self => _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag === "Done") { + return true; + } + _MutableList_js__rspack_import_2/* .clear */.IU(self.messages); + const offers = self.state.offers; + finalize(self, self.state._tag === "Open" ? exitInterrupt : self.state.exit); + if (offers.size > 0) { + for (const entry of offers) { + if (entry._tag === "Single") { + entry.resume(exitFalse); + } else { + entry.resume(_internal_core_js__rspack_import_1/* .exitSucceed */.xt(entry.remaining.slice(entry.offset))); + } + } + offers.clear(); + } + return true; +}); +/** + * Takes and returns all currently buffered messages without waiting for more. + * + * **Details** + * + * Returns an empty array when the queue is empty or has completed normally. If + * the queue has failed, the effect fails with the queue's error. + * + * **Example** (Clearing queued values) + * + * ```ts import.meta.vitest + * import { Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Clear all messages from the queue + * const messages = yield* Queue.clear(queue) + * + * // Queue is now empty + * const size = yield* Queue.size(queue) + * + * // Clearing empty queue returns empty array + * const empty = yield* Queue.clear(queue) + * return { messages, size, empty } + * }) + * + * await Effect.runPromise(program) // => { messages: [1, 2, 3, 4, 5], size: 0, empty: [] } + * ``` + * + * @category taking + * @since 4.0.0 + */ +const clear = self => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => { + if (self.state._tag === "Done") { + if (_Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause)) { + return _internal_effect_js__rspack_import_3/* .succeed */.PyW([]); + } + return self.state.exit; + } + const messages = takeAllUnsafe(self); + releaseCapacity(self); + return _internal_effect_js__rspack_import_3/* .succeed */.PyW(messages); +}); +/** + * Takes all currently available messages, waiting until at least one message + * is available when the queue is empty. + * + * **When to use** + * + * Use when consumers should process the next non-empty batch of buffered + * messages instead of repeatedly taking one message at a time. + * + * **Details** + * + * Returns a non-empty array. If the queue completes or fails before a message + * can be taken, the effect fails with the queue's terminal error. + * + * **Example** (Taking all available values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Take all available messages + * const messages1 = yield* Queue.takeAll(queue) + * return messages1 + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeAll = self => takeBetween(self, 1, Number.POSITIVE_INFINITY); +/** + * Takes all messages from the queue, until the queue has errored or is done. + * + * **Example** (Collecting values until completion) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(5) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * yield* Queue.end(queue) + * + * // Collect all available messages + * return yield* Queue.collect(queue) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category taking + * @since 4.0.0 + */ +const collect = self => internalEffect.suspend(() => { + const out = Arr.empty(); + return internalEffect.as(Pull.catchDone(internalEffect.whileLoop({ + while: constTrue, + body: constant(takeAll(self)), + step(items) { + for (let i = 0; i < items.length; i++) { + out.push(items[i]); + } + } + }), () => internalEffect.void), out); +}); +/** + * Takes up to `n` messages from the queue. + * + * **Details** + * + * The operation may wait until enough messages are available to satisfy the + * queue's batching rules. If `n` is less than or equal to zero, it succeeds + * with an empty array. If the queue completes or fails before messages can be + * taken, the effect fails with the queue's terminal error. + * + * **Example** (Taking a fixed number of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7]) + * + * // Take exactly 3 messages + * const first3 = yield* Queue.takeN(queue, 3) + * + * // Take exactly 2 more messages + * const next2 = yield* Queue.takeN(queue, 2) + * + * // Take remaining messages + * const remaining = yield* Queue.takeN(queue, 2) + * return [first3, next2, remaining] + * }) + * + * await Effect.runPromise(program) // => [[1, 2, 3], [4, 5], [6, 7]] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeN = (self, n) => takeBetween(self, n, n); +/** + * Takes between `min` and `max` messages from the queue. + * + * **Details** + * + * The operation waits when fewer than the required minimum messages are + * available. It returns at most `max` messages. If the queue completes or fails + * before the minimum can be satisfied, the effect fails with the queue's + * terminal error. + * + * **Example** (Taking a bounded batch of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add several messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7, 8]) + * + * // Take between 2 and 5 messages + * const batch1 = yield* Queue.takeBetween(queue, 2, 5) + * + * // Take between 1 and 10 messages (but only 3 remain) + * const batch2 = yield* Queue.takeBetween(queue, 1, 10) + * + * // No more messages available, will wait or return done + * // const batch3 = yield* Queue.takeBetween(queue, 1, 3) + * return [batch1, batch2] + * }) + * + * await Effect.runPromise(program) // => [[1, 2, 3, 4, 5], [6, 7, 8]] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const takeBetween = (self, min, max) => internalEffect.suspend(() => takeBetweenUnsafe(self, min, max) ?? internalEffect.andThen(awaitTake(self), takeBetween(self, 1, max))); +/** + * Takes a single message from the queue, or wait for a message to be + * available. + * + * **Details** + * + * If the queue is done, it will fail with `Done`. If the + * queue fails, the Effect will fail with the error. + * + * **Example** (Taking one value) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * // Add some messages + * yield* Queue.offer(queue, "first") + * yield* Queue.offer(queue, "second") + * + * // Take messages one by one + * const msg1 = yield* Queue.take(queue) + * const msg2 = yield* Queue.take(queue) + * + * // End the queue + * yield* Queue.end(queue) + * + * // Taking from an ended queue fails with Done + * const result = yield* Effect.exit(Queue.take(queue)) + * return [[msg1, msg2], result] + * }) + * + * await Effect.runPromise(program) // => [["first", "second"], Exit.fail(Cause.Done())] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const take = self => _internal_effect_js__rspack_import_3/* .suspend */.DYE(() => takeUnsafe(self) ?? _internal_effect_js__rspack_import_3/* .andThen */.hgn(awaitTake(self), take(self))); +/** + * Attempts to take one item from the queue without waiting. + * + * **Details** + * + * Returns `Option.some` when an item is immediately available. Returns + * `Option.none` when no item is available, when the queue is done, or when the + * immediate take observes a queue failure. + * + * **Example** (Polling without blocking) + * + * ```ts import.meta.vitest + * import { Effect, Option, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Poll returns Option.none if empty + * const maybe1 = yield* Queue.poll(queue) + * + * // Add an item + * yield* Queue.offer(queue, 42) + * + * // Poll returns Option.some with the item + * const maybe2 = yield* Queue.poll(queue) + * return [maybe1, maybe2] + * }) + * + * await Effect.runPromise(program) // => [Option.none(), Option.some(42)] + * ``` + * + * @category taking + * @since 2.0.0 + */ +const poll = self => internalEffect.suspend(() => { + const result = takeUnsafe(self); + if (result === undefined) { + return internalEffect.succeed(Option.none()); + } + if (result._tag === "Success") { + return internalEffect.succeed(Option.some(result.value)); + } + return internalEffect.succeed(Option.none()); +}); +/** + * Peeks at the next item without removing it. + * + * **Details** + * + * Blocks until an item is available. If the queue is done or fails, the error is propagated. + * + * **Example** (Peeking at the next value) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * yield* Queue.offer(queue, 42) + * + * // Peek at the next item without removing it + * const item = yield* Queue.peek(queue) + * return item + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category taking + * @since 4.0.0 + */ +const peek = self => internalEffect.suspend(() => { + if (self.state._tag === "Done") { + return self.state.exit; + } + if (self.messages.length > 0 && self.messages.head) { + return internalEffect.succeed(self.messages.head.array[self.messages.head.offset]); + } + return internalEffect.andThen(awaitTake(self), peek(self)); +}); +/** + * Attempts to take one message from the queue synchronously. + * + * **When to use** + * + * Use when polling queue internals must not suspend or register a waiting taker, + * and `undefined` is an acceptable result for an empty queue. + * + * **Details** + * + * Returns an `Exit` for an immediately available message or for the queue's + * terminal state. Returns `undefined` when no message is immediately available. + * This operation does not wait or register a taker. + * + * **Example** (Taking one value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Queue } from "effect" + * + * // Create a queue and use unsafe operations + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * + * // Take a message synchronously + * const result1 = Queue.takeUnsafe(queue) + * + * const result2 = Queue.takeUnsafe(queue) + * + * // No more messages - returns undefined + * const result3 = Queue.takeUnsafe(queue) + * return [result1, result2, result3] + * }) + * + * await Effect.runPromise(program) // => [Exit.succeed(1), Exit.succeed(2), undefined] + * ``` + * + * @category taking + * @since 4.0.0 + */ +const takeUnsafe = self => { + if (self.state._tag === "Done") { + return self.state.exit; + } + if (self.messages.length > 0) { + const message = _MutableList_js__rspack_import_2/* .take */.s(self.messages); + releaseCapacity(self); + return _internal_core_js__rspack_import_1/* .exitSucceed */.xt(message); + } else if (self.capacity <= 0 && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const message = _MutableList_js__rspack_import_2/* .take */.s(self.messages); + releaseCapacity(self); + return _internal_core_js__rspack_import_1/* .exitSucceed */.xt(message); + } + return undefined; +}; +const await_ = self => internalEffect.callback(resume => { + const awaiter = effect => resume(Pull.catchDone(effect, () => internalEffect.exitVoid)); + if (self.state._tag === "Done") { + return awaiter(self.state.exit); + } + self.state.awaiters.add(awaiter); + return internalEffect.sync(() => { + if (self.state._tag !== "Done") { + self.state.awaiters.delete(awaiter); + } + }); +}); + +/** + * Returns the current number of buffered messages in the queue. + * + * **Details** + * + * After `end`, a queue remains `Closing` while buffered messages are drained, + * and its size continues to include those messages. A `Done` queue reports a + * size of `0`. + * + * **Example** (Checking queue size) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Check size of empty queue + * const size1 = yield* Queue.size(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) + * + * // Check size after adding messages + * const size2 = yield* Queue.size(queue) + * + * // End the queue + * yield* Queue.end(queue) + * + * // Ending retains the buffered size while the queue is Closing + * const size3 = yield* Queue.size(queue) + * return [size1, size2, size3] + * }) + * + * await Effect.runPromise(program) // => [0, 5, 5] + * ``` + * + * @category sizes + * @since 2.0.0 + */ +const size = self => internalEffect.sync(() => sizeUnsafe(self)); +/** + * Checks whether the queue is full. + * + * **Example** (Checking if queues are full) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * const before = yield* Queue.isFull(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3]) + * + * const after = yield* Queue.isFull(queue) + * return [before, after] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFull = self => internalEffect.sync(() => isFullUnsafe(self)); +/** + * Returns the current number of buffered messages in the queue synchronously. + * + * **When to use** + * + * Use when you need an immediate `Queue` size snapshot for diagnostics or + * internals and do not need the read wrapped in `Effect`. + * + * **Details** + * + * After `endUnsafe`, a queue remains `Closing` while buffered messages are + * drained, and its size continues to include those messages. A `Done` queue + * reports a size of `0`. This unsafe operation reads the queue state directly + * without Effect wrapping. + * + * **Example** (Checking queue size synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Check size of empty queue + * const size1 = Queue.sizeUnsafe(queue) + * + * // Add some messages + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * Queue.offerUnsafe(queue, 3) + * + * // Check size after adding messages + * const size2 = Queue.sizeUnsafe(queue) + * + * // End the queue + * Queue.endUnsafe(queue) + * + * // Ending retains the buffered size while the queue is Closing + * const size3 = Queue.sizeUnsafe(queue) + * return [size1, size2, size3] + * }) + * + * await Effect.runPromise(program) // => [0, 3, 3] + * ``` + * + * @category sizes + * @since 4.0.0 + */ +const sizeUnsafe = self => self.state._tag === "Done" ? 0 : self.messages.length; +/** + * Checks whether the queue is full synchronously. + * + * **When to use** + * + * Use when an immediate `Queue` capacity snapshot is needed outside effectful + * code and racing queue changes are acceptable. + * + * **Example** (Checking fullness synchronously) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(3) + * + * const before = Queue.isFullUnsafe(queue) + * + * // Add some messages + * yield* Queue.offerAll(queue, [1, 2, 3]) + * + * const after = Queue.isFullUnsafe(queue) + * return [before, after] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isFullUnsafe = self => sizeUnsafe(self) === self.capacity; +/** + * Runs an `Effect` into a `Queue`, where success ends the queue and failure + * fails the queue. + * + * **Example** (Running effects into queues) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Queue } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(10) + * + * // Create an effect that succeeds + * const dataProcessing = Effect.gen(function*() { + * yield* Effect.yieldNow + * return "Processing completed successfully" + * }) + * + * // Pipe the effect into the queue + * // If dataProcessing succeeds, queue ends successfully + * // If dataProcessing fails, queue fails with the error + * const effectIntoQueue = Queue.into(queue)(dataProcessing) + * + * const wasCompleted = yield* effectIntoQueue + * const exit = yield* Effect.exit(Queue.take(queue)) + * return [wasCompleted, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail(Cause.Done())] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const into = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, self) => internalEffect.uninterruptibleMask(restore => internalEffect.matchCauseEffect(restore(effect), { + onFailure: cause => failCause(self, cause), + onSuccess: _ => end(self) +}))))); +// ----------------------------------------------------------------------------- +// internals +// ----------------------------------------------------------------------------- +// +const exitFalse = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitSucceed */.xt(false); +const exitTrue = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitSucceed */.xt(true); +const exitFailDone = /*#__PURE__*/_internal_core_js__rspack_import_1/* .exitFail */.Rk(/*#__PURE__*/_internal_core_js__rspack_import_1/* .Done */.RS()); +const exitInterrupt = /*#__PURE__*/_internal_effect_js__rspack_import_3/* .exitInterrupt */._sz(); +const releaseTakers = self => { + self.scheduleRunning = false; + if (self.state._tag === "Done" || self.state.takers.size === 0) { + return; + } + for (const taker of self.state.takers) { + self.state.takers.delete(taker); + taker(_internal_effect_js__rspack_import_3/* .exitVoid */.x5l); + if (self.messages.length === 0) { + break; + } + } +}; +const scheduleReleaseTaker = self => { + if (self.scheduleRunning || self.state._tag === "Done" || self.state.takers.size === 0) { + return; + } + self.scheduleRunning = true; + self.dispatcher.scheduleTask(() => releaseTakers(self), 0); +}; +const takeBetweenUnsafe = (self, min, max) => { + if (self.state._tag === "Done") { + return self.state.exit; + } else if (max <= 0 || min <= 0) { + return core.exitSucceed([]); + } else if (self.capacity <= 0 && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const messages = [MutableList.take(self.messages)]; + releaseCapacity(self); + return core.exitSucceed(messages); + } + min = Math.min(min, self.capacity || 1); + if (min <= self.messages.length) { + const messages = MutableList.takeN(self.messages, max); + releaseCapacity(self); + return core.exitSucceed(messages); + } +}; +const offerRemainingSingle = (self, message) => { + return _internal_effect_js__rspack_import_3/* .callback */.E2r(resume => { + if (self.state._tag !== "Open") { + return resume(exitFalse); + } + const entry = { + _tag: "Single", + message, + resume + }; + self.state.offers.add(entry); + return _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag === "Open") { + self.state.offers.delete(entry); + } + }); + }); +}; +const offerRemainingArray = (self, remaining) => { + return internalEffect.callback(resume => { + if (self.state._tag !== "Open") { + return resume(core.exitSucceed(remaining)); + } + const entry = { + _tag: "Array", + remaining, + offset: 0, + resume + }; + self.state.offers.add(entry); + return internalEffect.sync(() => { + if (self.state._tag === "Open") { + self.state.offers.delete(entry); + } + }); + }); +}; +const releaseCapacity = self => { + if (self.state._tag === "Done") { + return _Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause); + } else if (self.state.offers.size === 0) { + if (self.state._tag === "Closing" && self.messages.length === 0) { + finalize(self, self.state.exit); + return _Pull_js__rspack_import_4/* .isDoneCause */.Og(self.state.exit.cause); + } + return false; + } + let n = self.capacity - self.messages.length; + for (const entry of self.state.offers) { + if (n === 0) break;else if (entry._tag === "Single") { + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, entry.message); + n--; + entry.resume(exitTrue); + self.state.offers.delete(entry); + } else { + for (; entry.offset < entry.remaining.length; entry.offset++) { + if (n === 0) return false; + _MutableList_js__rspack_import_2/* .append */.BC(self.messages, entry.remaining[entry.offset]); + n--; + } + entry.resume(_internal_core_js__rspack_import_1/* .exitSucceed */.xt([])); + self.state.offers.delete(entry); + } + } + return false; +}; +const awaitTake = self => _internal_effect_js__rspack_import_3/* .callback */.E2r(resume => { + if (self.state._tag === "Done") { + return resume(self.state.exit); + } + self.state.takers.add(resume); + return _internal_effect_js__rspack_import_3/* .sync */.OH5(() => { + if (self.state._tag !== "Done") { + self.state.takers.delete(resume); + } + }); +}); +const takeAllUnsafe = self => { + if (self.messages.length > 0) { + const messages = _MutableList_js__rspack_import_2/* .takeAll */.h0(self.messages); + releaseCapacity(self); + return messages; + } else if (self.state._tag !== "Done" && self.state.offers.size > 0) { + self.capacity = 1; + releaseCapacity(self); + self.capacity = 0; + const messages = [_MutableList_js__rspack_import_2/* .take */.s(self.messages)]; + releaseCapacity(self); + return messages; + } + return []; +}; +const finalize = (self, exit) => { + if (self.state._tag === "Done") { + return; + } + const openState = self.state; + self.state = { + _tag: "Done", + exit + }; + for (const taker of openState.takers) { + taker(exit); + } + openState.takers.clear(); + for (const awaiter of openState.awaiters) { + awaiter(exit); + } + openState.awaiters.clear(); +}; +//# sourceMappingURL=Queue.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + AT: failCause, + IU: clear, + Mm: bounded, + _1: failCauseUnsafe, + n_: shutdown, + s: take, + x: offer +}); + + +}, +"./node_modules/effect/dist/Record.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_record_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/** + * Works with plain JavaScript records as immutable key/value dictionaries. + * + * A record is an object whose keys are strings or symbols. This module includes + * helpers for construction, lookup, updates, mapping, filtering, folding, + * set-like combination, and typed conversions between records and iterable + * entries. Helpers that change values return new records instead of mutating the + * input. + * + * @since 2.0.0 + */ + + + + + + +/** + * Creates a new, empty record. + * + * **Example** (Creating an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * // Create an empty record + * const emptyRecord = Record.empty() + * emptyRecord // => {} + * + * // The type ensures type safety for future operations + * Record.set(emptyRecord, "count", 42) // => { count: 42 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => ({}); +/** + * Determines if a mutable record is empty. + * + * **Example** (Checking for an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyRecord({}) // => true + * Record.isEmptyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyRecord = self => Object.keys(self).length === 0; +/** + * Determines if a readonly record is empty. + * + * **Example** (Checking for an empty readonly record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyReadonlyRecord({}) // => true + * Record.isEmptyReadonlyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyReadonlyRecord = (/* unused pure expression or super */ null && (isEmptyRecord)); +/** + * Takes an iterable and a projection function and returns a record. + * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. + * + * **Example** (Building a record from mapped iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromIterableWith([1, 2, 3, 4], (a) => [String(a), a * 2]) // => { "1": 2, "2": 4, "3": 6, "4": 8 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const a of self) { + const [k, b] = f(a); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Creates a new record from an iterable, utilizing the provided function to determine the key for each element. + * + * **Example** (Building a record keyed by iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const users = [ + * { id: "2", name: "name2" }, + * { id: "1", name: "name1" } + * ] + * + * Record.fromIterableBy( + * users, + * (user) => user.id + * ) // => { "1": { id: "1", name: "name1" }, "2": { id: "2", name: "name2" } } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (items, f) => fromIterableWith(items, a => [f(a), a])))); +/** + * Builds a record from an iterable of key-value pairs. + * + * **Details** + * + * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the + * previous ones. So the resulting record will only have the value of the last occurrence of each key. + * + * **Example** (Building a record from entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromEntries([["a", 1], ["b", 2]]) // => { a: 1, b: 2 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEntries = Object.fromEntries; +/** + * Transforms the values of a record into an `Array` with a custom mapping function. + * + * **Example** (Collecting mapped record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.collect(x, (key, n) => [key, n]) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const collect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + const out = []; + for (const key of keys(self)) { + out.push(f(key, self[key])); + } + return out; +}); +/** + * Takes a record and returns an array of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.toEntries(x) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const toEntries = /*#__PURE__*/collect((key, value) => [key, value]); +/** + * Returns the number of key/value pairs in a record. + * + * **Example** (Getting the record size) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.size({ a: "a", b: 1, c: true }) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => keys(self).length; +/** + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.has({ a: 1, b: 2 }, "a") // => true + * Record.has(Record.empty(), "c") // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const has = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key)))); +/** + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) + * + * ```ts import.meta.vitest + * import { Option, Record as R } from "effect" + * + * const person: Record = { name: "John Doe", age: 35 } + * + * R.get(person, "name") // => Option.some("John Doe") + * R.get(person, "email") // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key) ? Option.some(self[key]) : Option.none()))); +/** + * Applies a function to the element at the specified key safely, creating a new record, + * or return `Option.none()` if the key doesn't exist. + * + * **Example** (Modifying a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const f = (x: number) => x * 2 + * + * const input: Record = { a: 3 } + * + * Record.modify(input, "a", f) // => Option.some({ a: 6 }) + * Record.modify(input, "b", f) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, f) => { + if (!has(self, key)) return Option.none(); + return Option.some({ + ...self, + [key]: f(self[key]) + }); +}))); +/** + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.replace({ a: 1, b: 2, c: 3 }, "a", 10) // => Option.some({ a: 10, b: 2, c: 3 }) + * Record.replace(Record.empty(), "a", 10) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, b) => modify(self, key, () => b)))); +/** + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.remove({ a: 1, b: 2 }, "a") // => { b: 2 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => { + if (!has(self, key)) { + return { + ...self + }; + } + const out = { + ...self + }; + delete out[key]; + return out; +}))); +/** + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` + * of a tuple with the value and the record with the removed property. + * If the key is not present, returns `Option.none()`. + * + * **Example** (Popping a value and removing its key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const input: Record = { a: 1, b: 2 } + * + * Record.pop(input, "a") // => Option.some([1, { b: 2 }]) + * Record.pop(input, "c") // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const pop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => has(self, key) ? Option.some([self[key], remove(self, key)]) : Option.none()))); +/** + * Maps a record into another record by applying a transformation function to each of its values. + * + * **Example** (Mapping record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const f = (n: number) => `-${n}` + * + * Record.map({ a: 3, b: 5 }, f) // => { a: "-3", b: "-5" } + * + * const g = (n: number, key: string) => `${key.toUpperCase()}-${n}` + * + * Record.map({ a: 3, b: 5 }, g) // => { a: "A-3", b: "B-5" } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = { + ...self + }; + for (const key of keys(self)) { + InternalRecord.assignProperty(out, key, f(self[key], key)); + } + return out; +}))); +/** + * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. + * + * **Example** (Mapping record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()) // => { A: 3, B: 5 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapKeys = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const a = self[key]; + InternalRecord.assignProperty(out, f(key, a), a); + } + return out; +}))); +/** + * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. + * + * **Example** (Mapping record entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]) // => { A: 4, B: 6 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapEntries = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const [k, b] = f(self[key], key); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Transforms a record by applying the function `f` to each key and value in the original record. + * If the function succeeds, the key-value pair is included in the output record. + * + * **Example** (Filtering and mapping with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (a: number, key: string) => a > 2 ? Result.succeed(a * 2) : Result.failVoid + * Record.filterMap(x, f) // => { c: 6 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const key of keys(self)) { + const result = f(self[key], key); + if (R.isSuccess(result)) { + InternalRecord.assignProperty(out, key, result.success); + } + } + return out; +}))); +/** + * Selects properties from a record whose values match the given predicate. + * + * **Example** (Filtering record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3, d: 4 } + * Record.filter(x, (n) => n > 2) // => { c: 3, d: 4 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const out = empty(); + for (const key of keys(self)) { + if (predicate(self[key], key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + return out; +}))); +/** + * Returns a new record containing only the `Some` values from a record of + * `Option` values, preserving the original keys. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = empty(); + for (const key of keys(self)) { + const option = self[key]; + if (Option.isSome(option)) { + InternalRecord.assignProperty(out, key, option.value); + } + } + return out; +}; +/** + * Returns a new record containing only the `Err` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result failures) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getFailures({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { b: "err" } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isFailure(value)) { + InternalRecord.assignProperty(out, key, value.failure); + } + } + return out; +}; +/** + * Returns a new record containing only the `Ok` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result successes) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getSuccesses({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isSuccess(value)) { + InternalRecord.assignProperty(out, key, value.success); + } + } + return out; +}; +/** + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (n: number) => (n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) + * Record.partition(x, f) // => [{ a: 1, c: 3 }, { b: 2 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const left = empty(); + const right = empty(); + for (const key of keys(self)) { + const e = f(self[key], key); + if (R.isFailure(e)) { + InternalRecord.assignProperty(left, key, e.failure); + } else { + InternalRecord.assignProperty(right, key, e.success); + } + } + return [left, right]; +}))); +/** + * Partitions a record of `Result` values into two separate records, + * one with the `Err` values and one with the `Ok` values. + * + * **Example** (Separating Result values) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.separate({ a: Result.fail("e"), b: Result.succeed(1) }) // => [{ a: "e" }, { b: 1 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Retrieves the keys of a given record as an array. + * + * **Example** (Getting record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.keys({ a: 1, b: 2, c: 3 }) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const keys = self => Object.keys(self); +/** + * Retrieves the values of a given record as an array. + * + * **Example** (Getting record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const values = self => collect(self, (_, a) => a); +/** + * Adds a new key-value pair or update an existing key's value in a record. + * + * **Example** (Setting a record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.set("a", 5)({ a: 1, b: 2 }) // => { a: 5, b: 2 } + * Record.set("c", 5)({ a: 1, b: 2 }) // => { a: 1, b: 2, c: 5 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const set = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, value) => { + return { + ...self, + [key]: value + }; +}))); +/** + * Mutates a record by assigning a value to a property. + * + * **When to use** + * + * Use when incrementally constructing a new record and copying it for every + * property would be unnecessary. + * + * **Gotchas** + * + * This function mutates `self`. When `key` is `"__proto__"`, it creates an + * own data property instead of changing the object's prototype. + * + * **Example** (Assigning an external key safely) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const key: string = "__proto__" // Assume this comes from external input + * const value = { polluted: true } + * + * const unsafe: Record = {} + * unsafe[key] = value + * Object.getPrototypeOf(unsafe) === value // => true + * + * const safe: Record = {} + * Record.assignProperty(safe, key, value) + * Object.getPrototypeOf(safe) === Object.prototype // => true + * safe[key] === value // => true + * ``` + * + * @see {@link set} for an immutable update + * @category mutations + * @since 4.0.0 + */ +const assignProperty = _internal_record_js__rspack_import_1/* .assignProperty */.x; +/** + * Checks whether all the keys and values in one record are also found in another record. + * Uses the provided equivalence function to compare values. + * + * **Example** (Checking subrecords with a custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Record } from "effect" + * + * const isSubrecord = Record.isSubrecordBy( + * Equivalence.make((self, that) => self.toLowerCase() === that.toLowerCase()) + * ) + * + * const required: Record.ReadonlyRecord = { role: "Admin" } + * const available: Record.ReadonlyRecord = { + * role: "admin", + * status: "active" + * } + * + * isSubrecord(required, available) // => true + * isSubrecord({ role: "Admin", status: "inactive" }, available) // => false + * isSubrecord(required, { role: "editor", status: "active" }) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecordBy = equivalence => dual(2, (self, that) => { + for (const key of keys(self)) { + if (!has(that, key) || !equivalence(self[key], that[key])) { + return false; + } + } + return true; +}); +/** + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isSubrecord({ a: 1 } as Record, { a: 1, b: 2 }) // => true + * Record.isSubrecord({ a: 1, b: 2 }, { a: 1 } as Record) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecord = /*#__PURE__*/(/* unused pure expression or super */ null && (isSubrecordBy(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.reduce({ a: 1, b: 2, c: 3 }, 0, (acc, value) => acc + value) // => 6 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, zero, f) => { + let out = zero; + for (const key of keys(self)) { + out = f(out, self[key], key); + } + return out; +}))); +/** + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.every({ a: 1, b: 2 }, (n) => n > 0) // => true + * Record.every({ a: 1, b: -1 }, (n) => n > 0) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => { + for (const key of keys(self)) { + if (!refinement(self[key], key)) { + return false; + } + } + return true; +}))); +/** + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.some({ a: 1, b: 2 }, (n) => n > 1) // => true + * Record.some({ a: 1, b: 2 }, (n) => n > 2) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + for (const key of keys(self)) { + if (predicate(self[key], key)) { + return true; + } + } + return false; +}))); +/** + * Merges two records, preserving entries that exist in either of the records. + * For keys that exist in both records, the provided combine function is used to merge the values. + * + * **Example** (Merging records with union) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.union({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { a: 1, b: 5, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const union = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = empty(); + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } else { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(out, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Merges two records, retaining only the entries that exist in both records. + * For intersecting keys, the provided combine function is used to merge the values. + * + * **Example** (Merging intersecting keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.intersection({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { b: 5 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + const out = empty(); + if (isEmptyRecord(self) || isEmptyRecord(that)) { + return out; + } + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } + } + return out; +}))); +/** + * Merges two records, preserving only the entries that are unique to each record. + * Keys that exist in both records are excluded from the result. + * + * **Example** (Keeping keys unique to each record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.difference({ a: 1, b: 2 }, { b: 3, c: 4 }) // => { a: 1, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = {}; + for (const key of keys(self)) { + if (!has(that, key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(self, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Create an `Equivalence` for records using the provided `Equivalence` for values. + * Two records are considered equivalent if they have the same keys and their corresponding values are equivalent. + * + * **Example** (Comparing records with a value equivalence) + * + * ```ts import.meta.vitest + * import { Equal, Record } from "effect" + * + * const recordEquivalence = Record.makeEquivalence(Equal.asEquivalence()) + * + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 3 }) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = equivalence => { + const is = isSubrecordBy(equivalence); + return (self, that) => is(self, that) && is(that, self); +}; +/** + * Create a non-empty record from a single element. + * + * **Example** (Creating a singleton record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.singleton("a", 1) // => { a: 1 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const singleton = (key, value) => ({ + [key]: value +}); +/** + * Creates a `Reducer` for combining `Record`s using union, with values for keys that exist in both records combined + * using the provided `Combiner`. + * + * **When to use** + * + * Use to build a reusable reducer for accumulating many records into one + * union-shaped record, preserving keys from every input and combining + * overlapping values with the supplied combiner. + * + * **Details** + * + * The returned reducer uses `Record.union` for combine and an empty record as + * `initialValue`, so the default `combineAll` folds from `{}` and accumulates + * keys from each input record. + * + * @see {@link union} for one-off record merging with the same union semantics + * @see {@link makeReducerIntersection} for a reducer that keeps only keys present on both sides + * + * @category combining + * @since 4.0.0 + */ +function makeReducerUnion(combiner) { + return Reducer.make((self, that) => union(self, that, combiner.combine), {}); +} +/** + * Creates a `Reducer` whose `combine` operation intersects two records and + * combines values for keys present in both records. + * + * **When to use** + * + * Use to build a `Reducer` that combines records by retaining only keys shared + * by both inputs and combining matching values with a `Combiner`. + * + * **Gotchas** + * + * The reducer's `initialValue` is an empty record. Because intersection with + * an empty record is empty, the default `combineAll` folds from `{}` and + * therefore produces `{}` for ordinary non-empty inputs. + * + * @see {@link makeReducerUnion} for a reducer that preserves keys from either input record + * @see {@link intersection} for applying the shared-key merge to one pair of records + * + * @category combining + * @since 4.0.0 + */ +function makeReducerIntersection(combiner) { + return Reducer.make((self, that) => intersection(self, that, combiner.combine), {}); +} +/** + * Returns the first entry that satisfies the specified + * predicate, or `None` if no such entry exists. + * + * **Example** (Finding the first matching entry) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const record = { a: 1, b: 2, c: 3 } + * Record.findFirst( + * record, + * (value, key) => value > 1 && key !== "b" + * ) // => Option.some(["c", 3]) + * ``` + * + * @category searching + * @since 3.14.0 + */ +const findFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const k = keys(self); + for (let i = 0; i < k.length; i++) { + const key = k[i]; + if (f(self[key], key)) { + return Option.some([key, self[key]]); + } + } + return Option.none(); +}))); +//# sourceMappingURL=Record.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Wo: toEntries +}); + + +}, +"./node_modules/effect/dist/Redactable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @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 + * @category guards + * @since 3.10.0 + */ +const isRedactable = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(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 + * @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 + * @category destructors + * @since 4.0.0 + */ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context ?? emptyContext); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/new Map(); +const emptyContext = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +//# sourceMappingURL=Redactable.js.map +__webpack_require__.d(__webpack_exports__, { + E$: () => (redact), + f6: () => (getRedacted) +}, { + fL: currentFiberTypeId, + uC: symbolRedactable +}); + + +}, +"./node_modules/effect/dist/Reducer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Reusable strategies for reducing many values into one value. A `Reducer` + * extends `Combiner.Combiner` with an `initialValue` for empty collections and + * a `combineAll` method for folding an entire iterable. This module provides a + * constructor for reducers and a helper for reversing the order in which values + * are combined. + * + * @since 4.0.0 + */ +/** + * Creates a `Reducer` from a `combine` function and an `initialValue`. + * + * **When to use** + * + * Use when you have a custom reducing operation not covered by a pre-built reducer. + * - You want to provide an optimized `combineAll` (e.g. short-circuiting on + * a known absorbing element like `0` for multiplication). + * + * **Details** + * + * - If `combineAll` is omitted, a default left-to-right fold starting from + * `initialValue` is used. + * - If `combineAll` is provided, it completely replaces the default fold. + * + * **Example** (Multiplying with short-circuit) + * + * ```ts import.meta.vitest + * import { Reducer } from "effect" + * + * const Product = Reducer.make( + * (a, b) => a * b, + * 1, + * (collection) => { + * let acc = 1 + * for (const n of collection) { + * if (n === 0) return 0 + * acc *= n + * } + * return acc + * } + * ) + * + * Product.combineAll([2, 3, 4]) // => 24 + * Product.combineAll([2, 0, 4]) // => 0 + * ``` + * + * @see {@link Reducer} – the interface this creates + * @see {@link flip} – reverse the argument order + * + * @category constructors + * @since 4.0.0 + */ +function make(combine, initialValue, combineAll) { + return { + combine, + initialValue, + combineAll: combineAll ?? (collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + } + return out; + }) + }; +} +/** + * Reverses the argument order of a reducer's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative reducer such as string concatenation. + * + * **Details** + * + * - Returns a new `Reducer` where `combine(self, that)` calls the original + * reducer as `combine(that, self)`. + * - The `initialValue` is preserved from the original reducer. + * - The `combineAll` is re-derived from the flipped `combine` (using the + * default left-to-right fold), not carried over from the original. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Reducer, String } from "effect" + * + * const Prepend = Reducer.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * Prepend.combineAll(["a", "b", "c"]) // => "cba" + * ``` + * + * @see {@link make} + * @see {@link Combiner.flip} – the same operation on a plain `Combiner` + * + * @category combinators + * @since 4.0.0 + */ +function flip(reducer) { + return make((self, that) => reducer.combine(that, self), reducer.initialValue); +} +//# sourceMappingURL=Reducer.js.map +__webpack_require__.d(__webpack_exports__, { + L: () => (make) +}); + + +}, +"./node_modules/effect/dist/Request.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); + + + + + + +const TypeId = "~effect/Request"; +const requestVariance = /*#__PURE__*/_Equal_js__rspack_import_0/* .byReferenceUnsafe */.Xq({ + /* c8 ignore next */ + _E: _ => _, + /* c8 ignore next */ + _A: _ => _, + /* c8 ignore next */ + _R: _ => _ +}); +/** + * Prototype used by Effect's request constructors. + * + * **Details** + * + * This low-level value provides the structural request marker for values + * created by `Request.of`, `Request.tagged`, `Request.Class`, and + * `Request.TaggedClass`. Most users should use those constructors instead of + * interacting with the prototype directly. + * + * @category prototypes + * @since 4.0.0 + */ +const RequestPrototype = { + ..._internal_core_js__rspack_import_1/* .StructuralProto */.In, + [TypeId]: requestVariance +}; +/** + * Checks whether a value is a `Request`. + * + * **Example** (Checking request values) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * const GetUser = Request.tagged("GetUser") + * + * const request = GetUser({ id: "123" }) + * Request.isRequest(request) // => true + * Request.isRequest("not a request") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isRequest = u => hasProperty(u, TypeId); +/** + * Creates a constructor function for a specific Request type. + * + * **Example** (Creating untagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const UserProfile: unique symbol + * declare const ProfileError: unique symbol + * type UserProfile = typeof UserProfile + * type ProfileError = typeof ProfileError + * + * interface GetUserProfile extends Request.Request { + * readonly id: string + * readonly includeSettings: boolean + * } + * + * const GetUserProfile = Request.of() + * + * const request = GetUserProfile({ + * id: "user-123", + * includeSettings: true + * }) + * + * request.id // => "user-123" + * request.includeSettings // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = () => args => Object.setPrototypeOf({ + ...args +}, RequestPrototype); +/** + * Creates a constructor function for a tagged Request type. The tag is automatically + * added to the request, making it useful for discriminated unions. + * + * **Example** (Creating tagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * declare const Post: unique symbol + * declare const PostNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * type Post = typeof Post + * type PostNotFound = typeof PostNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * + * interface GetPost extends Request.Request { + * readonly _tag: "GetPost" + * readonly id: string + * } + * + * const GetUser = Request.tagged("GetUser") + * const GetPost = Request.tagged("GetPost") + * + * const userRequest = GetUser({ id: "user-123" }) + * const postRequest = GetPost({ id: "post-456" }) + * + * // _tag is automatically set + * Array.of(userRequest._tag, postRequest._tag) // => ["GetUser", "GetPost"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const tagged = tag => args => { + return Object.setPrototypeOf({ + ...args, + _tag: tag + }, RequestPrototype); +}; +/** + * Defines request types with TypeScript classes. + * + * **Details** + * + * Subclasses pass their data fields to `super`, and instances are marked as + * `Request` values while retaining the provided readonly fields. + * + * **Example** (Defining request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUser extends Request.Class<{ id: number }, string, Error> { + * constructor(readonly id: number) { + * super({ id }) + * } + * } + * + * const getUserRequest = new GetUser(123) + * getUserRequest.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function Class(args) { + if (args) { + InternalRecord.assignProperties(this, args); + } + } + Class.prototype = RequestPrototype; + return Class; +}())); +/** + * Creates a class constructor for requests with a fixed `_tag` field. + * + * **Details** + * + * Use this when defining class-based request types that should participate in + * tagged unions or tag-based request resolvers. + * + * **Example** (Defining tagged request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUserById + * extends Request.TaggedClass("GetUserById")<{ id: number }, string, Error> + * {} + * + * const request = new GetUserById({ id: 123 }) + * + * request._tag // => "GetUserById" + * request.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const TaggedClass = tag => { + return class TaggedClass extends Class { + _tag = tag; + }; +}; +/** + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, result) => internalEffect.sync(() => self.completeUnsafe(result))))); +/** + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const completeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.matchEffect(effect, { + onFailure: error => complete(self, core.exitFail(error)), + onSuccess: value => complete(self, core.exitSucceed(value)) +})))); +/** + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, error) => complete(self, core.exitFail(error))))); +/** + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => complete(self, core.exitFailCause(cause))))); +/** + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, value) => complete(self, core.exitSucceed(value))))); +/** + * Creates a `Request.Entry` from its component fields. + * + * **Details** + * + * This is a low-level helper for request runtime and resolver infrastructure; + * most application code receives entries from a `RequestResolver` instead of + * constructing them directly. + * + * @category constructors + * @since 2.0.0 + */ +const makeEntry = options => options; +//# sourceMappingURL=Request.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + lq: makeEntry +}); + + +}, +"./node_modules/effect/dist/Result.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/** + * Models a value that has already succeeded or failed. + * + * A `Result` is `Success` when a value is available and + * `Failure` when an error is available. It is plain data, so inspecting + * or transforming it does not run side effects. This module includes helpers + * for creating, checking, mapping, combining, and extracting results, plus + * conversions to and from `Option` and nullable values. + * + * @since 4.0.0 + */ + + + + + + + +const TypeId = "~effect/data/Result"; +/** + * 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` + * + * @category constructors + * @since 4.0.0 + */ +const succeed = _internal_result_js__rspack_import_0/* .succeed */.Py; +/** + * 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 + * + * @category constructors + * @since 4.0.0 + */ +const fail = _internal_result_js__rspack_import_0/* .fail */.fJ; +const void_ = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed(void 0))); + +/** + * Provides a pre-built failed `Result` whose failure value is `undefined`. + * + * **When to use** + * + * Use when you need a failed `Result` value that acts only as a control signal + * without failure data. + * + * **Details** + * + * This is equivalent to `Result.fail(undefined)` with type + * `Result`, but reuses a shared `Failure` wrapper instead of + * allocating one each time. + * + * **Example** (Failing without a payload) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.failVoid // => Result.fail(undefined) + * ``` + * + * @see {@link fail} to create a Failure with a specific value + * + * @category constructors + * @since 4.0.0 + */ +const failVoid = /*#__PURE__*/(/* unused pure expression or super */ null && (fail(void 0))); +/** + * Converts a possibly `null` or `undefined` value into a `Result`. + * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * + * - Non-nullish values become `Success>` + * - `null` or `undefined` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * - The `onNullish` callback receives the original value + * + * **Example** (Handling nullable values) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.fromNullishOr(1, () => "fallback") // => Result.succeed(1) + * + * Result.fromNullishOr(null, () => "fallback") // => Result.fail("fallback") + * ``` + * + * @see {@link fromOption} to convert from an Option + * @see {@link succeed} / {@link fail} for direct construction + * + * @category constructors + * @since 4.0.0 + */ +const fromNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onNullish) => self == null ? fail(onNullish(self)) : succeed(self)))); +/** + * Converts an `Option` into a `Result`. + * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * + * - `Some` becomes `Success` + * - `None` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Converting an Option to a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.fromOption(Option.some(1), () => "missing") // => Result.succeed(1) + * + * Result.fromOption(Option.none(), () => "missing") // => Result.fail("missing") + * ``` + * + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values + * + * @category constructors + * @since 2.0.0 + */ +const fromOption = _internal_result_js__rspack_import_0/* .fromOption */.sV; +const try_ = evaluate => { + if (isFunction(evaluate)) { + try { + return succeed(evaluate()); + } catch (e) { + return fail(e); + } + } else { + try { + return succeed(evaluate.try()); + } catch (e) { + return fail(evaluate.catch(e)); + } + } +}; + +/** + * Checks whether a value is a `Result` (either `Success` or `Failure`). + * + * **When to use** + * + * Use to validate unknown input before operating on it as a `Result`. + * + * **Details** + * + * - Returns `true` for both `Success` and `Failure` variants + * - Acts as a TypeScript type guard, narrowing to `Result` + * + * **Example** (Checking if a value is a Result) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.isResult(Result.succeed(1)) // => true + * + * Result.isResult({ value: 1 }) // => false + * ``` + * + * @see {@link isSuccess} / {@link isFailure} to narrow to a specific variant + * + * @category guards + * @since 4.0.0 + */ +const isResult = _internal_result_js__rspack_import_0/* .isResult */.aI; +/** + * 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 + * + * @category guards + * @since 4.0.0 + */ +const isFailure = _internal_result_js__rspack_import_0/* .isFailure */.N6; +/** + * Checks whether a `Result` is a `Success`. + * + * **When to use** + * + * Use to narrow a known `Result` to the `Success` variant. + * + * **Details** + * + * - Acts as a TypeScript type guard, narrowing to `Success` + * - After narrowing, you can access `.success` to read the value + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * const result = Result.succeed(42) + * + * if (Result.isSuccess(result)) { + * result.success // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link isResult} to check if a value is any Result + * + * @category guards + * @since 4.0.0 + */ +const isSuccess = _internal_result_js__rspack_import_0/* .isSuccess */.oJ; +/** + * Extracts the success value as an `Option`, discarding the failure. + * + * **When to use** + * + * Use when you need to extract the success value from a `Result` as an + * `Option` and discard failure information. + * + * **Details** + * + * - `Success` becomes `Some` + * - `Failure` becomes `None` + * + * **Example** (Extracting the success as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * + * Result.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} to extract the error instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_0/* .getSuccess */.Oz; +/** + * Extracts the failure value as an `Option`, discarding the success. + * + * **When to use** + * + * Use when you need to extract the failure value from a `Result` as an + * `Option` and discard successful values. + * + * **Details** + * + * - `Failure` becomes `Some` + * - `Success` becomes `None` + * + * **Example** (Extracting the failure as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getFailure(Result.succeed("ok")) // => Option.none() + * + * Result.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} to extract the success instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_0/* .getFailure */.L8; +/** + * Creates an `Equivalence` for comparing two `Result` values. + * + * **Details** + * + * - Two `Success` values are equal when the `success` equivalence says so + * - Two `Failure` values are equal when the `failure` equivalence says so + * - A `Success` and a `Failure` are never equal + * + * **Example** (Comparing Results for equality) + * + * ```ts import.meta.vitest + * import { Equivalence, Result } from "effect" + * + * const eq = Result.makeEquivalence( + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ) + * + * eq(Result.succeed(1), Result.succeed(1)) // => true + * + * eq(Result.succeed(1), Result.fail("x")) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = (success, failure) => Equivalence.make((x, y) => isFailure(x) ? isFailure(y) && failure(x.failure, y.failure) : isSuccess(y) && success(x.success, y.success)); +/** + * Transforms both the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(1), + * Result.mapBoth({ + * onSuccess: (n) => n + 1, + * onFailure: (e) => `Error: ${e}` + * }) + * ) // => Result.succeed(2) + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error value + * @see {@link match} to fold into a single value + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? fail(onFailure(self.failure)) : succeed(onSuccess(self.success))))); +/** + * Transforms the failure channel of a `Result`, leaving the success channel unchanged. + * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * + * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` + * - If the result is a `Success`, returns it as-is + * + * **Example** (Adding context to an error) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("not found"), + * Result.mapError((e) => `Error: ${e}`) + * ) // => Result.fail("Error: not found") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapBoth} to transform both channels + * + * @category mapping + * @since 4.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(f(self.failure)) : self))); +/** + * Transforms the success channel of a `Result`, leaving the failure channel unchanged. + * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * + * - If the result is a `Success`, applies `f` to the value and returns a new `Success` + * - If the result is a `Failure`, returns it as-is + * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) + * + * **Example** (Doubling the success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(3), + * Result.map((n) => n * 2) + * ) // => Result.succeed(6) + * ``` + * + * @see {@link mapError} to transform only the error value + * @see {@link mapBoth} to transform both channels + * @see {@link flatMap} when `f` returns a `Result` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isSuccess(self) ? succeed(f(self.success)) : self))); +/** + * Folds a `Result` into a single value by applying one of two functions. + * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * - Both branches must return the same type (or a common supertype) + * + * **Example** (Folding to a string) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const format = Result.match({ + * onSuccess: (n: number) => `Got ${n}`, + * onFailure: (e: string) => `Err: ${e}` + * }) + * + * format(Result.succeed(42)) // => "Got 42" + * + * format(Result.fail("timeout")) // => "Err: timeout" + * ``` + * + * @see {@link merge} to extract `A | E` without mapping + * @see {@link getOrElse} to unwrap only the success with a fallback + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? onFailure(self.failure) : onSuccess(self.success)); +/** + * Lifts a value into a `Result` based on a predicate or refinement. + * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * + * - If the predicate returns `true`, the value becomes `Success` + * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Validating a number) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * 5, + * Result.liftPredicate( + * (n: number) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.succeed(5) + * ``` + * + * @see {@link filterOrFail} to validate a value that is already in a `Result` + * @see {@link fromNullishOr} for nullable-based construction + * + * @category constructors + * @since 3.4.0 + */ +const liftPredicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (a, predicate, orFailWith) => predicate(a) ? succeed(a) : fail(orFailWith(a))))); +/** + * Validates the success value of a `Result` using a predicate, failing with a + * custom error if the predicate returns `false`. + * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * + * - If the result is already a `Failure`, it is returned as-is + * - If the predicate passes, the `Success` is returned unchanged + * - If the predicate fails, `orFailWith` produces the error for a new `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - The error type of the output is the union of both error types + * + * **Example** (Filtering a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(0), + * Result.filterOrFail( + * (n) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.fail("0 is not positive") + * ``` + * + * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate + * @see {@link flatMap} for general conditional chaining + * + * @category filtering + * @since 4.0.0 + */ +const filterOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, orFailWith) => flatMap(self, a => predicate(a) ? succeed(a) : fail(orFailWith(a)))))); +/** + * Unwraps a `Result` into `A | E` by returning the inner value regardless + * of whether it is a success or failure. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `E` + * - Useful when both channels share a compatible type + * + * **Example** (Extracting the inner value) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.merge(Result.succeed(42)) // => 42 + * + * Result.merge(Result.fail("error")) // => "error" + * ``` + * + * @see {@link match} to map each branch to a common type + * @see {@link getOrElse} to provide a fallback for failures + * + * @category getters + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (match({ + onFailure: identity, + onSuccess: identity +}))); +/** + * Extracts the success value, or computes a fallback from the error. + * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * + * - `Success` returns the inner value + * - `Failure` applies `onFailure` to the error and returns the result + * - The return type is `A | A2` (union of both branches) + * + * **Example** (Providing a fallback) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrElse(Result.succeed(1), () => 0) // => 1 + * + * Result.getOrElse(Result.fail("err"), () => 0) // => 0 + * ``` + * + * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks + * @see {@link getOrThrow} to throw on failure + * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => isFailure(self) ? onFailure(self.failure) : self.success))); +/** + * Extracts the success value, or returns `null` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `null`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `null` + * + * **Example** (Unwrapping to nullable) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrNull(Result.succeed(1)) // => 1 + * + * Result.getOrNull(Result.fail("err")) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constNull))); +/** + * Extracts the success value, or returns `undefined` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `undefined`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `undefined` + * + * **Example** (Unwrapping to optional) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrUndefined(Result.succeed(1)) // => 1 + * + * Result.getOrUndefined(Result.fail("err")) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constUndefined))); +/** + * Extracts the success value or throws a custom error derived from the failure. + * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws the value returned by `onFailure(e)` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrowWith(Result.succeed(1), () => new Error("fail")) // => 1 + * + * const failure = Result.try({ + * try: () => Result.getOrThrowWith( + * Result.fail("oops"), + * (error) => new Error(`Unexpected: ${error}`) + * ), + * catch: (error) => (error as Error).message + * }) + * Result.merge(failure) // => "Unexpected: oops" + * ``` + * + * @see {@link getOrThrow} to throw the raw failure value + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => { + if (isSuccess(self)) { + return self.success; + } + throw onFailure(self.failure); +}))); +/** + * Extracts the success value or throws the raw failure value `E`. + * + * **When to use** + * + * Use when unchecked boundaries should turn failures into thrown exceptions. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws `E` directly + * - Use {@link getOrThrowWith} for a custom error object + * + * **Example** (Unwrapping or throwing) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrow(Result.succeed(1)) // => 1 + * + * const failure = Result.try(() => Result.getOrThrow(Result.fail("error"))) + * Result.merge(failure) // => "error" + * ``` + * + * @see {@link getOrThrowWith} for custom error mapping + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrThrowWith(identity))); +/** + * Returns the original `Result` if it is a `Success`, otherwise applies + * `that` to the error and returns the resulting `Result`. + * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * + * - `Success` is returned unchanged + * - `Failure` calls `that(e)` to produce a new `Result` + * + * **Example** (Recovering from a failure) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("primary failed"), + * Result.orElse(() => Result.succeed(99)) + * ) // => Result.succeed(99) + * ``` + * + * @see {@link getOrElse} to unwrap with a fallback value (not a Result) + * @see {@link mapError} to transform the error without recovering + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => isFailure(self) ? that(self.failure) : succeed(self.success)))); +/** + * Chains a function that returns a `Result` onto a successful value. + * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * + * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` + * - If `self` is a `Failure`, short-circuits and returns it unchanged + * - The error types are merged into a union (`E | E2`) + * - This is the monadic `bind` / `>>=` for `Result` + * + * **Example** (Validating sequentially) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(5), + * Result.flatMap((n) => + * n > 0 ? Result.succeed(n * 2) : Result.fail("not positive") + * ) + * ) // => Result.succeed(10) + * ``` + * + * @see {@link andThen} for a more flexible variant that also accepts plain values + * @see {@link map} when `f` does not return a `Result` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(self.failure) : f(self.success)))); +/** + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** + * + * The second argument can be: + * - A function `(a: A) => Result` (same as `flatMap`) + * - A function `(a: A) => A2` (auto-wrapped in `succeed`) + * - A `Result` value (ignores the success of `self`) + * - A plain value `A2` (auto-wrapped in `succeed`, ignores `self`) + * + * If `self` is a `Failure`, the second argument is never evaluated. + * + * **Example** (Chaining Result values with different argument types) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * // With a function returning a Result + * const a = pipe( + * Result.succeed(1), + * Result.andThen((n) => Result.succeed(n + 1)) + * ) // => Result.succeed(2) + * + * // With a plain mapping function + * const b = pipe( + * Result.succeed(1), + * Result.andThen((n) => n + 1) + * ) // => Result.succeed(2) + * + * // With a constant value + * const c = pipe(Result.succeed(1), Result.andThen("done")) // => Result.succeed("done") + * ``` + * + * @see {@link flatMap} for the stricter variant (function returning Result only) + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => { + const out = isFunction(f) ? f(a) : f; + return isResult(out) ? out : succeed(out); +})))); +/** + * Collects a structure of `Result`s into a single `Result` of collected values. + * + * **When to use** + * + * Use to collect independent `Result` values into one `Result` while preserving + * the original structure. + * + * **Details** + * + * Accepts: + * - A tuple/array: returns `Result` with a tuple/array of success values + * - A struct (record): returns `Result` with a struct of success values + * - An iterable: returns `Result` with an array of success values + * + * Short-circuits on the first `Failure` encountered; later elements are not inspected. + * + * **Example** (Collecting a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * // Tuple + * Result.all([Result.succeed(1), Result.succeed("two")]) // => Result.succeed([1, "two"]) + * + * // Struct + * Result.all({ x: Result.succeed(1), y: Result.fail("err") }) // => Result.fail("err") + * ``` + * + * @see {@link flatMap} for chaining two Results sequentially + * @see {@link gen} for generator-based composition of multiple Results + * + * @category sequencing + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const e of input) { + if (isFailure(e)) { + return e; + } + out.push(e.success); + } + return succeed(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const e = input[key]; + if (isFailure(e)) { + return e; + } + InternalRecord.assignProperty(out, key, e.success); + } + return succeed(out); +}; +/** + * Swaps the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to swap channels when failure-focused operations are easier through + * success-oriented combinators. + * + * **Details** + * + * - `Success` becomes `Failure` (i.e., `Result`) + * - `Failure` becomes `Success` (i.e., `Result`) + * - Useful when you want to apply success-oriented operations (like `map`) + * to the error channel, then flip back + * + * **Example** (Swapping channels) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.flip(Result.succeed(42)) // => Result.fail(42) + * + * Result.flip(Result.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link mapError} to transform the error without swapping + * + * @category transforming + * @since 2.0.0 + */ +const flip = self => isFailure(self) ? succeed(self.failure) : fail(self.success); +/** + * Provides generator-based syntax for composing `Result` values sequentially. + * + * **When to use** + * + * Use when you need generator syntax to compose sequential `Result` + * computations instead of nested `flatMap` calls. + * + * **Details** + * + * - Use `yield*` to unwrap a `Result` inside the generator; if any yielded + * `Result` is a `Failure`, the generator short-circuits and returns that failure + * - The return value of the generator is wrapped in `Success` + * - Evaluated eagerly and synchronously (unlike `Effect.gen`) + * + * **Example** (Composing multiple Results) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.gen(function*() { + * const a = yield* Result.succeed(1) + * const b = yield* Result.succeed(2) + * return a + b + * }) // => Result.succeed(3) + * ``` + * + * @see {@link flatMap} for point-free sequential composition + * @see {@link all} to collect multiple independent Results + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isFailure(current)) { + return current; + } + state = iterator.next(current.success); + } + return succeed(state.value); +}; +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do notation" simulation with `Result`. + * + * **When to use** + * + * Use to start a `Result` do-notation pipeline from an empty successful record + * before adding named fields from `Result`-producing computations and pure + * computed values. + * + * **Details** + * + * Creates a `Result<{}>` (success with an empty object). Use with + * {@link bind} to add `Result`-producing fields and {@link let_ let} + * to add pure computed fields. + * + * **Example** (Building an object step by step) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", () => Result.succeed(3)), + * Result.let("sum", ({ x, y }) => x + y) + * ) // => Result.succeed({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add Result-producing fields + * @see {@link let_ let} to add pure computed fields + * @see {@link gen} for an alternative generator-based syntax + * @see {@link bindTo} for starting a do-notation chain from an existing Result + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +/** + * Adds a named field to the do-notation accumulator by running a `Result`-producing + * function that receives the current accumulated object. + * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * + * - Short-circuits on the first `Failure` + * - The field name must not collide with existing keys + * - Use {@link let_ let} for pure (non-Result) computed fields + * + * **Example** (Binding Result values) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", ({ x }) => Result.succeed(x + 3)) + * ) // => Result.succeed({ x: 2, y: 5 }) + * ``` + * + * @see {@link Do} to start the do-notation chain + * @see {@link let_ let} for pure computed fields + * @see {@link bindTo} to wrap an initial Result into a named field + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bind(map, flatMap))); +/** + * Wraps the success value of a `Result` into a named field, producing a + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. + * + * **Example** (Wrapping a value into a named field) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(42), + * Result.bindTo("answer") + * ) // => Result.succeed({ answer: 42 }) + * ``` + * + * @see {@link Do} to start from an empty object + * @see {@link bind} to add more fields + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.let_(map))); + +/** + * Transforms `Option>` into `Result, E>`. + * + * **When to use** + * + * Use when optional absence should be treated as a successful `None`, while an + * inner `Result` failure should still fail the whole result. + * + * **Details** + * + * - `None` becomes `Success(None)` + * - `Some(Success(a))` becomes `Success(Some(a))` + * - `Some(Failure(e))` becomes `Failure(e)` + * + * **Example** (Transposing an Option of a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.transposeOption(Option.some(Result.succeed(42))) // => Result.succeed(Option.some(42)) + * + * Result.transposeOption(Option.none>()) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeMapOption} to map and transpose in one step + * + * @category transposing + * @since 3.14.0 + */ +const transposeOption = self => { + return option_.isNone(self) ? succeedNone : map(self.value, option_.some); +}; +/** + * Maps an `Option` value with a `Result`-producing function, then transposes + * the structure from `Option>` to `Result, E>`. + * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * + * - `None` becomes `Success(None)` (the function is never called) + * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` + * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` + * + * **Example** (Mapping and transposing in one step) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parse = (s: string) => + * isNaN(Number(s)) + * ? Result.fail("not a number" as const) + * : Result.succeed(Number(s)) + * + * Result.transposeMapOption(Option.some("42"), parse) // => Result.succeed(Option.some(42)) + * + * Result.transposeMapOption(Option.none(), parse) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeOption} when the Option already contains a Result + * + * @category transposing + * @since 3.15.0 + */ +const transposeMapOption = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some)))); +/** + * Provides a pre-built `Result>` that succeeds with `None`. + * + * **When to use** + * + * Use when an optional success should be absent, such as the `None` branch of + * `transposeOption` or `transposeMapOption`. + * + * **Details** + * + * This is equivalent to `Result.succeed(Option.none())`, but reuses a shared + * `Success` wrapper instead of allocating one each time. + * + * **Example** (Succeeding with None) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedNone // => Result.succeed(Option.none()) + * ``` + * + * @see {@link succeedSome} for the `Some` counterpart + * @see {@link transposeOption} to transpose an Option that already contains a Result + * @see {@link transposeMapOption} to map and transpose an Option in one step + * + * @category constructors + * @since 4.0.0 + */ +const succeedNone = /*#__PURE__*/succeed(_internal_option_js__rspack_import_2/* .none */.dv); +/** + * Creates a `Result>` that succeeds with `Some(a)`. + * + * **Details** + * + * - Equivalent to `Result.succeed(Option.some(a))` + * - Useful with {@link transposeOption} patterns + * + * **Example** (Wrapping a value in Some inside a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedSome(42) // => Result.succeed(Option.some(42)) + * ``` + * + * @see {@link succeedNone} for the `None` counterpart + * + * @category constructors + * @since 4.0.0 + */ +const succeedSome = a => succeed(option_.some(a)); +/** + * Runs a side-effect on the success value without altering the `Result`. + * + * **Details** + * + * - If the result is a `Success`, calls `f` with the value (return value is ignored) + * - If the result is a `Failure`, `f` is not called + * - Returns the original `Result` unchanged (same reference) + * - Useful for logging, debugging, or performing mutations outside the Result chain + * + * **Example** (Logging a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const values: Array = [] + * const result = pipe( + * Result.succeed(42), + * Result.tap((n) => values.push(n)) + * ) + * + * values // => [42] + * result // => Result.succeed(42) + * ``` + * + * @see {@link map} to transform the success value + * + * @category mapping + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isSuccess(self)) { + f(self.success); + } + return self; +}))); +//# sourceMappingURL=Result.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + N6: isFailure, + Py: succeed, + YW: match, + fJ: fail, + oJ: isSuccess +}); + + +}, +"./node_modules/effect/dist/Schedule.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Pull_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Pull.js"); + + + + + + + + + + + + +const TypeId = "~effect/Schedule"; +const randomNext = /*#__PURE__*/(/* unused pure expression or super */ null && (random.Random.useSync(random => random.nextDoubleUnsafe()))); +/** + * Context reference containing metadata for the currently running schedule step. + * + * **Details** + * + * Repeat, retry, stream, and channel scheduling operations provide this service + * to effects run between schedule steps. The default value contains undefined + * input and output values, zero duration, and zeroed timing fields before any + * schedule step has produced metadata. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Schedule/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + input: undefined, + output: undefined, + duration: _Duration_js__rspack_import_2/* .zero */.v_, + attempt: 0, + start: 0, + now: 0, + elapsed: 0, + elapsedSincePrevious: 0 + }) +}); +const ScheduleProto = { + [TypeId]: { + _Out: _Function_js__rspack_import_1/* .identity */.D_, + _In: _Function_js__rspack_import_1/* .identity */.D_, + _Env: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_3/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * Type guard that checks if a value is a Schedule. + * + * **Example** (Checking for schedules) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.exponential("100 millis") + * const notSchedule = { foo: "bar" } + * + * Schedule.isSchedule(schedule) // => true + * Schedule.isSchedule(notSchedule) // => false + * Schedule.isSchedule(null) // => false + * Schedule.isSchedule(undefined) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isSchedule = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Creates a Schedule from a step function that returns a Pull. + * + * **Example** (Creating a custom schedule from a step function) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.fromStep(Effect.sync(() => { + * let count = 0 + * + * return (_now: number, _input: string) => { + * if (count >= 3) { + * return Cause.done(count) + * } + * return Effect.succeed([count++, Duration.millis(100)] as [number, Duration.Duration]) + * } + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => 0 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStep = step => { + const self = Object.create(ScheduleProto); + self.step = step; + return self; +}; +const metadataFn = () => { + let n = 0; + let previous; + let start; + return (now, input) => { + if (start === undefined) start = now; + const elapsed = now - start; + const elapsedSincePrevious = previous === undefined ? 0 : now - previous; + previous = now; + return { + input, + attempt: ++n, + start, + now, + elapsed, + elapsedSincePrevious + }; + }; +}; +/** + * Creates a Schedule from a step function that receives metadata about the schedule's execution. + * + * **Example** (Creating a metadata-aware schedule) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const firstThreeInputs = Schedule.fromStepWithMetadata(Effect.succeed((metadata: Schedule.InputMetadata) => { + * if (metadata.attempt > 3) { + * return Cause.done("finished") + * } + * + * return Effect.succeed([ + * `attempt ${metadata.attempt}: ${metadata.input}`, + * Duration.millis(250) + * ] as [string, Duration.Duration]) + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(firstThreeInputs) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "attempt 1: input" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStepWithMetadata = step => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(step, f => { + const meta = metadataFn(); + return (now, input) => f(meta(now, input)); +})); +/** + * Extracts the step function from a Schedule. + * + * **Example** (Extracting a schedule step function) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * // Extract step function from an existing schedule + * const schedule = Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * + * const program = Effect.gen(function*() { + * const stepFn = yield* Schedule.toStep(schedule) + * + * // Use the step function directly for custom logic. The timestamp is + * // supplied by the caller, so tests can pass a deterministic value. + * const now = 0 + * return yield* stepFn(now, "input") + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStep = schedule => _internal_effect_js__rspack_import_5/* .catchCause */.Tyx(schedule.step, cause => _internal_effect_js__rspack_import_5/* .succeed */.PyW(() => _internal_effect_js__rspack_import_5/* .failCause */.ATB(cause))); +/** + * Extracts a step function from a `Schedule` that sleeps for each computed + * delay and returns metadata for the completed step. + * + * **When to use** + * + * Use to drive a schedule manually while preserving the computed output, + * delay, input, attempt, and elapsed timing metadata for each step. + * + * **Details** + * + * The returned step reads the current time from `Clock` when invoked, calls the + * schedule step with that timestamp and input, sleeps for the returned + * duration, and then yields `Metadata`. + * + * @see {@link toStep} for manually supplying the timestamp and handling the returned delay yourself + * @see {@link toStepWithSleep} for the same automatic sleeping behavior when only the schedule output is needed + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithMetadata = schedule => _internal_effect_js__rspack_import_5/* .clockWith */.RKA(clock => _internal_effect_js__rspack_import_5/* .map */.TjK(toStep(schedule), step => { + const metaFn = metadataFn(); + return input => _internal_effect_js__rspack_import_5/* .suspend */.DYE(() => { + const now = clock.currentTimeMillisUnsafe(); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), ([output, duration]) => { + const meta = metaFn(now, input); + meta.output = output; + meta.duration = duration; + return _internal_effect_js__rspack_import_5.as(_internal_effect_js__rspack_import_5/* .sleep */.yy4(duration), meta); + }); + }); +})); +/** + * Extracts a step function from a Schedule that automatically handles sleep delays. + * + * **Example** (Extracting a sleeping step function) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const schedule = Schedule.recurs(3) + * + * const program = Effect.gen(function*() { + * const stepWithSleep = yield* Schedule.toStepWithSleep(schedule) + * + * return [yield* stepWithSleep("first"), yield* stepWithSleep("second")] + * }) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [0, 1] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithSleep = schedule => effect.map(toStepWithMetadata(schedule), step => input => effect.map(step(input), meta => meta.output)); +/** + * Returns a new `Schedule` that adds the delay computed by the specified + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.recurs(1).pipe( + * Schedule.addDelay(() => Effect.succeed("25 millis")) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(25) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const addDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => modifyDelay(self, metadata => effect.map(f(metadata), d => Duration.sum(Duration.fromInputUnsafe(d), metadata.duration)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concat(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const concat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => map(concatResult(self, other), ({ + output +}) => effect.succeed(Result.merge(output)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concatResult(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concatResult = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => fromStep(effect.sync(() => { + let currentSide = 0; + let currentStep; + const left = map(self, ({ + output + }) => Result.fail(output)); + const right = map(other, ({ + output + }) => Result.succeed(output)); + return function recur(now, input) { + if (currentStep) return currentStep(now, input); + return toStep(currentSide === 0 ? left : right).pipe(effect.flatMap(step => { + currentSide++; + if (currentSide === 1) { + currentStep = (now, input) => Pull.catchDone(step(now, input), _ => { + currentStep = undefined; + return recur(now, input); + }); + return currentStep(now, input); + } + currentStep = step; + return currentStep(now, input); + })); + }; +}))))); +/** + * Combines schedules by recurring while all schedules want to recur, using the + * maximum delay between recurrences and outputting that maximum delay. + * + * **When to use** + * + * Use when a combined policy should continue only while every schedule still + * recurs, and should wait for the slowest schedule between recurrences. + * + * **Example** (Combining retry schedules by their maximum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.max([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const max = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = maxDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const maxDuration = results => { + let max = results[0]; + for (let i = 1; i < results.length; i++) { + max = results[i] && max && Duration.max(max, results[i]); + if (max === undefined) break; + } + return max; +}; +/** + * Returns a new `Schedule` that recurs on the specified `Cron` schedule and + * outputs the duration between recurrences. + * + * **Example** (Scheduling work with cron expressions) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const everyMinute = Schedule.cron("* * * * *") + * Schedule.isSchedule(everyMinute) // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const cron = (expression, tz) => { + const parsed = Cron.isCron(expression) ? Result.succeed(expression) : Cron.parse(expression, tz); + return fromStep(effect.map(effect.fromResult(parsed), cron => (now, _) => { + if (now === Number.POSITIVE_INFINITY) { + return Cause.done(Duration.zero); + } + return effect.sync(() => { + const next = Cron.next(cron, now).getTime(); + const duration = Duration.millis(next - now); + return [duration, duration]; + }); + })); +}; +/** + * Returns a schedule that recurs once after the specified duration. + * + * **When to use** + * + * Use when you need a schedule that recurs once after a fixed delay. + * + * **Details** + * + * The schedule outputs the configured duration for its first recurrence and + * then completes. + * + * **Example** (Recurring once after a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.duration("1 second")) // => true + * ``` + * + * @see {@link during} for recurring until a duration has elapsed + * + * @category constructors + * @since 2.0.0 + */ +const duration = durationInput => { + const duration = Duration.fromInputUnsafe(durationInput); + return fromStepWithMetadata(effect.succeed(meta => meta.attempt === 1 ? effect.succeed([duration, duration]) : Cause.done(Duration.zero))); +}; +/** + * Returns a new `Schedule` that will always recur, but only during the + * specified `duration` of time. + * + * **When to use** + * + * Use to bound a repeating or retrying schedule by elapsed time. + * + * **Example** (Repeating work during a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.during("5 seconds")) // => true + * ``` + * + * @see {@link duration} for one delayed recurrence + * + * @category constructors + * @since 4.0.0 + */ +const during = duration => { + const durationMillis = Duration.toMillis(duration); + return fromStepWithMetadata(effect.succeed(meta => { + const elapsed = Duration.millis(meta.elapsed); + return meta.elapsed > durationMillis ? Cause.done(elapsed) : effect.succeed([elapsed, Duration.zero]); + })); +}; +/** + * Combines schedules by recurring while at least one schedule wants to recur, + * using the minimum delay between recurrences and outputting that minimum delay. + * + * **When to use** + * + * Use when a combined policy should continue while any schedule still recurs, + * and should wait for the fastest schedule between recurrences. + * + * **Example** (Combining retry schedules by their minimum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.min([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const min = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = minDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const minDuration = results => { + let min = undefined; + for (let i = 0; i < results.length; i++) { + const duration = results[i]; + if (duration !== undefined) { + min = min === undefined ? duration : Duration.min(min, duration); + } + } + return min; +}; +/** + * Schedule that always recurs, but will wait a certain amount between + * repetitions, given by `base * factor.pow(n)`, where `n` is the number of + * repetitions so far. Returns the current duration between recurrences. + * + * **Example** (Retrying with exponential backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.exponential("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const exponential = (base, factor = 2) => { + const baseMillis = Duration.toMillis(Duration.fromInputUnsafe(base)); + return fromStepWithMetadata(effect.succeed(meta => { + const duration = Duration.millis(baseMillis * Math.pow(factor, meta.attempt - 1)); + return effect.succeed([duration, duration]); + })); +}; +/** + * Schedule that always recurs, increasing delays by summing the preceding + * two delays (similar to the Fibonacci sequence). Returns the current + * duration between recurrences. + * + * **Example** (Retrying with Fibonacci backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fibonacci("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fibonacci = one => { + const oneMillis = Duration.toMillis(Duration.fromInputUnsafe(one)); + return fromStep(effect.sync(() => { + let a = 0; + let b = oneMillis; + return constant(effect.sync(() => { + const next = a + b; + a = b; + b = next; + const duration = Duration.millis(next); + return [duration, duration]; + })); + })); +}; +/** + * Returns a `Schedule` that recurs on the specified fixed `interval` and + * outputs the number of repetitions of the schedule so far. + * + * **When to use** + * + * Use when recurrences should stay aligned to a regular cadence. + * + * **Gotchas** + * + * If the action run between recurrences takes longer than the interval, the + * next recurrence happens immediately, but missed intervals are not replayed. + * + * ```text + * |-----interval-----|-----interval-----|-----interval-----| + * |---------action--------||action|-----|action|-----------| + * ``` + * + * **Example** (Repeating on fixed intervals) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fixed("1 second")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(1)] + * ``` + * + * @see {@link spaced} for delaying after each action completes + * + * @category constructors + * @since 2.0.0 + */ +const fixed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.sync(() => { + let start = 0; + let lastRun = 0; + return meta => effect.sync(() => { + if (window === 0) { + return [meta.attempt - 1, Duration.zero]; + } + if (meta.attempt === 1) { + start = meta.now; + lastRun = meta.now + window; + return [0, Duration.millis(window)]; + } + const runningBehind = meta.now > lastRun + window; + const boundary = window - (meta.now - start) % window; + const delay = runningBehind ? 0 : boundary === 0 ? window : boundary; + lastRun = runningBehind ? meta.now : meta.now + delay; + return [meta.attempt - 1, Duration.millis(delay)]; + }); + })); +}; +/** + * Returns a new `Schedule` that maps each schedule decision to a new output + * using the full schedule metadata. + * + * **Details** + * + * The callback receives the schedule input, output, selected delay duration, + * current attempt, and elapsed timing information. Return either a plain value + * or an `Effect` that produces the new output. + * + * **Example** (Mapping schedule outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const countSchedule = Schedule.recurs(5).pipe( + * Schedule.map(({ output: count }) => Effect.succeed(`Execution #${count + 1}`)) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(countSchedule) + * const [output] = yield* step(0, undefined) + * return output + * }) + * + * await Effect.runPromise(program) // => "Execution #1" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => Pull.matchEffect(step(now, input), { + onSuccess: ([output, duration]) => { + const result = f({ + ...meta(now, input), + output, + duration + }); + if (!isEffect(result)) return effect.succeed([result, duration]); + return effect.map(result, output => [output, duration]); + }, + onFailure: effect.failCause, + onDone: output => { + const result = f({ + ...meta(now, input), + output, + duration: Duration.zero + }); + if (!isEffect(result)) return Cause.done(result); + return effect.flatMap(result, Cause.done); + } + }); +}))))); +/** + * Returns a new `Schedule` that modifies the delay of the next recurrence + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule metadata) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.spaced("10 millis").pipe( + * Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.times(duration, 2))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(20) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const modifyDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.flatMap(step(now, input), ([output, duration]) => effect.map(f({ + ...meta(now, input), + output, + duration + }), replacement => [output, Duration.fromInputUnsafe(replacement)])); +}))))); +/** + * Returns a new `Schedule` that randomly adjusts each recurrence delay. + * + * **When to use** + * + * Use to add random variation to an existing schedule's recurrence delays while + * preserving its output and completion behavior. + * + * **Details** + * + * Each recurrence delay is scaled by a random factor between `0.8` and `1.2`. + * + * @see {@link modifyDelay} for replacing recurrence delays with a custom effectful transformation + * + * @category delays & timeouts + * @since 2.0.0 + */ +const jittered = self => modifyDelay(self, ({ + duration +}) => effect.map(randomNext, random => { + const millis = Duration.toMillis(duration); + return Duration.millis(millis * 0.8 * (1 - random) + millis * 1.2 * random); +})); +/** + * Returns a new `Schedule` that outputs the inputs of the specified schedule. + * + * **Example** (Passing inputs through as outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const inputSchedule = Schedule.passthrough( + * Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(inputSchedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "input" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const passthrough = self => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => (now, input) => _Pull_js__rspack_import_6/* .matchEffect */.tv(step(now, input), { + onSuccess: result => _internal_effect_js__rspack_import_5/* .succeed */.PyW([input, result[1]]), + onFailure: _internal_effect_js__rspack_import_5/* .failCause */.ATB, + onDone: () => _Cause_js__rspack_import_7/* .done */.Vw(input) +}))); +/** + * Returns a `Schedule` which can only be stepped the specified number of + * `times` before it terminates. + * + * **When to use** + * + * Use when you need a counter schedule with no additional delay. + * + * **Gotchas** + * + * `recurs(n)` counts schedule recurrences, not the first evaluation of the + * effect being repeated or retried. For retrying, this means one initial + * attempt plus at most `n` retries. + * + * **Example** (Limiting recurrences) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(Schedule.recurs(3)), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3, 4] + * ``` + * + * @see {@link upTo} for limiting an existing schedule + * + * @category constructors + * @since 2.0.0 + */ +const recurs = times => while_(forever, ({ + attempt +}) => _internal_effect_js__rspack_import_5/* .succeed */.PyW(attempt <= times)); +/** + * Returns a schedule that recurs continuously, each repetition spaced the + * specified duration from the last run. + * + * **When to use** + * + * Use when each delay should start after the previous action completes. + * + * **Example** (Repeating with fixed spacing) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.spaced("2 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(2)] + * ``` + * + * @see {@link fixed} for recurrence aligned to a regular cadence + * + * @category constructors + * @since 2.0.0 + */ +const spaced = duration => { + const decoded = _Duration_js__rspack_import_2/* .fromInputUnsafe */.bN(duration); + return fromStepWithMetadata(_internal_effect_js__rspack_import_5/* .succeed */.PyW(meta => _internal_effect_js__rspack_import_5/* .succeed */.PyW([meta.attempt - 1, decoded]))); +}; +/** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const attempts: Array = [] + * const monitoredSchedule = Schedule.recurs(2).pipe( + * Schedule.tap((metadata) => Effect.sync(() => attempts.push(metadata.attempt))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(monitoredSchedule) + * const [output] = yield* step(0, undefined) + * return { attempts, output } + * }) + * + * await Effect.runPromise(program) // => { attempts: [1], output: 0 } + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.tap(step(now, input), ([output, duration]) => f({ + ...meta(now, input), + output, + duration + })); +}))))); +/** + * Returns a new `Schedule` that limits an existing schedule by elapsed + * duration, number of outputs, or both. + * + * **When to use** + * + * Use to bound an existing schedule while preserving its output and delay + * behavior. When both `duration` and `times` are specified, the schedule + * stops as soon as either limit is reached. + * + * **Gotchas** + * + * The `times` option limits schedule outputs. When used with repeat or retry, + * the effect is evaluated once before the schedule is stepped, so the total + * number of evaluations can be one greater than the configured number of + * outputs. + * + * The `duration` option is based on the elapsed time observed by the schedule + * step. Long-running effects can cause the duration limit to be detected on the + * following schedule step. + * + * **Example** (Limiting by duration and recurrence count) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const upTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const duration = options.duration === undefined ? undefined : Duration.fromInputUnsafe(options.duration); + return while_(self, ({ + attempt, + elapsed + }) => effect.succeed((options.times === undefined || attempt <= options.times) && (duration === undefined || Duration.isLessThanOrEqualTo(Duration.millis(elapsed), duration)))); +}))); +const while_ = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), result => { + const [output, duration] = result; + const eff = predicate({ + ...meta(now, input), + output, + duration + }); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB((0,_internal_core_js__rspack_import_8/* .isEffect */.yw)(eff) ? eff : _internal_effect_js__rspack_import_5/* .succeed */.PyW(eff), check => check ? _internal_effect_js__rspack_import_5/* .succeed */.PyW(result) : _Cause_js__rspack_import_7/* .done */.Vw(output)); + }); +}))); + +/** + * Schedule that divides the timeline to `interval`-long windows, and sleeps + * until the nearest window boundary every time it recurs. + * + * **Details** + * + * For example, `Schedule.windowed("10 seconds")` would produce a schedule as + * follows: + * + * ```text + * 10s 10s 10s 10s + * |----------|----------|----------|----------| + * |action------|sleep---|act|-sleep|action----| + * ``` + * + * **Example** (Repeating on aligned windows) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.windowed("5 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(5)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const windowed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.succeed(meta => effect.sync(() => [meta.attempt - 1, window === 0 ? Duration.zero : Duration.millis(window - meta.elapsed % window)]))); +}; +/** + * Returns a new `Schedule` that will recur forever. + * + * **Details** + * + * The output of the schedule is the current count of its repetitions thus far + * (i.e. `0, 1, 2, ...`). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const forever = /*#__PURE__*/spaced(_Duration_js__rspack_import_2/* .zero */.v_); +const constIdentity = /*#__PURE__*/(/* unused pure expression or super */ null && (fromStep(/*#__PURE__*/effect.succeed((_now, input) => effect.succeed([input, Duration.zero]))))); +const identity_ = () => constIdentity; + +/** + * Sets the input type of the provided schedule without altering its behavior. + * + * **When to use** + * + * Use to adapt a schedule that does not depend on its input values. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Setting a schedule input type) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.recurs(3).pipe( + * Schedule.setInputType() + * ) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const setInputType = () => self => self; +//# sourceMappingURL=Schedule.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + E6: while_, + GM: isSchedule, + d3: CurrentMetadata, + i4: forever, + le: passthrough, + t5: recurs, + xn: toStepWithMetadata +}); + + +}, +"./node_modules/effect/dist/Scheduler.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.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. + * + * @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. + * + * @category services + * @since 2.0.0 + */ +const Scheduler = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setImmediate = "setImmediate" in globalThis ? f => { + // @ts-ignore + const timer = globalThis.setImmediate(f); + // @ts-ignore + return () => globalThis.clearImmediate(timer); +} : f => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setMicrotask = f => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +class PriorityBuckets { + 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. + * + * @category models + * @since 2.0.0 + */ +class MixedScheduler { + 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.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); + } +} +class MixedSchedulerDispatcher { + tasks = /*#__PURE__*/new PriorityBuckets(); + running = undefined; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === undefined) { + this.running = this.setImmediate(this.afterScheduled); + } + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = undefined; + 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 !== undefined) { + this.running(); + this.running = undefined; + } + 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 + * + * @category services + * @since 4.0.0 + */ +const MaxOpsBeforeYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("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 + * + * @category services + * @since 4.0.0 + */ +const PreventSchedulerYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +//# sourceMappingURL=Scheduler.js.map +__webpack_require__.d(__webpack_exports__, { + FG: () => (MixedScheduler) +}, { + Zm: MaxOpsBeforeYield, + _F: Scheduler, + hf: PreventSchedulerYield +}); + + +}, +"./node_modules/effect/dist/Scope.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.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. + * + * @since 2.0.0 + */ + +const TypeId = _internal_effect_js__rspack_import_0/* .ScopeTypeId */.kWD; +const CloseableTypeId = _internal_effect_js__rspack_import_0/* .ScopeCloseableTypeId */.obm; +/** + * Service tag for the active resource lifetime. + * + * **When to use** + * + * Use to access the active lifetime when registering finalizers or sharing + * resources with the surrounding scope. + * + * **Example** (Accessing the scope service) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.Scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) + * }) + * + * Effect.runSync(Effect.scoped(program)) + * cleanups // => ["Cleanup"] + * ``` + * + * @category services + * @since 2.0.0 + */ +const Scope = _internal_effect_js__rspack_import_0/* .scopeTag */.DLK; +/** + * Creates a new `Scope` with the specified finalizer strategy. + * + * **Example** (Creating a scope) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 2"))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * cleanups // => ["Cleanup 2", "Cleanup 1"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = _internal_effect_js__rspack_import_0/* .scopeMake */.RWE; +/** + * 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"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = _internal_effect_js__rspack_import_0/* .scopeMakeUnsafe */.d97; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const provide = _internal_effect_js__rspack_import_0/* .provideScope */.AAo; +/** + * Registers an exit-aware finalizer on a scope. + * + * **When to use** + * + * Use when cleanup needs to know whether the scope closed with success, + * failure, or interruption. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes and receives + * the scope's exit value. If the scope is already closed, the finalizer runs + * immediately with the stored exit value. + * + * **Example** (Adding an exit-aware finalizer) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const exits: Array> = [] + * const withResource = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizerExit(scope, (exit) => Effect.sync(() => exits.push(exit))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(withResource) + * exits // => [Exit.void] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizerExit = _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio; +/** + * Registers a finalizer effect on a scope. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes, regardless of + * whether the scope closes successfully or with an error. If the scope is + * already closed, the finalizer runs immediately. + * + * **Example** (Adding finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 2"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 3"))) + * events.push("work") + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * events // => ["work", "cleanup 3", "cleanup 2", "cleanup 1"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_0/* .scopeAddFinalizer */.iLB; +/** + * Creates a closeable child scope registered with a parent scope. + * + * **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) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const nestedScopes = Effect.gen(function*() { + * const parentScope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) + * const childScope = yield* Scope.fork(parentScope, "parallel") + * yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) + * yield* Scope.close(childScope, Exit.void) + * yield* Scope.close(parentScope, Exit.void) + * }) + * + * Effect.runSync(nestedScopes) + * cleanups // => ["child", "parent"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const fork = _internal_effect_js__rspack_import_0/* .scopeFork */.Z$R; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const forkUnsafe = _internal_effect_js__rspack_import_0/* .scopeForkUnsafe */.pSt; +/** + * 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`. + * + * **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"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const close = _internal_effect_js__rspack_import_0/* .scopeClose */.vDJ; +/** + * Closes a scope unsafely with the provided exit value. + * + * **When to use** + * + * Use when implementing lower-level scope machinery that must transition a + * scope to `Closed` immediately and can run the returned finalizer effect when + * one is produced. + * + * **Details** + * + * Returns an effect that runs registered finalizers, or `undefined` when the + * scope was already closed or no finalizers need to run. + * + * **Gotchas** + * + * Ignoring the returned effect skips registered finalizers. + * + * @see {@link close} for the usual effectful close operation that always returns an `Effect` + * + * @category unsafe + * @since 4.0.0 + */ +const closeUnsafe = _internal_effect_js__rspack_import_0/* .scopeCloseUnsafe */.fou; +/** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * + * @category combinators + * @since 2.0.0 + */ +const use = _internal_effect_js__rspack_import_0/* .scopeUse */.mdu; +//# sourceMappingURL=Scope.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Fp: forkUnsafe, + Gt: provide, + LZ: makeUnsafe, + U9: addFinalizer, + VN: close, + a6: addFinalizerExit +}); + + +}, +"./node_modules/effect/dist/Semaphore.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + + +/** + * Creates a `Semaphore` synchronously with the specified total + * number of permits. + * + * **When to use** + * + * Use to construct a semaphore synchronously when an immediate value is + * required outside an Effect workflow. + * + * **Example** (Creating an unsafe semaphore) + * + * ```ts import.meta.vitest + * import { Effect, Semaphore } from "effect" + * + * const semaphore = Semaphore.makeUnsafe(3) + * + * const task = (id: number) => + * semaphore.withPermits(1)( + * Effect.gen(function*() { + * yield* Effect.yieldNow + * return id + * }) + * ) + * + * // Only 3 tasks can run concurrently + * const program = Effect.all([ + * task(1), + * task(2), + * task(3), + * task(4), + * task(5) + * ], { concurrency: "unbounded" }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = permits => new SemaphoreImpl(permits); +const waitForPermits = (self, n, effect) => _internal_effect_js__rspack_import_0/* .callback */.E2r(resume => { + if (self.free >= n) return resume(effect); + const observer = () => { + if (self.free < n) return; + self.waiters.delete(observer); + resume(effect); + }; + self.waiters.add(observer); + return _internal_effect_js__rspack_import_0/* .sync */.OH5(() => { + self.waiters.delete(observer); + }); +}); +class SemaphoreImpl { + waiters = /*#__PURE__*/new Set(); + taken = 0; + permits; + constructor(permits) { + this.permits = permits; + } + get free() { + return this.permits - this.taken; + } + take(n) { + const take = _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) { + return waitForPermits(this, n, take); + } + this.taken += n; + return _internal_effect_js__rspack_import_0/* .succeed */.PyW(n); + }); + return take; + } + takeIfAvailable(n) { + return _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) return _internal_effect_js__rspack_import_0/* .succeed */.PyW(false); + this.taken += n; + return _internal_effect_js__rspack_import_0/* .succeed */.PyW(true); + }); + } + releaseUnsafe(fiber, n) { + this.taken -= n; + if (this.waiters.size > 0) { + fiber.currentDispatcher.scheduleTask(() => { + for (const observer of this.waiters) { + if (this.free <= 0) break; + observer(); + } + }, 0); + } + return this.free; + } + resize(permits) { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => { + this.permits = permits; + if (this.free < 0) return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + this.releaseUnsafe(fiber, 0); + return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + }); + } + release(n) { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => _internal_effect_js__rspack_import_0/* .succeed */.PyW(this.releaseUnsafe(fiber, n))); + } + get releaseAll() { + return _internal_core_js__rspack_import_1/* .withFiber */.R6(fiber => _internal_effect_js__rspack_import_0/* .succeed */.PyW(this.releaseUnsafe(fiber, this.taken))); + } + withPermits(n) { + return self => _internal_effect_js__rspack_import_0/* .uninterruptibleMask */.FcF(restore => { + const acquire = _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + if (this.free < n) { + const wait = waitForPermits(this, n, _internal_effect_js__rspack_import_0/* ["void"] */.rIH); + return _internal_effect_js__rspack_import_0/* .flatMap */.qIB(restore(wait), () => acquire); + } + this.taken += n; + return _internal_effect_js__rspack_import_0/* .onExitPrimitive */.r7h(restore(self), () => { + this.releaseUnsafe(_internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku(), n); + return undefined; + }, true); + }); + return acquire; + }); + } + withPermit = /*#__PURE__*/this.withPermits(1); + withPermitsIfAvailable(n) { + return self => _internal_effect_js__rspack_import_0/* .uninterruptibleMask */.FcF(restore => { + if (this.free < n) return _internal_effect_js__rspack_import_0/* .succeedNone */.lwU; + this.taken += n; + return _internal_effect_js__rspack_import_0/* .onExitPrimitive */.r7h(restore(_internal_effect_js__rspack_import_0/* .asSome */.Xx$(self)), () => { + this.releaseUnsafe(_internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku(), n); + return undefined; + }, true); + }); + } +} +/** + * Creates a `Semaphore` initialized with the specified total number of permits. + * + * **When to use** + * + * Use to create a semaphore inside Effect code for bounding concurrency with + * automatic or manual permit management. + * + * **Example** (Creating a semaphore) + * + * ```ts import.meta.vitest + * import { Effect, Semaphore } from "effect" + * + * const program = Effect.gen(function*() { + * const semaphore = yield* Semaphore.make(2) + * + * const task = (id: number) => + * semaphore.withPermits(1)( + * Effect.gen(function*() { + * yield* Effect.yieldNow + * return id + * }) + * ) + * + * // Run 4 tasks, but only 2 can run concurrently + * return yield* Effect.all([task(1), task(2), task(3), task(4)]) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = permits => internal.sync(() => new SemaphoreImpl(permits)); +/** + * Sets the total number of permits managed by the semaphore. + * + * **When to use** + * + * Use to change the concurrency limit of an existing semaphore while keeping + * current acquisitions in place. + * + * **Details** + * + * Existing acquisitions remain taken after resizing. If the new total is less + * than the currently taken permit count, new acquisitions wait until enough + * permits are released. + * + * @see {@link make} for creating a semaphore with an initial permit count + * @see {@link release} for returning permits without changing semaphore capacity + * + * @category combinators + * @since 4.0.0 + */ +const resize = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.resize(permits)))); +/** + * Runs an effect with the given number of permits and releases the permits when + * the effect completes. + * + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits + * for the duration of that effect. + * + * **Details** + * + * The effect waits until enough permits are available. Acquired permits are + * released when the wrapped effect exits. + * + * @see {@link withPermit} for acquiring exactly one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * + * @category combinators + * @since 4.0.0 + */ +const withPermits = (self, permits, effect) => { + const withPermits = self.withPermits(permits); + return effect ? withPermits(effect) : withPermits; +}; +/** + * Runs an effect with a single permit and releases the permit when the effect + * completes. + * + * **When to use** + * + * Use to guard an effect with exactly one semaphore permit while automatically + * releasing that permit when the effect exits. + * + * @see {@link withPermits} for acquiring more than one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * + * @category combinators + * @since 4.0.0 + */ +const withPermit = (self, effect) => { + if (!effect) return self.withPermit; + return self.withPermit(effect); +}; +/** + * Runs an effect only if the specified number of permits are immediately + * available. + * + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * + * **Details** + * + * When the permits are unavailable, the effect is not run and the result is + * `Option.none`. When permits are available, the effect is run, its result is + * wrapped in `Option.some`, and the acquired permits are released when the + * effect exits. + * + * @see {@link withPermits} for the variant that waits until permits are available + * + * @category combinators + * @since 4.0.0 + */ +const withPermitsIfAvailable = (self, permits, effect) => { + const withPermits = self.withPermitsIfAvailable(permits); + return effect ? withPermits(effect) : withPermits; +}; +/** + * Acquires the specified number of permits and returns the acquired permit + * count. + * + * **When to use** + * + * Use when you need manual permit acquisition for a lower-level protocol with + * explicit acquisition and release control. + * + * **Details** + * + * The effect waits until enough permits are available. + * + * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect + * @see {@link takeIfAvailable} for manually acquiring permits without waiting + * @see {@link release} for returning manually acquired permits + * + * @category combinators + * @since 4.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.take(permits)))); +/** + * Acquires the specified number of permits only if they are immediately + * available. + * + * **When to use** + * + * Use when you need fail-fast manual permit acquisition for a lower-level + * protocol with explicit acquisition and release control. + * + * **Details** + * + * If enough permits are available, they are acquired and the effect returns + * `true`. Otherwise, the effect returns `false` immediately without acquiring + * any permits. + * + * @see {@link take} for the variant that waits until permits are available + * @see {@link release} for returning manually acquired permits + * @see {@link withPermitsIfAvailable} for automatic acquisition and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const takeIfAvailable = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.takeIfAvailable(permits)))); +/** + * Releases the specified number of permits and returns the resulting available + * permits. + * + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. + * + * **Details** + * + * Running the effect releases the requested permits, wakes waiting acquirers + * when permits become available, and returns the current available permit + * count. + * + * **Gotchas** + * + * Manual `take` / `release` usage must keep permit counts balanced. Prefer + * `withPermit` or `withPermits` when the acquisition can be scoped to one + * effect. + * + * @see {@link take} for manually acquiring permits + * @see {@link releaseAll} for returning every currently taken permit + * @see {@link withPermits} for automatic acquire and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const release = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, permits) => self.release(permits)))); +/** + * Releases all permits held by this semaphore and returns the resulting + * available permits. + * + * **When to use** + * + * Use to return every currently taken permit to a semaphore at once, typically + * during cleanup of manual `take` / `release` protocols. + * + * @see {@link release} for releasing a known permit count + * @see {@link withPermits} for automatic acquire and release around an effect + * + * @category combinators + * @since 4.0.0 + */ +const releaseAll = self => self.releaseAll; +//# sourceMappingURL=Semaphore.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + LZ: makeUnsafe +}); + + +}, +"./node_modules/effect/dist/Stream.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Cause_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Channel_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Channel.js"); +/* import */ var _Effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var _Function_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_stream_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/stream.js"); +/* import */ var _Option_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Describes effectful sources that emit values over time. + * + * A `Stream` can emit many `A` values, fail with `E`, and require + * services `R` while it is being consumed. Streams are useful for data that is + * pulled in steps, such as values from collections, queues, pubsubs, schedules, + * callbacks, async iterables, or platform streams. The APIs here cover the full + * stream lifecycle: create a stream, transform or combine it, control buffering + * and timing, handle failures, and finally consume it. + * + * @since 2.0.0 + */ +// @effect-diagnostics returnEffectInGen:off + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * Runtime identifier stored on `Stream` values and used by `isStream` to + * recognize them. + * + * **Details** + * + * This marker is part of the runtime representation of `Stream` values. Prefer + * `isStream` when narrowing unknown values. + * + * @see {@link isStream} for the public guard that checks this identifier + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = "~effect/Stream"; +/** + * Checks whether a value is a Stream. + * + * **Example** (Checking whether a value is a Stream) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * Stream.isStream(Stream.make(1, 2, 3)) // => true + * Stream.isStream({ data: [1, 2, 3] }) // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isStream = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +/** + * The default chunk size used by Stream constructors and combinators. + * + * **Example** (Reading the default chunk size) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * Stream.DefaultChunkSize // => 4096 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const DefaultChunkSize = (/* inlined export .DefaultChunkSize */4096); +/** + * Creates a stream from a array-emitting `Channel`. + * + * **Example** (Creating a stream from an array-emitting channel) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Stream } from "effect" + * + * const channel = Channel.succeed([1, 2, 3] as const) + * const stream = Stream.fromChannel(channel) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromChannel = _internal_stream_js__rspack_import_2/* .fromChannel */.E; +/** + * Creates a stream from an effect. + * + * **Example** (Creating a stream from an effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.fromEffect(Effect.succeed(42)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [42] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEffect = effect => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of))); +/** + * Accesses a service from the context and emits it as a single element. + * + * **Example** (Accessing a service as a stream) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.service(Greeter).pipe( + * Stream.map((greeter) => greeter.greet("World")) + * ) + * + * await Effect.runPromise( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}!` + * }), + * Stream.runCollect + * ) + * ) // => ["Hello, World!"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const service = service => fromEffect(Effect.service(service)); +/** + * Optionally accesses a service from the context and emits the result as a + * single element. + * + * **When to use** + * + * Use when you need a stream that emits an optional service from the context + * without requiring that service to be present. + * + * **Example** (Accessing an optional service as a stream) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.serviceOption(Greeter).pipe( + * Stream.map((maybeGreeter) => + * Option.match(maybeGreeter, { + * onNone: () => "No greeter", + * onSome: (greeter) => greeter.greet("World") + * }) + * ) + * ) + * + * await Effect.runPromise( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}!` + * }), + * Stream.runCollect + * ) + * ) // => ["Hello, World!"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const serviceOption = service => fromEffect(Effect.serviceOption(service)); +/** + * Creates a stream that runs the effect and emits no elements. + * + * **Example** (Draining an effect into a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * let drained = false + * await Effect.runPromise( + * Stream.fromEffectDrain(Effect.sync(() => { + * drained = true + * })).pipe(Stream.runDrain) + * ) + * drained // => true + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectDrain = effect => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done()))); +/** + * Creates a stream from an effect producing a value of type `A` which repeats forever. + * + * **Example** (Repeating an effect forever) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * let n = 0 + * const stream = Stream.fromEffectRepeat(Effect.sync(() => ++n)).pipe(Stream.take(5)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3, 4, 5] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectRepeat = effect => fromPull(Effect.succeed(Effect.map(effect, Arr.of))); +/** + * Creates a stream from an effect producing a value of type `A`, which is + * repeated using the specified schedule. + * + * **Example** (Repeating an effect with a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const stream = Stream.fromEffectSchedule(Effect.succeed("ping"), Schedule.recurs(2)) + * await Effect.runPromise(Stream.runCollect(stream)) // => ["ping", "ping", "ping"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromEffectSchedule = (effect, schedule) => fromPull(Effect.gen(function* () { + const step = yield* Schedule.toStepWithMetadata(schedule); + let s = yield* Effect.provideService(effect, Schedule.CurrentMetadata, Schedule.CurrentMetadata.defaultValue()); + let initial = true; + const pull = Effect.suspend(() => step(s)).pipe(Effect.flatMap(meta => Effect.provideService(effect, Schedule.CurrentMetadata, meta)), Effect.map(next => { + s = next; + return Arr.of(next); + })); + return Effect.suspend(() => { + if (initial) { + initial = false; + return Effect.succeed(Arr.of(s)); + } + return pull; + }); +})); +/** + * Creates a stream that emits `void` immediately once, then emits another + * `void` after each specified interval. + * + * **Example** (Emitting ticks on an interval) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.tick(0).pipe(Stream.take(3), Stream.runCollect)) // => [undefined, undefined, undefined] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const tick = interval => fromPull(Effect.sync(() => { + let first = true; + const effect = Effect.succeed(Arr.of(undefined)); + const delayed = Effect.delay(effect, interval); + return Effect.suspend(() => { + if (first) { + first = false; + return effect; + } + return delayed; + }); +})); +/** + * Creates a stream from a pull effect, such as one produced by `Stream.toPull`. + * + * **Details** + * + * A pull effect yields chunks on demand and completes when the upstream stream ends. + * See `Stream.toPull` for a matching producer. + * + * **Example** (Creating a stream from a pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const source = Stream.make(1, 2, 3) + * const pull = yield* Stream.toPull(source) + * const stream = Stream.fromPull(Effect.succeed(pull)) + * return yield* Stream.runCollect(stream) + * }) + * ) + * + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPull = pull => fromChannel(_Channel_js__rspack_import_1/* .fromPull */.OB(pull)); +/** + * Derives a stream by transforming its pull effect. + * + * **Example** (Transforming a pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const transformed = Stream.transformPull(stream, (pull) => Effect.succeed(pull)) + * + * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPull = (self, f) => fromChannel(_Channel_js__rspack_import_1/* .fromTransform */.Z1((_, scope) => _Effect_js__rspack_import_3/* .flatMap */.qIB(_Channel_js__rspack_import_1/* .toPullScoped */.lB(self.channel, scope), pull => f(pull, scope)))); +/** + * Transforms a stream by effectfully transforming its pull effect. + * + * **Details** + * + * A forked scope is also provided to the transformation function, which is + * closed once the resulting stream has finished processing. + * + * **Example** (Transforming a stream by effectfully transforming its pull effect) + * + * ```ts import.meta.vitest + * import { Effect, Scope, Stream } from "effect" + * + * const finalized: Array = [] + * const stream = Stream.make(1, 2, 3) + * + * const transformed = Stream.transformPullBracket( + * stream, + * (pull, _scope, forkedScope) => + * Effect.gen(function*() { + * yield* Scope.addFinalizer(forkedScope, Effect.sync(() => finalized.push(true))) + * return pull + * }) + * ) + * + * await Effect.runPromise(Stream.runCollect(transformed)) // => [1, 2, 3] + * finalized // => [true] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const transformPullBracket = (self, f) => fromChannel(Channel.fromTransformBracket((_, scope, forkedScope) => Effect.flatMap(Channel.toPullScoped(self.channel, scope), pull => f(pull, scope, forkedScope)))); +/** + * Creates a channel from a stream. + * + * **Example** (Converting a stream to a channel) + * + * ```ts import.meta.vitest + * import { Channel, Effect, Stream } from "effect" + * + * const channel = Stream.toChannel(Stream.make(1, 2, 3)) + * const values = await Effect.runPromise(Channel.runCollect(channel)) + * values.flat() // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const toChannel = stream => stream.channel; +/** + * Creates a stream from a callback that can emit values into a queue. + * + * **When to use** + * + * Use when you need callback-based code to emit stream values by offering to a + * `Queue`, or signal stream completion through the `Queue` module APIs. + * + * By default it uses an "unbounded" buffer size. + * You can customize the buffer size and strategy by passing an object as the + * second argument with the `bufferSize` and `strategy` fields. + * + * **Example** (Creating a stream from a callback that can emit values into a queue) + * + * ```ts import.meta.vitest + * import { Effect, Queue, Stream } from "effect" + * + * const stream = Stream.callback((queue) => + * Effect.sync(() => { + * // Emit values to the stream + * Queue.offerUnsafe(queue, 1) + * Queue.offerUnsafe(queue, 2) + * Queue.offerUnsafe(queue, 3) + * // Signal completion + * Queue.endUnsafe(queue) + * }) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = (f, options) => fromChannel(Channel.callbackArray(f, options)); +/** + * Creates an empty stream. + * + * **Example** (Creating an empty stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.runCollect(Stream.empty)) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = /*#__PURE__*/fromChannel(_Channel_js__rspack_import_1/* .empty */.Ie); +/** + * Creates a single-valued pure stream. + * + * **Example** (Creating a single-valued pure stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.runCollect(Stream.succeed(3))) // => [3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeed = value => fromChannel(Channel.succeed(Arr.of(value))); +/** + * Creates a stream from a sequence of values. + * + * **Example** (Creating a stream from a sequence of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = (...values) => fromArray(values); +/** + * Creates a stream that synchronously evaluates a function and emits the result as a single value. + * + * **Details** + * + * The function is evaluated each time the stream is run. + * + * **Example** (Evaluating a value synchronously) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.sync(() => 2 + 1).pipe(Stream.runCollect)) // => [3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const sync = evaluate => fromChannel(Channel.sync(() => Arr.of(evaluate()))); +/** + * Creates a lazily constructed stream. + * + * **Details** + * + * The stream factory is evaluated each time the stream is run. + * + * **Example** (Creating a lazily constructed stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Stream.suspend(() => Stream.make(1, 2, 3)).pipe(Stream.runCollect)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = stream => fromChannel(Channel.suspend(() => stream().channel)); +/** + * Terminates with the specified error. + * + * **Example** (Failing a stream) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * await Effect.runPromise(Effect.exit(Stream.runCollect(Stream.fail("Uh oh!")))) // => Exit.fail("Uh oh!") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fail = error => fromChannel(Channel.fail(error)); +/** + * Terminates with the specified lazily evaluated error. + * + * **Example** (Failing a stream lazily) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * const stream = Stream.failSync(() => "Uh oh!") + * + * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail("Uh oh!") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = evaluate => fromChannel(Channel.failSync(evaluate)); +/** + * Creates a stream that fails with the specified `Cause`. + * + * **Example** (Failing with a cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const stream = Stream.failCause(Cause.fail("Database connection failed")).pipe( + * Stream.catchCause(() => Stream.succeed("recovered")) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => ["recovered"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = cause => fromChannel(Channel.failCause(cause)); +/** + * The stream that dies with the specified defect. + * + * **Example** (Dying with a defect) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Stream } from "effect" + * + * const defect = new Error("Boom") + * const stream = Stream.die(defect) + * + * await Effect.runPromise(Effect.exit(Stream.runCollect(stream))) // => Exit.failCause(Cause.die(defect)) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const die = defect => fromChannel(Channel.die(defect)); +/** + * The stream that always fails with the specified lazily evaluated `Cause`. + * + * **Example** (Failing with a lazy cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit, Stream } from "effect" + * + * const stream = Stream.failCauseSync(() => + * Cause.fail("Connection timeout after retries") + * ) + * + * await Effect.runPromise(Stream.runCollect(stream).pipe(Effect.exit)) // => Exit.fail("Connection timeout after retries") + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = evaluate => fromChannel(Channel.failCauseSync(evaluate)); +/** + * Creates a stream that consumes values from an iterator. + * + * **Details** + * + * The `maxChunkSize` parameter controls how many values are pulled per chunk. + * + * **Example** (Consuming values from an iterator) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * function* numbers() { + * yield 1 + * yield 2 + * yield 3 + * } + * + * const stream = Stream.fromIteratorSucceed(numbers()) + * + * const program = Effect.gen(function* () { + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIteratorSucceed = (iterator, maxChunkSize) => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize)); +/** + * Creates a new `Stream` from an iterable collection of values. + * + * **Details** + * + * - `chunkSize`: Maximum number of values emitted per chunk. + * + * **Example** (Creating a stream from an iterable) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const numbers = [1, 2, 3] + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromIterable(numbers) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = (iterable, options) => Array.isArray(iterable) && options?.chunkSize === undefined ? fromArray(iterable) : fromChannel(Channel.fromIterableArray(iterable, options?.chunkSize)); +/** + * Creates a stream from an effect producing an iterable of values. + * + * **When to use** + * + * Use when the iterable must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an iterable effect) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class UserRepo extends Context.Service> + * }>()("UserRepo") {} + * + * const listUsers = Effect.service(UserRepo).pipe( + * Effect.andThen((repo) => repo.list) + * ) + * + * const stream = Stream.fromIterableEffect(listUsers) + * + * const program = Effect.gen(function*() { + * const users = yield* stream.pipe( + * Stream.provideService(UserRepo, { + * list: Effect.succeed(["user1", "user2"]) + * }), + * Stream.runCollect + * ) + * users // => ["user1", "user2"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableEffect = iterable => unwrap(Effect.map(iterable, fromIterable)); +/** + * Creates a stream by repeatedly running an effect that yields an iterable of values. + * + * **Example** (Repeating an iterable effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromIterableEffectRepeat(Effect.succeed([1, 2])).pipe( + * Stream.take(5) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 1, 2, 1] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromIterableEffectRepeat = iterable => flatMap(fromEffectRepeat(iterable), fromIterable); +/** + * Creates a stream from an array of values. + * + * **Example** (Creating a stream from an array of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArray([1, 2, 3]) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArray = array => _Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(array) ? fromChannel(_Channel_js__rspack_import_1/* .succeed */.Py(array)) : empty; +/** + * Creates a stream from an effect that produces an array of values. + * + * **When to use** + * + * Use when the array must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an effect that produces an array of values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArrayEffect(Effect.succeed(["Ada", "Grace"])) + * const values = yield* Stream.runCollect(stream) + * values // => ["Ada", "Grace"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArrayEffect = effect => unwrap(Effect.map(effect, fromArray)); +/** + * Creates a stream from an arbitrary number of arrays. + * + * **Example** (Creating a stream from an arbitrary number of arrays) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromArrays([1, 2], [3, 4]) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromArrays = (...arrays) => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty))); +/** + * Creates a stream that pulls values from a `Queue.Dequeue`. + * + * **Details** + * + * The stream emits non-empty batches of queued values and ends when the queue + * fails with `Cause.Done`; other queue failures are propagated. + * + * **Example** (Creating a stream from a queue of values) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.unbounded() + * yield* Queue.offer(queue, 1) + * yield* Queue.offer(queue, 2) + * yield* Queue.offer(queue, 3) + * yield* Queue.end(queue) + * + * const stream = Stream.fromQueue(queue) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromQueue = queue => fromChannel(Channel.fromQueueArray(queue)); +/** + * Creates a stream from a subscription to a `PubSub`. + * + * **Example** (Creating a stream from a subscription to a PubSub) + * + * ```ts import.meta.vitest + * import { Effect, Fiber, PubSub, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded({ replay: 3 }) + * + * const fiber = yield* Stream.fromPubSub(pubsub).pipe( + * Stream.take(3), + * Stream.runCollect, + * Effect.forkChild + * ) + * + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * yield* PubSub.publish(pubsub, 3) + * + * const values = yield* Fiber.join(fiber) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromPubSub = pubsub => fromChannel(Channel.fromPubSubArray(pubsub)); +/** + * Creates a stream from a PubSub of `Take` values. + * + * **Details** + * + * `Take` values include end and failure signals. + * + * **Example** (Creating a stream from PubSub takes) + * + * ```ts import.meta.vitest + * import { Effect, Exit, PubSub, Stream, Take } from "effect" + * + * const program = Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded>({ + * replay: 3 + * }) + * + * yield* PubSub.publish(pubsub, [1]) + * yield* PubSub.publish(pubsub, [2]) + * yield* PubSub.publish(pubsub, Exit.succeed(undefined)) + * + * const values = yield* Stream.fromPubSubTake(pubsub).pipe(Stream.runCollect) + * values // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPubSubTake = pubsub => fromChannel(Channel.fromPubSubTake(pubsub)); +/** + * Creates a stream from a lazily supplied Web `ReadableStream`. + * + * **Details** + * + * The stream reads from a `ReadableStreamDefaultReader`, maps read failures + * with `onError`, and closes the reader when the stream finalizes. By default + * the reader is canceled; set `releaseLockOnEnd` to release the lock instead. + * + * **Example** (Creating a stream from a ReadableStream) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} + * + * const readableStream = new ReadableStream({ + * start(controller) { + * controller.enqueue(1) + * controller.enqueue(2) + * controller.enqueue(3) + * controller.close() + * } + * }) + * + * const program = Effect.gen(function*() { + * const stream = Stream.fromReadableStream({ + * evaluate: () => readableStream, + * onError: (cause) => new StreamError({ cause }) + * }) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromReadableStream = options => fromChannel(_Channel_js__rspack_import_1/* .fromReadableStream */.fp(options)); +/** + * Creates a stream from an AsyncIterable. + * + * **Example** (Creating a stream from an AsyncIterable) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} + * + * const iterable = (async function*() { + * yield 1 + * yield 2 + * yield 3 + * })() + * + * await Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause })) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * })) + * + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromAsyncIterable = (iterable, onError) => fromChannel(Channel.fromAsyncIterableArray(iterable, onError)); +/** + * Creates a stream that emits each output of a schedule that does not require input, + * for as long as the schedule continues. + * + * **Example** (Creating a stream from a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const schedule = Schedule.recurs(3) + * const stream = Stream.fromSchedule(schedule) + * const values = yield* Stream.runCollect(stream) + * values // => [0, 1, 2] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromSchedule = schedule => fromPull(Effect.map(Schedule.toStepWithSleep(schedule), step => Pull.catchDone(Effect.map(step(void 0), Arr.of), () => Cause.done()))); +/** + * Creates a stream from a PubSub subscription. + * + * **When to use** + * + * Use when you already have a `PubSub.Subscription` and want to expose its + * messages as a `Stream`, with `Stream.take` or cancellation controlling how + * many values are consumed. + * + * **Example** (Creating a stream from a PubSub subscription) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function*() { + * const pubsub = yield* PubSub.unbounded() + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* PubSub.publish(pubsub, 1) + * yield* PubSub.publish(pubsub, 2) + * + * const stream = Stream.fromSubscription(subscription) + * const values = yield* stream.pipe(Stream.take(2), Stream.runCollect) + * values // => [1, 2] + * })) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromSubscription = pubsub => fromChannel(Channel.fromSubscriptionArray(pubsub)); +/** + * Creates a stream from an event listener. + * + * **Example** (Creating a stream from an event listener) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * class NumberTarget implements Stream.EventListener { + * addEventListener(event: string, f: (event: number) => void) { + * if (event === "data") { + * f(1) + * f(2) + * f(3) + * } + * } + * removeEventListener(_event: string, _f: (event: number) => void) {} + * } + * + * await Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromEventListener(new NumberTarget(), "data").pipe( + * Stream.take(3) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * })) + * + * ``` + * + * @category constructors + * @since 3.1.0 + */ +const fromEventListener = (target, type, options) => callback(queue => { + function emit(event) { + Queue.offerUnsafe(queue, event); + } + return Effect.acquireRelease(Effect.sync(() => target.addEventListener(type, emit, options)), () => Effect.sync(() => target.removeEventListener(type, emit, options))); +}, { + bufferSize: typeof options === "object" ? options.bufferSize : undefined +}); +/** + * Creates a stream by repeatedly applying an effectful step function to a + * state. + * + * **Details** + * + * Each `readonly [value, nextState]` result emits `value` and continues with + * `nextState`; returning `undefined` ends the stream. + * + * **Example** (Unfolding stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1] as const)) + * const values = yield* Stream.runCollect(stream.pipe(Stream.take(5))) + * values // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (s, f) => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let state = s; + return _Effect_js__rspack_import_3/* .flatMap */.qIB(_Effect_js__rspack_import_3/* .suspend */.DYE(() => f(state)), next => { + if (next === undefined) return _Cause_js__rspack_import_5/* .done */.Vw(); + state = next[1]; + return _Effect_js__rspack_import_3/* .succeed */.PyW(_Array_js__rspack_import_4.of(next[0])); + }); +})); +/** + * Creates a stream by repeatedly evaluating an effectful page function. + * + * **When to use** + * + * Use to consume paginated APIs where each step returns a batch of values + * together with an optional next state. + * + * **Details** + * + * This is similar to {@link unfold}, but each step can emit zero or more values + * and independently decide whether another state should be requested. + * + * **Example** (Paginating stream state) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.paginate(0, (n: number) => + * Effect.succeed( + * [ + * [n], + * n < 3 ? Option.some(n + 1) : Option.none() + * ] as const + * )) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [0, 1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const paginate = (s, f) => fromPull(_Effect_js__rspack_import_3/* .sync */.OH5(() => { + let state = s; + let done = false; + return _Effect_js__rspack_import_3/* .suspend */.DYE(function loop() { + if (done) return _Cause_js__rspack_import_5/* .done */.Vw(); + return _Effect_js__rspack_import_3/* .flatMap */.qIB(f(state), ([a, s]) => { + if (_Option_js__rspack_import_6.isNone(s)) { + done = true; + } else { + state = s.value; + } + if (!_Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(a)) return loop(); + return _Effect_js__rspack_import_3/* .succeed */.PyW(a); + }); + }); +})); +/** + * Creates an infinite stream by repeatedly applying a function to a seed value. + * + * **Example** (Iterating from a seed value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.iterate(1, (n) => n + 1).pipe(Stream.take(3)) + * + * const program = Effect.gen(function* () { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const iterate = (value, next) => unfold(value, a => Effect.succeed([a, next(a)])); +/** + * Constructs a stream from a range of integers, including both endpoints. + * + * **Details** + * + * If the provided `min` is greater than `max`, the stream will not emit any + * values. + * + * **Example** (Creating a numeric range) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.range(1, 5).pipe(Stream.runCollect) + * values // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const range = (min, max, chunkSize = (/* inlined export .DefaultChunkSize */4096)) => min > max ? empty : fromPull(Effect.sync(() => { + const size = Math.max(1, chunkSize); + let start = min; + let done = false; + return Effect.suspend(() => { + if (done) return Cause.done(); + const remaining = max - start + 1; + if (remaining > size) { + const chunk = Arr.range(start, start + size - 1); + start += size; + return Effect.succeed(chunk); + } + const chunk = Arr.range(start, start + remaining - 1); + done = true; + return Effect.succeed(chunk); + }); +})); +/** + * The stream that never produces any value or fails with any error. + * + * **Example** (Creating a never-ending stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.never.pipe( + * Stream.take(0), + * Stream.runCollect + * ) + * + * await Effect.runPromise(program) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = /*#__PURE__*/fromChannel(_Channel_js__rspack_import_1/* .never */.Zm); +/** + * Creates a stream produced from an `Effect`. + * + * **Example** (Unwrapping a stream effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const effect = Effect.succeed(Stream.make(1, 2, 3)) + * + * const stream = Stream.unwrap(effect) + * + * const program = Effect.gen(function*() { + * const chunk = yield* Stream.runCollect(stream) + * chunk // => [ 1, 2, 3 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unwrap = effect => fromChannel(_Channel_js__rspack_import_1/* .unwrap */.oA(_Effect_js__rspack_import_3/* .map */.TjK(effect, toChannel))); +/** + * Runs a stream that requires `Scope` in a managed scope, ensuring its + * finalizers are run when the stream completes. + * + * **Example** (Scoping a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.scoped( + * Stream.fromEffect( + * Effect.acquireRelease( + * Effect.sync(() => { + * events.push("acquire") + * return "resource" + * }), + * () => Effect.sync(() => events.push("release")) + * ) + * ) + * ) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => ["resource"] + * events // => ["acquire", "release"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const scoped = self => fromChannel(Channel.scoped(self.channel)); +/** + * Transforms the elements of this stream using the supplied function. + * + * **Example** (Mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.map((n, i) => n + i)) + * await Effect.runPromise(Stream.runCollect(stream)) // => [1, 3, 5] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => suspend(() => { + let i = 0; + return fromChannel(Channel.map(self.channel, Arr.map(o => f(o, i++)))); +})))); +/** + * Maps both the failure and success channels of a stream. + * + * **Example** (Mapping both the failure and success channels of a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const mapper = { + * onFailure: (error: string) => `error: ${error}`, + * onSuccess: (value: number) => value * 2 + * } + * + * const program = Effect.gen(function*() { + * const success = yield* Stream.make(1, 2).pipe( + * Stream.mapBoth(mapper), + * Stream.runCollect + * ) + * success // => [ 2, 4 ] + * + * const failure = yield* Stream.fail("boom").pipe( + * Stream.mapBoth(mapper), + * Stream.catch((error: string) => Stream.succeed(error)), + * Stream.runCollect + * ) + * failure // => [ 'error: boom' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => self.pipe(map(options.onSuccess), mapError(options.onFailure))))); +/** + * Transforms each emitted chunk using the provided function, which receives the chunk and its index. + * + * **Example** (Mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.mapArray((chunk, index) => Array.map(chunk, (n) => n + index)), + * Stream.runCollect + * ) + * result // => [ 1, 2, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.map(self.channel, f))))); +/** + * Maps over elements of the stream with the specified effectful function. + * + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.make(1, 2, 3) + * + * const mappedStream = stream.pipe( + * Stream.mapEffect((n) => + * Effect.sync(() => { + * events.push(`Processing: ${n}`) + * return n * 2 + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(mappedStream) + * result // => [2, 4, 6] + * }) + * + * await Effect.runPromise(program) + * events // => ["Processing: 1", "Processing: 2", "Processing: 3"] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => self.channel.pipe(_Channel_js__rspack_import_1/* .flattenArray */.ed, _Channel_js__rspack_import_1/* .mapEffect */.WK(f, options), _Channel_js__rspack_import_1/* .map */.Tj(_Array_js__rspack_import_4.of), fromChannel)); +/** + * Flattens a stream of `Effect` values into a stream of their results. + * + * **When to use** + * + * Use when stream elements already are effects and their successes should become + * stream elements while their failures enter the stream error channel. + * + * **Example** (Flattening a stream of Effect values into a stream of their results) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(Effect.succeed(1), Effect.succeed(2), Effect.succeed(3)) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream.pipe(Stream.flattenEffect())) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flattenEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => mapEffect(self, identity, options)))); +/** + * Maps over non-empty array chunks emitted by the stream effectfully. + * + * **When to use** + * + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. + * + * **Example** (Effectfully mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3, 4]).pipe( + * Stream.rechunk(2), + * Stream.mapArrayEffect((chunk, index) => + * Effect.succeed(Array.map(chunk, (n) => n + index * 10)) + * ), + * Stream.runCollect + * ) + * result // => [ 1, 2, 13, 14 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.mapEffect(self.channel, f))))); +/** + * Lifts failures and successes into a `Result`, yielding a stream that cannot fail. + * + * **Details** + * + * The stream ends after the first failure, emitting a `Result.fail` value. + * + * **Example** (Converting failures to results) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const results = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.result, + * Stream.map(Result.match({ + * onFailure: (error) => `failure: ${error}`, + * onSuccess: (value) => `success: ${value}` + * })), + * Stream.runCollect + * ) + * results // => [ 'success: 1', 'success: 2', 'failure: boom' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const result = self => self.pipe(map(Result.succeed), catch_(e => succeed(Result.fail(e)))); +/** + * Runs the provided effect for each element while preserving the elements. + * + * **Example** (Tapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.tap((n) => Effect.sync(() => events.push(`before mapping: ${n}`))), + * Stream.map((n) => n * 2), + * Stream.tap((n) => Effect.sync(() => events.push(`after mapping: ${n}`))), + * Stream.runCollect + * ) + * + * result // => [2, 4, 6] + * }) + * + * await Effect.runPromise(program) + * events // => ["before mapping: 1", "after mapping: 2", "before mapping: 2", "after mapping: 4", "before mapping: 3", "after mapping: 6"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => mapEffect(self, a => _Effect_js__rspack_import_3.as(f(a), a), options)); +/** + * Returns a stream that effectfully "peeks" at elements and failures. + * + * **Example** (Tapping values and errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapBoth({ + * onElement: (value) => Effect.sync(() => events.push(`seen: ${value}`)), + * onError: (error) => Effect.sync(() => events.push(`error: ${error}`)) + * }), + * Stream.catch(() => Stream.make(3)) + * ) + * const result = yield* Stream.runCollect(stream) + * result // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["seen: 1", "seen: 2", "error: boom"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => self.pipe(tapError(options.onError), tap(options.onElement, { + concurrency: options.concurrency +}))))); +/** + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Ref, Sink, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const seen = yield* Ref.make>([]) + * const sink = Sink.forEach((value: number) => + * Ref.update(seen, (items) => [...items, value]) + * ) + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.tapSink(sink), + * Stream.runCollect + * ) + * const tapped = yield* Ref.get(seen) + * tapped // => [ 1, 2, 3 ] + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapSink = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => transformPullBracket(self, Effect.fnUntraced(function* (pull, _, scope) { + const upstreamLatch = Latch.makeUnsafe(); + const sinkLatch = Latch.makeUnsafe(); + let chunk = undefined; + let causeSink = undefined; + let sinkDone = false; + let streamDone = false; + const sinkUpstream = upstreamLatch.whenOpen(Effect.suspend(() => { + if (chunk) { + const arr = chunk; + chunk = undefined; + if (!streamDone) upstreamLatch.closeUnsafe(); + return Effect.as(sinkLatch.open, arr); + } + return Cause.done(); + })); + yield* Effect.suspend(() => sink.transform(sinkUpstream, scope)).pipe(eff => Effect.onExitPrimitive(eff, exit => { + sinkDone = true; + if (Exit.isFailure(exit)) { + causeSink = exit.cause; + } + return sinkLatch.open; + }, true), Effect.forkIn(scope)); + const pullAndOffer = pull.pipe(Effect.flatMap(chunk_ => { + chunk = chunk_; + sinkLatch.closeUnsafe(); + upstreamLatch.openUnsafe(); + return Effect.as(sinkLatch.await, chunk_); + }), Pull.catchDone(() => { + streamDone = true; + sinkLatch.closeUnsafe(); + upstreamLatch.openUnsafe(); + return Effect.flatMap(sinkLatch.await, () => Cause.done()); + })); + return Effect.suspend(() => { + if (causeSink) { + return Effect.failCause(causeSink); + } else if (sinkDone) { + return pull; + } + return pullAndOffer; + }); +}))))); +/** + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flat mapping stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.flatMap((n) => Stream.make(n, n * 2)), + * Stream.runCollect + * ) + * values // => [ 1, 2, 2, 4, 3, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, f, options) => self.channel.pipe(_Channel_js__rspack_import_1/* .flattenArray */.ed, _Channel_js__rspack_import_1/* .flatMap */.qI(a => f(a).channel, options), fromChannel)); +/** + * Switches to the latest stream produced by the mapping function, interrupting + * the previous stream when a new element arrives. + * + * **Example** (Switching to the latest stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make(1, 2, 3).pipe( + * Stream.switchMap((n) => (n === 3 ? Stream.make(n) : Stream.never)), + * Stream.runCollect + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* program + * result // => [ 3 ] + * })) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const switchMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => self.channel.pipe(Channel.flattenArray, Channel.switchMap(a => f(a).channel, options), fromChannel)))); +/** + * Flattens a stream of streams into a single stream. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * strict order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flattening nested streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const streamOfStreams = Stream.make( + * Stream.make(1, 2), + * Stream.make(3, 4), + * Stream.make(5, 6) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(Stream.flatten(streamOfStreams)) + * values // => [ 1, 2, 3, 4, 5, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, options) => flatMap(self, _Function_js__rspack_import_7/* .identity */.D_, options)); +/** + * Flattens a stream of non-empty arrays into a stream of elements. + * + * **Example** (Flattening a stream of non-empty arrays into a stream of elements) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const stream = Stream.make(Array.make(1, 2), Array.make(3)) + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.runCollect(Stream.flattenArray(stream)) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flattenArray = self => fromChannel(Channel.flattenArray(self.channel)); +/** + * Converts this stream to one that runs its effects but emits no elements. + * + * **Example** (Draining stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 6).pipe(Stream.drain, Stream.runCollect) + * result // => [] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const drain = self => fromChannel(Channel.drain(self.channel)); +/** + * Runs the provided stream in the background while this stream runs, interrupting it + * when this stream completes and failing if the background stream fails or defects. + * + * **Example** (Draining a stream in the background) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const foreground = Stream.make(1, 2) + * const background = Stream.fromEffect(Effect.sync(() => events.push("background task"))) + * + * const program = Effect.gen(function*() { + * const values = yield* foreground.pipe( + * Stream.drainFork(background), + * Stream.runCollect + * ) + * values // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * events // => ["background task"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const drainFork = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => mergeEffect(self, runDrain(that))))); +/** + * Repeats the entire stream according to the provided schedule. + * + * **Example** (Repeating a stream on a schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.make(1).pipe( + * Stream.repeat(Schedule.recurs(4)), + * Stream.runCollect + * ) + * + * result // => [ 1, 1, 1, 1, 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => fromChannel(Channel.repeat(self.channel, schedule))))); +/** + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.schedule(Schedule.recurs(3)), + * Stream.runCollect + * ) + * + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => self.channel.pipe(Channel.flattenArray, Channel.schedule(schedule), Channel.map(Arr.of), fromChannel)))); +/** + * Ends the stream if it does not produce a value within the specified duration. + * + * **Example** (Timing out a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1).pipe( + * Stream.concat(Stream.never), + * Stream.timeout("1 second"), + * Stream.runCollect + * ) + * values // => [ 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timeout = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, duration) => timeoutOrElse(self, { + duration, + orElse: () => empty +})))); +/** + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category delays & timeouts + * @since 4.0.0 + */ +const timeoutOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const duration = Duration.fromInputUnsafe(options.duration); + if (!Duration.isFinite(duration)) return self; + if (Duration.isZero(duration)) return suspend(options.orElse); + const timeoutSymbol = Symbol(); + return catchCause(suspend(() => { + const parent = Fiber.getCurrent(); + const clock = parent.getRef(Clock); + const durationMs = Duration.toMillis(duration); + let deadline = undefined; + const latch = Latch.makeUnsafe(false); + return merge(transformPull(self, (pull, _scope) => Effect.suspend(() => { + deadline = clock.currentTimeMillisUnsafe() + durationMs; + latch.openUnsafe(); + return pull; + }).pipe(Effect.map(arr => { + latch.closeUnsafe(); + deadline = undefined; + return arr; + }), Effect.succeed)), fromEffectDrain(Effect.gen(function* () { + while (true) { + yield* latch.await; + if (deadline === undefined) continue; + yield* Effect.sleep(deadline - clock.currentTimeMillisUnsafe()); + if (deadline === undefined) continue; + const remaining = deadline - clock.currentTimeMillisUnsafe(); + if (remaining > 0) continue; + return yield* Effect.die(timeoutSymbol); + } + })), { + haltStrategy: "left" + }); + }), cause => { + const isTimeout = cause.reasons.find(r => r._tag === "Die" && r.defect === timeoutSymbol); + if (isTimeout) return options.orElse(); + return failCause(cause); + }); +}))); +/** + * Repeats each element of the stream according to the provided schedule, + * including the original emission. + * + * **Example** (Repeating stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make("A", "B", "C").pipe( + * Stream.repeatElements(Schedule.recurs(1)), + * Stream.runCollect + * ) + * values // => [ 'A', 'A', 'B', 'B', 'C', 'C' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const repeatElements = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => fromChannel(Channel.fromTransform((upstream, scope) => Effect.map(Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope), pullElement => { + let pullRepeat = undefined; + const pull = Effect.gen(function* () { + const element = yield* pullElement; + const chunk = Arr.of(element); + const step = yield* Schedule.toStepWithSleep(schedule); + pullRepeat = step(element).pipe(Effect.as(chunk), Pull.catchDone(_ => { + pullRepeat = undefined; + return pull; + })); + return chunk; + }); + return Effect.suspend(() => pullRepeat ?? pull); +})))))); +/** + * Repeats this stream forever. + * + * **Example** (Repeating a stream forever) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("A", "B").pipe( + * Stream.forever, + * Stream.take(5) + * ) + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.runCollect(stream) + * output // => [ 'A', 'B', 'A', 'B', 'A' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const forever = self => fromChannel(Channel.forever(self.channel)); +/** + * Flattens the iterables emitted by this stream into the stream's structure. + * + * **Example** (Flattening iterable values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make([1, 2], [3, 4]).pipe(Stream.flattenIterable) + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const flattenIterable = self => flatMap(self, fromIterable); +/** + * Unwraps `Take` values, emitting elements from non-empty arrays and ending or + * failing when the `Exit` signals completion. + * + * **Example** (Flattening Take values) + * + * ```ts import.meta.vitest + * import { Array, Effect, Exit, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const takes = Stream.make( + * Array.make(1, 2), + * Array.make(3), + * Exit.succeed(undefined) + * ) + * + * const values = yield* Stream.flattenTake(takes).pipe(Stream.runCollect) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flattenTake = self => self.channel.pipe(Channel.flattenArray, Channel.flattenTake, fromChannel); +/** + * Concatenates two streams, emitting all elements from the first stream + * followed by all elements from the second stream. + * + * **Example** (Concatenating streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.concat(Stream.make(1, 2, 3), Stream.make(4, 5, 6)) + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3, 4, 5, 6 ] + * })) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const concat = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, that) => flatten(fromArray([self, that]))); +/** + * Prepends the values from the provided iterable before the stream's elements. + * + * **Example** (Prepending values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(3, 4).pipe( + * Stream.prepend([1, 2]), + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, values) => concat(fromIterable(values), self)))); +/** + * Merges two streams, emitting elements from both as they arrive. + * + * **Details** + * + * By default, the merged stream ends when both streams end. Use + * `haltStrategy` to change the termination behavior. + * + * **Example** (Merging stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const fast = Stream.make(1, 2, 3) + * const slow = Stream.fromEffect(Effect.delay(Effect.succeed(4), "50 millis")) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(Stream.merge(fast, slow)) + * result // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]) && isStream(args[1]), (self, that, options) => fromChannel(Channel.merge(toChannel(self), toChannel(that), options))))); +/** + * Merges this stream with a background effect, keeping the stream's elements. + * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * + * The effect runs concurrently, fails the stream if it fails, and is interrupted + * when the stream completes. + * + * **Example** (Merging with a background effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.mergeEffect(Effect.sync(() => events.push("side task"))), + * Stream.runCollect + * ) + * + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["side task"] + * ``` + * + * @category merging + * @since 4.0.0 + */ +const mergeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => self.channel.pipe(Channel.mergeEffect(effect), fromChannel)))); +/** + * Merges this stream and the specified stream together, tagging values from the + * left stream as `Result.succeed` and values from the right stream as `Result.fail`. + * + * **When to use** + * + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. + * + * **Example** (Merging streams into results) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const left = Stream.fromEffect(Effect.succeed("left")) + * const right = Stream.fromEffect(Effect.delay(Effect.succeed("right"), "10 millis")) + * + * const merged = left.pipe( + * Stream.mergeResult(right), + * Stream.map( + * Result.match({ + * onFailure: (value) => `right:${value}`, + * onSuccess: (value) => `left:${value}` + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(merged) + * result // => [ 'left:left', 'right:right' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 4.0.0 + */ +const mergeResult = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => merge(map(self, Result.succeed), map(that, Result.fail))))); +/** + * Merges two streams while emitting only the values from the left stream. + * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * + * The right stream still runs for its effects, and any failures from the right + * stream are propagated. The merged stream completes when the left stream + * completes, interrupting the right stream. + * + * **Example** (Merging streams while keeping left values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const values = yield* left.pipe(Stream.mergeLeft(right), Stream.runCollect) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const mergeLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => mergeEffect(left, runDrain(right))))); +/** + * Merges this stream and the specified stream together, emitting only the + * values from the right stream while the left stream runs for its effects. + * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * + * The merged stream ends when the right stream completes, interrupting the + * left stream. Failures from the left stream still fail the merged stream. + * + * **Example** (Merging streams while keeping right values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const left = Stream.make("left-1", "left-2").pipe( + * Stream.tap(() => Effect.sync(() => undefined)) + * ) + * const right = Stream.make(1, 2) + * + * const merged = Stream.mergeRight(left, right) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(merged) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const mergeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => mergeEffect(right, runDrain(left))))); +/** + * Merges a collection of streams, running up to the specified number concurrently. + * + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const streams = [ + * Stream.fromEffect(Effect.delay(Effect.succeed("A"), "20 millis")), + * Stream.fromEffect(Effect.delay(Effect.succeed("B"), "10 millis")) + * ] + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.mergeAll(streams, { concurrency: 2 }).pipe( + * Stream.runCollect + * ) + * values // => [ 'B', 'A' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 + */ +const mergeAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (streams, options) => flatten(fromIterable(streams), options)))); +/** + * Creates the cartesian product of two streams, running the `right` stream for + * each element in the `left` stream. + * + * **Details** + * + * See also `Stream.zip` for the more common point-wise variant. + * + * **Example** (Computing cartesian products) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const values = yield* Stream.runCollect(Stream.cross(left, right)) + * values // => [ [ 1, 'a' ], [ 1, 'b' ], [ 2, 'a' ], [ 2, 'b' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const cross = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => crossWith(left, right, (l, r) => [l, r])))); +/** + * Creates a cartesian product of elements from two streams using a function. + * + * **Details** + * + * The `right` stream is rerun for every element in the `left` stream. + * + * See also `Stream.zipWith` for the more common point-wise variant. + * + * **Example** (Combining cartesian products) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 2) + * const right = Stream.make("a", "b") + * const combined = Stream.crossWith(left, right, (n, s) => `${n}-${s}`) + * const result = yield* Stream.runCollect(combined) + * result // => [ '1-a', '1-b', '2-a', '2-b' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const crossWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => flatMap(left, l => map(right, r => f(l, r)))))); +/** + * Zips two streams point-wise with a combining function, ending when either stream ends. + * + * **Example** (Zipping streams with a function) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3, 4, 5, 6) + * const stream2 = Stream.make("a", "b", "c") + * + * const zipped = Stream.zipWith(stream1, stream2, (n, s) => `${n}-${s}`) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ '1-a', '2-b', '3-c' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => zipWithArray(left, right, zipArrays(f))))); +const zipArrays = f => (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const result = []; + for (let i = 0; i < minLength; i++) { + result.push(f(leftArr[i], rightArr[i])); + } + return [result, leftArr.slice(minLength), rightArr.slice(minLength)]; +}; +/** + * Zips two streams by applying a function to non-empty arrays of elements. + * + * **Details** + * + * The function returns output plus leftover arrays that carry into the next pull. + * + * **Example** (Zipping stream chunks) + * + * ```ts import.meta.vitest + * import { Array, Effect, Stream } from "effect" + * + * const left = Stream.fromArrays([1, 2, 3], [4, 5]) + * const right = Stream.fromArrays(["a", "b"], ["c", "d", "e"]) + * + * const zipped = Stream.zipWithArray(left, right, (leftChunk, rightChunk) => { + * const minLength = Math.min(leftChunk.length, rightChunk.length) + * const output = Array.makeBy(minLength, (i) => [leftChunk[i], rightChunk[i]] as const) + * + * return [output, leftChunk.slice(minLength), rightChunk.slice(minLength)] + * }) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ], [ 4, 'd' ], [ 5, 'e' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 4.0.0 + */ +const zipWithArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_, scope) { + const pullLeft = yield* Channel.toPullScoped(left.channel, scope); + const pullRight = yield* Channel.toPullScoped(right.channel, scope); + const pullBoth = Effect.gen(function* () { + const fiberLeft = yield* Effect.forkIn(pullLeft, scope); + const fiberRight = yield* Effect.forkIn(pullRight, scope); + return yield* Fiber.joinAll([fiberLeft, fiberRight]); + }); + let state = { + _tag: "PullBoth" + }; + const pull = Effect.gen(function* () { + const [left, right] = state._tag === "PullBoth" ? yield* pullBoth : state._tag === "PullLeft" ? [yield* pullLeft, state.rightArray] : [state.leftArray, yield* pullRight]; + const result = f(left, right); + if (Arr.isReadonlyArrayNonEmpty(result[1])) { + state = { + _tag: "PullRight", + leftArray: result[1] + }; + } else if (Arr.isReadonlyArrayNonEmpty(result[2])) { + state = { + _tag: "PullLeft", + rightArray: result[2] + }; + } else { + state = { + _tag: "PullBoth" + }; + } + return result[0]; + }); + return pull; +})))))); +/** + * Zips this stream with another point-wise and emits tuples of elements from + * both streams. The new stream ends when either stream ends. + * + * **Example** (Zipping streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3) + * const stream2 = Stream.make("a", "b", "c") + * + * const zipped = Stream.zip(stream1, stream2) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(zipped) + * result // => [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, (a, a2) => [a, a2])))); +/** + * Zips this stream with another point-wise and keeps only the values from + * the left stream. + * + * **Details** + * + * The resulting stream ends when either side ends. + * + * **Example** (Zipping streams while keeping left values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2, 3, 4) + * const stream2 = Stream.make("a", "b") + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipLeft(stream1, stream2).pipe(Stream.runCollect) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const output = leftArr.slice(0, minLength); + const leftoverLeft = leftArr.slice(minLength); + const leftoverRight = rightArr.slice(minLength); + return [output, leftoverLeft, leftoverRight]; +})))); +/** + * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. + * + * **Example** (Zipping streams while keeping right values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream1 = Stream.make(1, 2) + * const stream2 = Stream.make("a", "b", "c", "d") + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipRight(stream1, stream2).pipe(Stream.runCollect) + * result // => [ 'a', 'b' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWithArray(left, right, (leftArr, rightArr) => { + const minLength = Math.min(leftArr.length, rightArr.length); + const output = rightArr.slice(0, minLength); + const leftoverLeft = leftArr.slice(minLength); + const leftoverRight = rightArr.slice(minLength); + return [output, leftoverLeft, leftoverRight]; +})))); +/** + * Zips this stream with another point-wise and emits tuples of elements from + * both streams, flattening the left tuple. + * + * **Details** + * + * The new stream will end when one of the sides ends. + * + * **Example** (Zipping and flattening tuples) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream1 = Stream.make( + * [1, "a"] as const, + * [2, "b"] as const, + * [3, "c"] as const + * ) + * const stream2 = Stream.make("x", "y", "z") + * const result = yield* Stream.zipFlatten(stream1, stream2).pipe(Stream.runCollect) + * + * result // => [ [ 1, 'a', 'x' ], [ 2, 'b', 'y' ], [ 3, 'c', 'z' ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipFlatten = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, (a, a2) => [...a, a2])))); +/** + * Zips this stream together with the index of elements. + * + * **Example** (Zipping elements with indices) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const indexed = yield* Stream.make("a", "b", "c", "d").pipe( + * Stream.zipWithIndex, + * Stream.runCollect + * ) + * indexed // => [ [ 'a', 0 ], [ 'b', 1 ], [ 'c', 2 ], [ 'd', 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithIndex = self => map(self, (a, i) => [a, i]); +/** + * Zips each element with the next element, pairing the final element with + * `Option.none()`. + * + * **Example** (Zipping elements with next values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4)) + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [[1, Option.some(2)], [2, Option.some(3)], [3, Option.some(4)], [4, Option.none()]] + * })) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithNext = self => mapAccumArray(self, Option.none, (acc, arr) => { + let i = 0; + if (acc._tag === "None") { + i = 1; + acc = Option.some(arr[0]); + } + const pairs = Arr.empty(); + for (; i < arr.length; i++) { + const value = acc.value; + acc = Option.some(arr[i]); + pairs.push([value, acc]); + } + return [acc, pairs]; +}, { + onHalt(state) { + return state._tag === "Some" ? [[state.value, Option.none()]] : []; + } +}); +/** + * Zips each element with its previous element, starting with `None`. + * + * **Example** (Zipping elements with previous values) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4)) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [[Option.none(), 1], [Option.some(1), 2], [Option.some(2), 3], [Option.some(3), 4]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithPrevious = self => mapAccumArray(self, Option.none, (acc, arr) => { + const pairs = Arr.empty(); + for (let i = 0; i < arr.length; i++) { + const value = arr[i]; + pairs.push([acc, value]); + acc = Option.some(arr[i]); + } + return [acc, pairs]; +}); +/** + * Zips each element with its previous and next values. + * + * **Example** (Zipping elements with neighbors) + * + * ```ts import.meta.vitest + * import { Console, Effect, Option, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.zipWithPreviousAndNext, + * Stream.runCollect + * ) + * values // => [[Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWithPreviousAndNext = self => mapAccumArray(self, () => ({ + prev: Option.none(), + current: Option.none() +}), (acc, arr) => { + let i = 0; + let current; + if (acc.current._tag === "None") { + i = 1; + current = arr[0]; + acc.current = Option.some(current); + } else { + current = acc.current.value; + } + const pairs = Arr.empty(); + for (; i < arr.length; i++) { + const element = arr[i]; + acc.current = Option.some(element); + pairs.push([acc.prev, current, acc.current]); + acc.prev = Option.some(current); + current = element; + } + return [acc, pairs]; +}, { + onHalt(acc) { + return acc.current._tag === "Some" ? [[acc.prev, acc.current.value, Option.none()]] : []; + } +}); +/** + * Zips multiple streams so that when a value is emitted by any stream, it is + * combined with the latest values from the other streams to produce a result. + * + * **When to use** + * + * Use when each stream should contribute its latest value after all streams have + * emitted at least once. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values from many streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.zipLatestAll( + * Stream.make(1, 2, 3).pipe(Stream.rechunk(1)), + * Stream.make("a", "b", "c").pipe(Stream.rechunk(1)), + * Stream.make(true, false, true).pipe(Stream.rechunk(1)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [[1, "a", true], [2, "a", true], [2, "b", true], [2, "b", false], [3, "b", false], [3, "c", false], [3, "c", true]] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 3.3.0 + */ +const zipLatestAll = (...streams) => fromChannel(Channel.suspend(() => { + const latest = []; + const emitted = new Set(); + const readyLatch = Latch.makeUnsafe(); + return Channel.mergeAll(Channel.fromArray(streams.map((s, i) => s.channel.pipe(Channel.flattenArray, Channel.mapEffect(a => { + latest[i] = a; + if (!emitted.has(i)) { + emitted.add(i); + if (emitted.size < streams.length) { + return readyLatch.await; + } + return Effect.as(readyLatch.open, Arr.of(latest.slice())); + } + return Effect.succeed(Arr.of(latest.slice())); + }), Channel.filter(isNotUndefined)))), { + concurrency: "unbounded", + bufferSize: 0 + }); +})); +/** + * Combines two streams by emitting each new element with the latest value from the other stream. + * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.zipLatest( + * Stream.make(1), + * Stream.make("a") + * ).pipe(Stream.runCollect) + * + * result // => [ [ 1, 'a' ] ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLatest = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipLatestAll(left, right)))); +/** + * Combines the latest values from both streams whenever either emits, using + * the provided function. + * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * + * Note: tracking the latest value is done on a per-array basis. That means + * that emitted elements that are not the last value in arrays will never be + * used for zipping. + * + * **Example** (Zipping latest values with a function) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.rechunk(1), + * Stream.zipLatestWith( + * Stream.make(10, 20).pipe(Stream.rechunk(1)), + * (n, m) => n + m + * ), + * Stream.runCollect + * ) + * + * result // => [ 11, 12, 22, 23 ] + * })) + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipLatestWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => map(zipLatestAll(left, right), ([a, a2]) => f(a, a2))))); +/** + * Runs all streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the rest. + * + * **Details** + * + * Failures or completion from losing streams before a winner is chosen are + * ignored unless every stream fails or completes before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing multiple streams) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.raceAll( + * Stream.empty, + * Stream.make(0, 1, 2) + * ).pipe(Stream.runCollect) + * result // => [ 0, 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category racing + * @since 3.5.0 + */ +const raceAll = (...streams) => fromChannel(Channel.fromTransform((_, scope) => Effect.sync(() => { + let winner; + const race = Effect.raceAll(streams.map(stream => { + const childScope = Scope.forkUnsafe(scope); + return Channel.toPullScoped(stream.channel, childScope).pipe(Effect.flatMap(pull => Effect.zip(Effect.succeed(pull), pull)), Effect.onExit(exit => { + if (exit._tag === "Success") { + if (winner) { + return Scope.close(childScope, exit); + } + winner = exit.value[0]; + return Effect.void; + } + return Scope.close(childScope, exit); + }), Effect.map(([, chunk]) => chunk)); + })); + return Effect.suspend(() => winner ?? race); +}))); +/** + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.race( + * Stream.empty, + * Stream.make(0, 1, 2) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 0, 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category racing + * @since 3.7.0 + */ +const race = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => raceAll(left, right)))); +/** + * Filters a stream to the elements that satisfy a predicate. + * + * **Example** (Filtering stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4).pipe( + * Stream.filter((n) => n % 2 === 0) + * ) + * const values = yield* Stream.runCollect(stream) + * values // => [ 2, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromChannel(Channel.filterArray(toChannel(self), predicate))))); +/** + * Filters and maps stream elements in one pass using a `Filter`. + * + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromChannel(Channel.filterMapArray(toChannel(self), filter))))); +/** + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.filterEffect((n) => Effect.succeed(n > 2))) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => fromChannel(Channel.filterArrayEffect(toChannel(self), predicate))))); +/** + * Filters and maps elements in one pass effectfully using a `FilterEffect`. + * + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 + */ +const filterMapEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => fromChannel(Channel.filterMapArrayEffect(toChannel(self), filter))))); +/** + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** + * + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. + * + * **Example** (Partitioning a stream into queues) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const [passes, fails] = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.partitionQueue((n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) + * ) + * + * const passValues = yield* Stream.fromQueue(passes).pipe(Stream.runCollect) + * const failValues = yield* Stream.fromQueue(fails).pipe(Stream.runCollect) + * + * passValues // => [ 2, 4 ] + * failValues // => [ 1, 3 ] + * }) + * + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const partitionQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), /*#__PURE__*/Effect.fnUntraced(function* (self, filter, options) { + const scope = yield* Effect.scope; + const pull = yield* Channel.toPullScoped(self.channel, scope); + const capacity = options?.capacity === "unbounded" ? undefined : options?.capacity ?? DefaultChunkSize; + const passes = yield* Queue.make({ + capacity + }); + const fails = yield* Queue.make({ + capacity + }); + yield* Effect.gen(function* () { + while (true) { + const chunk = yield* pull; + const excluded = []; + const satisfying = []; + for (let i = 0; i < chunk.length; i++) { + const result = filter(chunk[i]); + if (Result.isFailure(result)) { + excluded.push(result.failure); + } else { + satisfying.push(result.success); + } + } + let passFiber = undefined; + if (satisfying.length > 0) { + const leftover = Queue.offerAllUnsafe(passes, satisfying); + if (leftover.length > 0) { + passFiber = yield* Effect.forkChild(Queue.offerAll(passes, leftover)); + } + } + if (excluded.length > 0) { + const leftover = Queue.offerAllUnsafe(fails, excluded); + if (leftover.length > 0) { + yield* Queue.offerAll(fails, leftover); + } + } + if (passFiber) yield* Fiber.join(passFiber); + } + }).pipe(Effect.onError(cause => { + Queue.failCauseUnsafe(passes, cause); + Queue.failCauseUnsafe(fails, cause); + return Effect.void; + }), Effect.forkIn(scope)); + return [passes, fails]; +})))); +/** + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering + * @since 4.0.0 + */ +const partitionEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(mapEffect(self, a => filter(a), options), result => result, options), ([passes, fails]) => [fromQueue(passes), fromQueue(fails)])))); +/** + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) + * + * ```ts import.meta.vitest + * import { Effect, Result, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const [excluded, satisfying] = yield* Stream.partition( + * Stream.make(1, 2, 3, 4), + * (n) => n % 2 === 0 ? Result.succeed(n) : Result.fail(n) + * ) + * const left = yield* Stream.runCollect(excluded) + * const right = yield* Stream.runCollect(satisfying) + * left // => [ 1, 3 ] + * right // => [ 2, 4 ] + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, options) => Effect.map(partitionQueue(self, filter, { + capacity: options?.bufferSize ?? 16 +}), ([passes, fails]) => [fromQueue(fails), fromQueue(passes)])))); +/** + * Returns the specified stream if the given condition is satisfied, otherwise + * returns an empty stream. + * + * **Example** (Conditionally keeping a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect( + * Stream.when(Stream.make(1, 2, 3), Effect.succeed(false)) + * ) + * result // => [] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const when = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, test) => test.pipe(Effect.map(pass => pass ? self : empty), unwrap)))); +/** + * Runs a sink to peel off enough elements to produce a value and returns that + * value with the remaining stream in a scope. + * + * **Details** + * + * The returned stream is only valid within the scope. + * + * **Example** (Peeling a stream with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const stream = Stream.fromArrays([1, 2, 3], [4, 5, 6]) + * const sink = Sink.take(3) + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [peeled, rest] = yield* Stream.peel(stream, sink) + * const remaining = yield* Stream.runCollect(rest) + * const result = [peeled, remaining] // => [[1, 2, 3], [4, 5, 6]] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const peel = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, sink) { + let cause = undefined; + const originalPull = yield* Channel.toPull(self.channel); + const pull = Effect.catchCause(originalPull, cause_ => { + cause = cause_; + return Effect.failCause(cause_); + }); + let stream = fromPull(Effect.succeed(pull)); + const leftover = yield* run(stream, sink); + if (cause) return [leftover, empty]; + stream = fromPull(Effect.succeed(originalPull)); + return [leftover, stream]; +})))); +/** + * Buffers up to `capacity` elements so a faster producer can progress + * independently of a slower consumer. + * + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.buffer({ capacity: 1 }), + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category buffering + * @since 2.0.0 + */ +const buffer = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromChannel(Channel.bufferArray(self.channel, options))))); +/** + * Allows a faster producer to progress independently of a slower consumer by + * buffering up to `capacity` chunks in a queue. + * + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. + * + * **Example** (Buffering stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArrays([1, 2], [3, 4]).pipe( + * Stream.bufferArray({ capacity: 2 }), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category buffering + * @since 4.0.0 + */ +const bufferArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => fromChannel(Channel.buffer(self.channel, options))))); +/** + * Switches over to the stream produced by the provided function in case this + * one fails. Allows recovery from all causes of failure, including + * interruption if the stream is uninterruptible. + * + * **Example** (Catching stream causes) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("Oops!")), + * Stream.concat(Stream.make(3, 4)) + * ) + * + * const recovered = stream.pipe( + * Stream.catchCause(() => Stream.make(999)) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(recovered) + * values // => [ 1, 2, 999 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.channel.pipe(Channel.catchCause(cause => f(cause).channel), fromChannel)))); +/** + * Runs an effect when the stream fails without changing its values or error, + * unless the tap effect itself fails. + * + * **Example** (Tapping stream causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const observations: Array = [] + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapCause((cause) => Effect.sync(() => observations.push(Cause.isReason(cause)))), + * Stream.catch(() => Stream.succeed(0)) + * ) + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.runCollect(stream) + * result // => [1, 2, 0] + * }) + * + * await Effect.runPromise(program) + * observations // => [false] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.channel.pipe(Channel.tapCause(f), fromChannel)))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.catch(self.channel, error => f(error).channel))))); + +/** + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const errors: Array = [] + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.tapError((error) => Effect.sync(() => errors.push(error))), + * Stream.catch(() => Stream.make(999)) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 999] + * }) + * + * await Effect.runPromise(program) + * errors // => ["boom"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => self.channel.pipe(_Channel_js__rspack_import_1/* .tapError */.sF(f), fromChannel)); +/** + * Recovers from errors that match a predicate by switching to a recovery stream. + * + * **Details** + * + * When a failure matches the filter, the stream switches to the recovery + * stream. Non-matching failures propagate downstream, so the error type is + * preserved unless the filter narrows it. + * + * **Example** (Catching matching failures) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.concat(Stream.fail(42)), + * Stream.catchIf( + * (error): error is 42 => error === 42, + * () => Stream.make(999) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 999 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, predicate, f, orElse) => fromChannel(Channel.catchIf(toChannel(self), predicate, e => f(e).channel, orElse && (e => orElse(e).channel)))))); +/** + * Recovers from errors that match a `Filter` by switching to a recovery + * stream. + * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, filter, f, orElse) => fromChannel(Channel.catchFilter(toChannel(self), filter, e => f(e).channel, orElse && (e => orElse(e).channel)))))); +/** + * Recovers from failures whose `_tag` matches the provided value by switching to + * the stream returned by `f`. + * + * **When to use** + * + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. + * + * **Example** (Catching tagged failures) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class HttpError extends Data.TaggedError("HttpError")<{ message: string }> {} + * + * const stream = Stream.fail(new HttpError({ message: "timeout" })) + * + * const recovered = Stream.catchTag(stream, "HttpError", (error) => + * Stream.make(`Recovered: ${error.message}`) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(recovered) + * values // => [ 'Recovered: timeout' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => hasProperty(e, "_tag") && k.includes(e._tag) : isTagged(k); + return catchIf(self, pred, f, orElse); +}))); +/** + * Switches to a recovery stream based on matching `_tag` handlers. + * + * **Example** (Catching tagged failures with handlers) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * class NotFound { + * readonly _tag = "NotFound" + * constructor(readonly resource: string) {} + * } + * + * class Unauthorized { + * readonly _tag = "Unauthorized" + * constructor(readonly user: string) {} + * } + * + * const stream = Stream.fail(new NotFound("profile")) + * + * const program = Effect.gen(function* () { + * const result = yield* stream.pipe( + * Stream.catchTags({ + * NotFound: () => Stream.succeed("fallback"), + * Unauthorized: () => Stream.succeed("login") + * }), + * Stream.runCollect + * ) + * result // => [ 'fallback' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTags = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, cases, orElse) => { + let keys; + return catchFilter(self, e => { + keys ??= Object.keys(cases); + return hasProperty(e, "_tag") && isString(e["_tag"]) && keys.includes(e["_tag"]) ? Result.succeed(e) : Result.fail(e); + }, e => cases[e["_tag"]](e), orElse); +}))); +/** + * Catches a specific reason within a tagged error. + * + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const stream = Stream.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* stream.pipe( + * Stream.catchReason("AiError", "RateLimitError", (reason) => + * Stream.succeed(`retry: ${reason.retryAfter}`) + * ), + * Stream.runCollect + * ) + * values // => [ 'retry: 60' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, errorTag, reasonTag, f, orElse) => fromChannel(Channel.catchReason(toChannel(self), errorTag, reasonTag, (reason, error) => f(reason, error).channel, orElse && ((reason, error) => orElse(reason, error).channel)))))); +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * **Example** (Catching tagged error reasons) + * + * ```ts import.meta.vitest + * import { Data, Effect, Stream } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const stream = Stream.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 60 }) }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* stream.pipe( + * Stream.catchReasons("AiError", { + * RateLimitError: (reason) => Stream.succeed(`retry: ${reason.retryAfter}`), + * QuotaExceededError: (reason) => Stream.succeed(`quota: ${reason.limit}`) + * }), + * Stream.runCollect + * ) + * values // => [ 'retry: 60' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, errorTag, cases, orElse) => { + const handlers = Object.create(null); + for (const key of Object.keys(cases)) { + const handler = cases[key]; + handlers[key] = (reason, error) => handler(reason, error).channel; + } + const orElseHandler = orElse && ((reason, error) => orElse(reason, error).channel); + return fromChannel(Channel.catchReasons(self.channel, errorTag, handlers, orElseHandler)); +}))); +/** + * Transforms the errors emitted by this stream using `f`. + * + * **Example** (Mapping stream errors) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fail("bad").pipe( + * Stream.mapError((error) => `mapped: ${error}`), + * Stream.catch((error) => Stream.make(`recovered from ${error}`)), + * Stream.runCollect + * ) + * result // => [ 'recovered from mapped: bad' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.mapError(self.channel, f))))); +/** + * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. + * Non-matching causes are re-emitted as failures. + * + * **Example** (Catching matching causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const failingStream = Stream.fail("NetworkError") + * const recovered = Stream.catchCauseIf( + * failingStream, + * (cause) => Cause.hasFails(cause), + * (cause) => Stream.make(`Recovered: ${Cause.squash(cause)}`) + * ) + * + * const output = yield* Stream.runCollect(recovered) + * output // => [ 'Recovered: NetworkError' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, f) => fromChannel(Channel.catchCauseIf(self.channel, predicate, cause => f(cause).channel))))); +/** + * Recovers from stream failures by filtering the `Cause` and switching to a + * recovery stream. + * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, filter, f) => fromChannel(Channel.catchCauseFilter(self.channel, filter, (failure, cause) => f(failure, cause).channel))))); +/** + * Switches to a fallback stream if this stream is empty. + * + * **Example** (Switching on empty streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.empty.pipe( + * Stream.orElseIfEmpty(() => Stream.make(1, 2)), + * Stream.runCollect + * ) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseIfEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, orElse) => fromChannel(Channel.orElseIfEmpty(self.channel, _ => toChannel(orElse())))))); +/** + * Returns a stream that emits a fallback value when this stream fails. + * + * **Example** (Recovering with a fallback value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.fail("NetworkError").pipe( + * Stream.orElseSucceed((error) => `Recovered: ${error}`) + * ) + * + * const values = yield* Stream.runCollect(stream) + * values // => [ 'Recovered: NetworkError' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSucceed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => catch_(self, e => succeed(f(e)))))); +/** + * Turns typed failures into defects, making the stream infallible. + * + * **Example** (Turning failures into defects) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.orDie, + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => fromChannel(Channel.orDie(self.channel)); +/** + * Ignores failures and ends the stream on error. + * + * **When to use** + * + * Use when you want a failing stream to end gracefully rather than propagate + * the error. + * + * **Details** + * + * The `log` option controls whether the failure is logged before the stream + * terminates. + * + * **Example** (Ignoring stream failures) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.ignore, + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * **Example** (Configuring ignore logging) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.fail("boom").pipe( + * Stream.ignore({ log: false }), + * Stream.runCollect + * ) + * values // => [] + * })) + * + * ``` + * + * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures + * + * @category error handling + * @since 4.0.0 + */ +const ignore = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignore(self.channel, options))))); +/** + * Ignores the stream's failure cause, including defects, and ends the stream. + * + * **When to use** + * + * Use when you need to silently suppress a stream's entire failure cause, + * including both typed errors and defects, rather than propagate it downstream. + * + * **Example** (Ignoring stream failure causes) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.die("boom")), + * Stream.ignoreCause({ log: false }), + * Stream.runCollect + * ) + * values // => [1, 2] + * })) + * + * ``` + * + * @see {@link ignore} to ignore only typed failures without suppressing defects + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => fromChannel(Channel.ignoreCause(self.channel, options))))); +/** + * Retries the stream according to the given schedule when it fails. + * + * **Details** + * + * This retries the entire stream, so will re-execute all of the stream's + * acquire operations. + * + * The schedule is reset as soon as the first element passes through the + * stream again. + * + * **Example** (Retrying stream failures) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.retry(Schedule.recurs(1)), + * Stream.take(2), + * Stream.runCollect + * ) + * + * values // => [ 1, 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const retry = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, policy) => fromChannel(Channel.retry(self.channel, policy))))); +const retryWithoutReset = (self, schedule) => unwrap(Effect.map(Schedule.toStepWithMetadata(schedule), step => { + let meta = Schedule.CurrentMetadata.defaultValue(); + const loop = () => catch_(provideServiceEffect(self, Schedule.CurrentMetadata, Effect.sync(() => meta)), error => unwrap(Pull.catchDone(Effect.map(step(error), meta_ => { + meta = meta_; + return unwrap(Effect.as(Effect.yieldNow, loop())); + }), () => Effect.succeed(fail(error))))); + return loop(); +})); +/** + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources + * until it succeeds or the plan is exhausted. + * + * **Details** + * + * By default, a failing step can fallback even after emitting elements; set + * `preventFallbackOnPartialStream` to fail instead of mixing partial output with + * a later fallback. + * + * Attempts can be observed from outside the stream by passing + * `options.onEvent`, which receives an `ExecutionPlan.Event` before each + * attempt and after it settles; see `Effect.withExecutionPlan` for the handler + * semantics. When a downstream consumer stops pulling early (for example + * `Stream.take` outside the plan), the truncated attempt reports + * `AttemptSuccess`: the consumer stopped, not the source. + * + * **Example** (Applying an execution plan) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer, Stream } from "effect" + * + * class Service extends Context.Service()("Service", { + * make: Effect.succeed({ + * stream: Stream.fail("A") as Stream.Stream + * }) + * }) { + * static Bad = Layer.succeed(Service, Service.of({ stream: Stream.fail("A") })) + * static Good = Layer.succeed(Service, Service.of({ stream: Stream.make(1, 2, 3) })) + * } + * + * const plan = ExecutionPlan.make( + * { provide: Service.Bad }, + * { provide: Service.Good } + * ) + * + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) + * + * const program = Effect.gen(function*() { + * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) + * items // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category error handling + * @since 3.16.0 + */ +const withExecutionPlan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, policy, options) => suspend(() => { + const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false; + let i = 0; + let meta = { + attempt: 0, + stepIndex: 0 + }; + const provideMeta = provideServiceEffect(ExecutionPlan.CurrentMetadata, Effect.sync(() => { + meta = { + attempt: meta.attempt + 1, + stepIndex: i + }; + return meta; + })); + const emitter = options?.onEvent === undefined ? undefined : internalExecutionPlan.makeEventEmitter(options.onEvent, () => meta); + let attemptState; + const instrument = emitter === undefined ? identity : attempt => onExit(onStart(attempt, Effect.map(emitter.begin, state => { + attemptState = state; + })), exit => Effect.suspend(() => { + if (attemptState === undefined) return Effect.void; + const state = attemptState; + attemptState = undefined; + return emitter.end(state, exit); + })); + let lastError = Option.none(); + const loop = suspend(() => { + const step = policy.steps[i]; + if (!step) { + return fail(Option.getOrThrow(lastError)); + } + let nextStream = provideMeta(instrument(provide(self, step.provide))); + let receivedElements = false; + if (Option.isSome(lastError)) { + const error = lastError.value; + let attempted = false; + const wrapped = nextStream; + // ensure the schedule is applied at least once + nextStream = suspend(() => { + if (attempted) return wrapped; + attempted = true; + return fail(error); + }); + nextStream = retryWithoutReset(nextStream, internalExecutionPlan.scheduleFromStep(step, false)); + } else { + const schedule = internalExecutionPlan.scheduleFromStep(step, true); + nextStream = schedule ? retryWithoutReset(nextStream, schedule) : nextStream; + } + return catch_(preventFallbackOnPartialStream ? onFirst(nextStream, _ => { + receivedElements = true; + return Effect.void; + }) : nextStream, error => { + i++; + if (preventFallbackOnPartialStream && receivedElements) { + return fail(error); + } + lastError = Option.some(error); + return loop; + }); + }); + return loop; +})))); +/** + * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. + * + * **Example** (Taking values from the left) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.take(3), + * Stream.runCollect + * ) + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => n < 1 ? empty : takeUntil(self, (_, i) => i === n - 1)))); +/** + * Emits byte chunks until the configured limit would be exceeded, then drops + * the crossing chunk and switches to a fallback stream. + * + * **Example** (Truncating at a byte limit) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make( + * new Uint8Array([1, 2]), + * new Uint8Array([3, 4, 5]) + * ).pipe( + * Stream.limitBytes(4, () => Stream.empty), + * Stream.runCollect, + * Effect.map((chunks) => chunks.map((chunk) => [...chunk])) + * ) + * + * await Effect.runPromise(program) // => [[1, 2]] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const limitBytes = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, bytes, onLimitReached) => suspend(() => { + const limit = BigInt(bytes); + let size = BigInt(0); + let limitReached = false; + return concat(takeWhile(self, chunk => { + const nextSize = size + BigInt(chunk.length); + if (nextSize > limit) { + limitReached = true; + return false; + } + size = nextSize; + return true; + }), suspend(() => limitReached ? onLimitReached() : empty)); +})))); +/** + * Keeps the last `n` elements from this stream. + * + * **Example** (Taking elements from the right) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.range(1, 6).pipe( + * Stream.takeRight(3), + * Stream.runCollect + * ) + * values // => [ 4, 5, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => mapAccumArray(self, MutableList.make, (list, arr) => { + MutableList.appendAll(list, arr); + if (list.length > n) { + MutableList.takeNVoid(list, list.length - n); + } + return [list, emptyArr]; +}, { + onHalt(list) { + return MutableList.takeAll(list); + } +})))); +/** + * Takes elements until the predicate matches. + * + * **Details** + * + * When `excludeLast` is `true`, the matching element is dropped. + * + * **Example** (Taking until a predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(1, 5) + * + * const program = Effect.gen(function*() { + * const inclusive = yield* stream.pipe( + * Stream.takeUntil((n) => n % 3 === 0), + * Stream.runCollect + * ) + * inclusive // => [ 1, 2, 3 ] + * + * const exclusive = yield* stream.pipe( + * Stream.takeUntil((n) => n % 3 === 0, { excludeLast: true }), + * Stream.runCollect + * ) + * exclusive // => [ 1, 2 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeUntil = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => _Effect_js__rspack_import_3/* .sync */.OH5(() => { + let i = 0; + let done = false; + const pump = _Effect_js__rspack_import_3/* .flatMap */.qIB(_Effect_js__rspack_import_3/* .suspend */.DYE(() => done ? _Cause_js__rspack_import_5/* .done */.Vw() : pull), chunk => { + const index = chunk.findIndex(a => predicate(a, i++)); + if (index >= 0) { + done = true; + const arr = chunk.slice(0, options?.excludeLast ? index : index + 1); + return _Array_js__rspack_import_4/* .isReadonlyArrayNonEmpty */.ET(arr) ? _Effect_js__rspack_import_3/* .succeed */.PyW(arr) : _Cause_js__rspack_import_5/* .done */.Vw(); + } + return _Effect_js__rspack_import_3/* .succeed */.PyW(chunk); + }); + return pump; +}))); +/** + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.takeUntilEffect((n) => Effect.succeed(n % 3 === 0)), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeUntilEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, predicate, options) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let i = 0; + let done = false; + return Effect.gen(function* () { + if (done) return yield* Cause.done(); + const chunk = yield* pull; + for (let j = 0; j < chunk.length; j++) { + if (yield* predicate(chunk[j], i++)) { + done = true; + const arr = chunk.slice(0, options?.excludeLast ? j : j + 1); + return Arr.isReadonlyArrayNonEmpty(arr) ? arr : yield* Cause.done(); + } + } + return chunk; + }); +}))))); +/** + * Takes the longest initial prefix of elements that satisfy the predicate. + * + * **Example** (Taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(1, 5).pipe( + * Stream.takeWhile((n) => n % 3 !== 0) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let i = 0; + let done = false; + const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => { + const out = []; + for (let j = 0; j < chunk.length; j++) { + if (!predicate(chunk[j], i++)) { + done = true; + break; + } + out.push(chunk[j]); + } + return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump; + }); + return pump; +}))))); +/** + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. + * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** + * + * The stream stops at the first `Result.fail` returned by the filter. + * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements + * + * @category filtering + * @since 4.0.0 + */ +const takeWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let done = false; + const pump = Effect.flatMap(Effect.suspend(() => done ? Cause.done() : pull), chunk => { + const out = []; + for (let j = 0; j < chunk.length; j++) { + const result = filter(chunk[j]); + if (Result.isFailure(result)) { + done = true; + break; + } + out.push(result.success); + } + return Arr.isReadonlyArrayNonEmpty(out) ? Effect.succeed(out) : done ? Cause.done() : pump; + }); + return pump; +}))))); +/** + * Takes elements from the stream while the effectful predicate is `true`. + * + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.takeWhileEffect((n) => Effect.succeed(n % 3 !== 0)), + * Stream.runCollect + * ) + * result // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const takeWhileEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => takeUntilEffect(self, (a, n) => Effect.map(predicate(a, n), b => !b), { + excludeLast: true +})))); +/** + * Drops the first `n` elements from this stream. + * + * **Example** (Dropping values from the left) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const result = Stream.drop(stream, 2) + * + * const program = Effect.gen(function*() { + * const items = yield* Stream.runCollect(result) + * items // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropped = 0; + const pump = pull.pipe(Effect.flatMap(chunk => { + if (dropped >= n) return Effect.succeed(chunk); + dropped += chunk.length; + if (dropped <= n) return pump; + return Effect.succeed(chunk.slice(n - dropped)); + })); + return pump; +}))))); +/** + * Drops elements until the specified predicate evaluates to `true`, then drops + * that matching element. + * + * **Example** (Dropping until a predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const result = Stream.dropUntil(stream, (n) => n >= 3) + * + * await Effect.runPromise(Effect.gen(function*() { + * const output = yield* Stream.runCollect(result) + * output // => [ 4, 5 ] + * })) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropUntil = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => drop(dropWhile(self, (a, i) => !predicate(a, i)), 1)))); +/** + * Drops all elements of the stream until the specified effectful predicate + * evaluates to `true`. + * + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(1, 5).pipe( + * Stream.dropUntilEffect((n) => Effect.succeed(n % 3 === 0)), + * Stream.runCollect + * ) + * result // => [ 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropUntilEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => drop(dropWhileEffect(self, (a, i) => Effect.map(predicate(a, i), b => !b)), 1)))); +/** + * Drops elements from the stream while the specified predicate evaluates to `true`. + * + * **Example** (Dropping while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropWhile((n) => n < 3), + * Stream.runCollect + * ) + * values // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + let index = 0; + const filtered = Effect.flatMap(pull, arr => { + const found = arr.findIndex(a => !predicate(a, index++)); + if (found === -1) return filtered; + dropping = false; + return Effect.succeed(arr.slice(found)); + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops elements while the filter succeeds. + * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering + * @since 4.0.0 + */ +const dropWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, filter) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + const filtered = Effect.flatMap(pull, arr => { + const found = arr.findIndex(a => Result.isFailure(filter(a))); + if (found === -1) return filtered; + dropping = false; + return Effect.succeed(arr.slice(found)); + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops elements while the specified effectful predicate evaluates to `true`. + * + * **Example** (Effectfully dropping while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropWhileEffect((n) => Effect.succeed(n < 3)), + * Stream.runCollect + * ) + * result // => [ 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropWhileEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let dropping = true; + let index = 0; + const filtered = Effect.gen(function* () { + while (true) { + const arr = yield* pull; + for (let i = 0; i < arr.length; i++) { + const drop = yield* predicate(arr[i], index++); + if (drop) continue; + dropping = false; + return arr.slice(i); + } + } + }); + return Effect.suspend(() => dropping ? filtered : pull); +}))))); +/** + * Drops the last specified number of elements from this stream. + * + * **Details** + * + * Keeps the last `n` elements in memory to drop them on completion. + * + * **Example** (Dropping values from the right) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.dropRight(2), + * Stream.runCollect + * ) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dropRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + if (n <= 0) return self; + return transformPull(self, (pull, _scope) => Effect.sync(() => { + const list = MutableList.make(); + const emit = Effect.flatMap(pull, arr => { + MutableList.appendAllUnsafe(list, arr); + const toTake = list.length - n; + const items = MutableList.takeN(list, toTake); + return Arr.isArrayNonEmpty(items) ? Effect.succeed(items) : emit; + }); + return emit; + })); +}))); +/** + * Exposes the underlying chunks as a stream of non-empty arrays. + * + * **Example** (Exposing stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const chunks = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.chunks, + * Stream.runCollect + * ) + * chunks // => [ [ 1, 2 ], [ 3, 4 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const chunks = self => self.channel.pipe(Channel.map(Arr.of), fromChannel); +/** + * Groups the stream into arrays of the specified size, preserving element order. + * + * **Details** + * + * The size is clamped to at least 1. + * + * **Example** (Rechunking stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.rechunk(2), + * Stream.chunks, + * Stream.runCollect + * ) + * result // => [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const rechunk = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, target) => { + target = Math.max(1, target); + return transformPull(self, (pull, _scope) => Effect.sync(() => { + let chunk = Arr.empty(); + let index = 0; + let current; + let done = false; + return Effect.suspend(function loop() { + if (done) return Cause.done();else if (current === undefined) { + return Effect.flatMap(pull, arr => { + if (chunk.length === 0 && arr.length === target) { + return Effect.succeed(arr); + } else if (chunk.length + arr.length < target) { + chunk.push(...arr); + return loop(); + } + current = arr; + return loop(); + }); + } + for (; index < current.length;) { + chunk.push(current[index++]); + if (chunk.length === target) { + const result = chunk; + chunk = []; + return Effect.succeed(result); + } + } + index = 0; + current = undefined; + return loop(); + }).pipe(Pull.catchDone(() => { + if (chunk.length === 0) return Cause.done(); + const result = chunk; + done = true; + chunk = []; + return Effect.succeed(result); + })); + })); +}))); +/** + * Emits a sliding window of `n` elements. + * + * **Example** (Emitting sliding windows) + * + * ```ts import.meta.vitest + * import { Effect, pipe, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* pipe( + * Stream.make(1, 2, 3, 4, 5), + * Stream.sliding(2), + * Stream.runCollect + * ) + * result // => [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ] + * })) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const sliding = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, chunkSize) => slidingSize(self, chunkSize, 1)))); +/** + * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. + * + * **Example** (Emitting sliding windows with a step size) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const chunks = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.slidingSize(3, 2), + * Stream.runCollect + * ) + * chunks // => [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const slidingSize = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, chunkSize, stepSize) => transformPull(self, (upstream, _scope) => Effect.sync(() => { + let cause = null; + const list = MutableList.make(); + let emitted = false; + let skip = 0; + const pull = Effect.matchCauseEffect(upstream, { + onSuccess(arr) { + MutableList.appendAllUnsafe(list, arr); + if (skip > 0) { + const length = list.length; + MutableList.takeNVoid(list, skip); + skip = Math.max(0, skip - length); + } + if (list.length < chunkSize) return pull; + emitted = true; + const chunks = []; + while (list.length >= chunkSize) { + if (chunkSize === stepSize) { + chunks.push(MutableList.takeN(list, chunkSize)); + } else { + chunks.push(MutableList.toArrayN(list, chunkSize)); + if (chunkSize === 1 && stepSize <= 0) { + MutableList.take(list); + } else { + const length = list.length; + MutableList.takeNVoid(list, stepSize); + skip = Math.max(0, stepSize - length); + } + } + } + return Effect.succeed(chunks); + }, + onFailure(cause_) { + if (emitted) MutableList.takeNVoid(list, chunkSize - stepSize); + if (list.length === 0) return Effect.failCause(cause_); + cause = cause_; + return Effect.succeed(Arr.of(MutableList.takeAll(list))); + } + }); + return Effect.suspend(() => cause ? Effect.failCause(cause) : pull); +}))))); +/** + * Splits the stream into non-empty groups whenever the predicate matches. + * + * **Details** + * + * Matching elements act as delimiters and are not included in the output. + * + * **Example** (Splitting on matching values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.range(0, 9).pipe( + * Stream.split((n) => n % 4 === 0), + * Stream.runCollect + * ) + * result // => [ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 9 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const split = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => mapAccumArray(self, Arr.empty, (acc, arr) => { + const out = Arr.empty(); + for (let i = 0; i < arr.length; i++) { + if (predicate(arr[i])) { + if (Arr.isArrayNonEmpty(acc)) { + out.push(acc); + acc = []; + } + } else { + acc.push(arr[i]); + } + } + return [acc, out]; +}, { + onHalt(arr) { + return Arr.isArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +})))); +/** + * Combines elements from this stream and the specified stream by repeatedly + * applying a stateful function that can pull from either side. + * + * **Details** + * + * Where possible, prefer `Stream.combineArray` for a more efficient + * implementation. + * + * **Example** (Combining streams with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.combine( + * Stream.make("A", "B", "C"), + * Stream.make(1, 2, 3), + * () => true, + * (takeLeft, pullLeft, pullRight) => + * takeLeft + * ? Effect.map(pullLeft, (value) => [`L:${value}`, false] as const) + * : Effect.map(pullRight, (value) => [`R:${value}`, true] as const) + * ) + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.runCollect(stream) + * output // => [ 'L:A', 'R:1', 'L:B', 'R:2', 'L:C', 'R:3' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => Channel.combine(Channel.flattenArray(self.channel), Channel.flattenArray(that.channel), s, f).pipe(Channel.map(Arr.of), fromChannel)))); +/** + * Combines two streams chunk-by-chunk with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2).pipe( + * Stream.combineArray( + * Stream.make(10, 20), + * () => true, + * (useLeft, pullLeft, pullRight) => + * Effect.gen(function*() { + * const array = useLeft ? yield* pullLeft : yield* pullRight + * return [array, !useLeft] as const + * }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 10, 20 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const combineArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(4, (self, that, s, f) => fromChannel(Channel.combine(self.channel, that.channel, s, f))))); +/** + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const totals = yield* Stream.make(0, 1, 2, 3, 4, 5, 6).pipe( + * Stream.mapAccum(() => 0, (total, n) => { + * const next = total + n + * return [next, [next]] as const + * }), + * Stream.runCollect + * ) + * + * totals // => [0, 1, 3, 6, 10, 15, 21] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { + const acc = Arr.empty(); + for (let index = 0; index < arr.length; index++) { + const [newState, values] = f(state, arr[index]); + state = newState; + acc.push(...values); + } + return [state, Arr.isArrayNonEmpty(acc) ? Arr.of(acc) : emptyArr]; +}, options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined))))); +/** + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** + * + * The mapping function runs once per chunk and the state is threaded across chunks. + * + * **Example** (Statefully mapping stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const output = yield* Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.rechunk(2), + * Stream.mapAccumArray(() => 0, (sum: number, chunk) => { + * const next = chunk.reduce((acc, n) => acc + n, sum) + * return [next, [next]] + * }), + * Stream.runCollect + * ) + * output // => [ 3, 10, 21 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapAccumArray = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => fromChannel(Channel.mapAccum(self.channel, initial, (state, arr) => { + const [newState, values] = f(state, arr); + state = newState; + return [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]; +}, options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined))))); +const emptyArr = /*#__PURE__*/(/* unused pure expression or super */ null && (Arr.empty())); +/** + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.make(1, 1, 1).pipe( + * Stream.mapAccumEffect(() => 0, (total, n) => + * Effect.succeed([total + n, [total + n]]) + * ), + * Stream.runCollect + * ) + * + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapAccumEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.flattenArray, Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : Arr.empty()]), options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined), fromChannel)))); +/** + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const totals = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.rechunk(2), + * Stream.mapAccumArrayEffect(() => 0, (total, chunk) => + * Effect.gen(function*() { + * const next = chunk.reduce((sum, value) => sum + value, total) + * return [next, [next]] as const + * }) + * ), + * Stream.runCollect + * ) + * totals // => [ 3, 10 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapAccumArrayEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, initial, f, options) => self.channel.pipe(Channel.mapAccum(initial, (state, a) => Effect.map(f(state, a), ([state, values]) => [state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : emptyArr]), options?.onHalt ? { + onHalt(state) { + const arr = options.onHalt(state); + return Arr.isReadonlyArrayNonEmpty(arr) ? Arr.of(arr) : emptyArr; + } +} : undefined), fromChannel)))); +/** + * Accumulates state across the stream, emitting the initial state and each updated state. + * + * **Example** (Scanning stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.scan(0, (acc, n) => acc + n), + * Stream.runCollect + * ) + * values // => [ 0, 1, 3, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => suspend(() => { + let isFirst = true; + return fromChannel(Channel.mapAccum(self.channel, constant(initial), (state, arr) => { + const states = Arr.empty(); + if (isFirst) { + isFirst = false; + states.push(state); + } + for (let index = 0; index < arr.length; index++) { + state = f(state, arr[index]); + states.push(state); + } + return [state, Arr.of(states)]; + })); +})))); +/** + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const states = yield* Stream.make(1, 2, 3).pipe( + * Stream.scanEffect(0, (sum, n) => Effect.succeed(sum + n)), + * Stream.runCollect + * ) + * states // => [ 0, 1, 3, 6 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const scanEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => self.channel.pipe(Channel.flattenArray, Channel.scanEffect(initial, f), Channel.map(Arr.of), fromChannel)))); +/** + * Drops earlier elements within the debounce window and emits only the latest element after the pause. + * + * **Example** (Debouncing stream elements) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3).pipe(Stream.debounce(Duration.zero)) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 3 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const debounce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, duration) => transformPull(self, Effect.fnUntraced(function* (pull, scope) { + const clock = yield* Clock; + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + let lastArr; + let cause; + let emitAtMs = Infinity; + const pullLatch = Latch.makeUnsafe(); + const emitLatch = Latch.makeUnsafe(); + const endLatch = Latch.makeUnsafe(); + yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => { + emitLatch.openUnsafe(); + lastArr = arr; + emitAtMs = clock.currentTimeMillisUnsafe() + durationMs; + return Effect.void; + }), Effect.forever({ + disableYield: true + }), Effect.onError(cause_ => { + cause = cause_; + emitAtMs = clock.currentTimeMillisUnsafe(); + emitLatch.openUnsafe(); + endLatch.openUnsafe(); + return Effect.void; + }), Effect.forkIn(scope)); + const sleepLoop = Effect.suspend(function loop() { + const now = clock.currentTimeMillisUnsafe(); + const timeMs = emitAtMs < now ? durationMs : Math.min(durationMs, emitAtMs - now); + return Effect.flatMap(Effect.raceFirst(Effect.sleep(timeMs), endLatch.await), () => { + const now = clock.currentTimeMillisUnsafe(); + if (now < emitAtMs) { + return loop(); + } else if (lastArr) { + emitLatch.closeUnsafe(); + pullLatch.closeUnsafe(); + const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr))); + lastArr = undefined; + return eff; + } else if (cause) { + return Effect.failCause(cause); + } + return loop(); + }); + }); + return Effect.suspend(() => { + if (cause) { + if (lastArr) { + const eff = Effect.succeed(Arr.of(Arr.lastNonEmpty(lastArr))); + lastArr = undefined; + return eff; + } + return Effect.failCause(cause); + } + pullLatch.openUnsafe(); + return emitLatch.whenOpen(sleepLoop); + }); +}))))); +/** + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. + * + * If using the "enforce" strategy, arrays that do not meet the bandwidth + * constraints are dropped. If using the "shape" strategy, arrays are delayed + * until they can be emitted without exceeding the bandwidth constraints. + * + * Defaults to the "shape" strategy. + * + * **Example** (Throttling stream chunks effectfully) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(0, 5).pipe( + * Stream.rechunk(1), + * Stream.throttleEffect({ + * cost: (arr) => Effect.succeed(arr.length), + * units: 1, + * duration: 0, + * strategy: "shape" + * }) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ 0, 1, 2, 3, 4, 5 ] + * })) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const throttleEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const burst = options.burst ?? 0; + if (options.strategy === "enforce") { + return throttleEnforceEffect(self, options.cost, options.units, options.duration, burst); + } + return throttleShapeEffect(self, options.cost, options.units, options.duration, burst); +}))); +const throttleEnforceEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => { + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst; + let tokens = units; + let timestampMs = clock.currentTimeMillisUnsafe(); + return Effect.succeed(Effect.flatMap(pull, function loop(arr) { + return Effect.flatMap(cost(arr), weight => { + const currentMs = clock.currentTimeMillisUnsafe(); + const elapsed = currentMs - timestampMs; + const cycles = elapsed / durationMs; + const sum = tokens + cycles * units; + const available = sum < 0 ? max : Math.min(sum, max); + if (weight <= available) { + tokens = available - weight; + timestampMs = currentMs; + return Effect.succeed(arr); + } + // Drop the array and continue + return Effect.flatMap(pull, loop); + }); + })); +})); +const throttleShapeEffect = (self, cost, units, duration, burst) => transformPull(self, pull => Effect.clockWith(clock => { + const durationMs = Duration.toMillis(Duration.fromInputUnsafe(duration)); + const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst; + let tokens = units; + let timestampMs = clock.currentTimeMillisUnsafe(); + return Effect.succeed(Effect.flatMap(pull, arr => Effect.flatMap(cost(arr), weight => { + const currentMs = clock.currentTimeMillisUnsafe(); + const elapsed = currentMs - timestampMs; + const cycles = elapsed / durationMs; + const sum = tokens + cycles * units; + const available = sum < 0 ? max : Math.min(sum, max); + const remaining = available - weight; + if (remaining >= 0) { + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + } + // Calculate delay needed + const waitCycles = -remaining / units; + const delayMs = Math.max(0, waitCycles * durationMs); + if (delayMs > 0) { + return Effect.flatMap(Effect.sleep(delayMs), () => { + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + }); + } + tokens = remaining; + timestampMs = currentMs; + return Effect.succeed(arr); + }))); +})); +/** + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. + * + * If using the "enforce" strategy, arrays that do not meet the bandwidth + * constraints are dropped. If using the "shape" strategy, arrays are delayed + * until they can be emitted without exceeding the bandwidth constraints. + * + * Defaults to the "shape" strategy. + * + * **Example** (Throttling stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.range(0, 5).pipe( + * Stream.rechunk(1), + * Stream.throttle({ + * cost: (arr) => arr.length, + * units: 1, + * duration: 0, + * strategy: "shape" + * }) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 0, 1, 2, 3, 4, 5 ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category rate limiting + * @since 2.0.0 + */ +const throttle = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => throttleEffect(self, { + ...options, + cost: arr => Effect.succeed(options.cost(arr)) +})))); +/** + * Partitions the stream into non-empty arrays of the specified size. + * + * **Details** + * + * The final array may be smaller if there are not enough elements to fill it. + * + * **Example** (Grouping elements by size) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.range(1, 8).pipe( + * Stream.grouped(3), + * Stream.runCollect + * ) + * grouped // => [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const grouped = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => chunks(rechunk(self, n))))); +/** + * Partitions the stream into arrays, emitting when the chunk size is reached + * or the duration passes. + * + * **Example** (Grouping elements by size or time) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.groupedWithin(2, "5 seconds"), + * Stream.runCollect + * ) + * values // => [ [ 1, 2 ], [ 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupedWithin = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, chunkSize, duration) => aggregateWithin(self, Sink.take(chunkSize), Schedule.spaced(duration))))); +/** + * Groups elements into keyed substreams using an effectful classifier. + * + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.groupBy((n) => + * Effect.succeed([n % 2 === 0 ? "even" : "odd", n] as const) + * ), + * Stream.mapEffect( + * Effect.fnUntraced(function*([key, stream]) { + * return [key, yield* Stream.runCollect(stream)] as const + * }), + * { concurrency: "unbounded" } + * ), + * Stream.runCollect + * ) + * + * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) { + for (let i = 0; i < arr.length; i++) { + const [key, value] = yield* f(arr[i]); + const oentry = MutableHashMap.get(queueMap, key); + const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key)); + yield* RcMap.touch(queues, key); + yield* Queue.offer(queue, value); + } +}), options)))); +/** + * Groups elements by a key and emits a stream per key. + * + * **Example** (Grouping elements by key) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const grouped = yield* Stream.make(1, 2, 3, 4, 5).pipe( + * Stream.groupByKey((n) => n % 2 === 0 ? "even" : "odd"), + * Stream.mapEffect( + * ([key, stream]) => + * Stream.runCollect(stream).pipe( + * Effect.map((values) => [key, values] as const) + * ), + * { concurrency: "unbounded" } + * ), + * Stream.runCollect + * ) + * grouped // => [ [ 'odd', [ 1, 3, 5 ] ], [ 'even', [ 2, 4 ] ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupByKey = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, f, options) => suspend(() => { + const batch = MutableHashMap.empty(); + return groupByImpl(self, Effect.fnUntraced(function* (arr, queues, queueMap) { + for (let i = 0; i < arr.length; i++) { + const key = f(arr[i]); + const ovalues = MutableHashMap.get(batch, key); + if (Option.isNone(ovalues)) { + MutableHashMap.set(batch, key, [arr[i]]); + } else { + ovalues.value.push(arr[i]); + } + } + for (const [key, values] of batch) { + const oentry = MutableHashMap.get(queueMap, key); + const queue = Option.isSome(oentry) ? oentry.value : yield* Effect.scoped(RcMap.get(queues, key)); + yield* RcMap.touch(queues, key); + yield* Queue.offerAll(queue, values); + } + MutableHashMap.clear(batch); + }), options); +})))); +const groupByImpl = (self, f, options) => transformPullBracket(self, Effect.fnUntraced(function* (pull, scope, forkedScope) { + const out = yield* Queue.unbounded(); + yield* Scope.addFinalizer(scope, Queue.shutdown(out)); + const queueMap = MutableHashMap.empty(); + const queues = yield* RcMap.make({ + lookup: key => Effect.acquireRelease(Queue.make({ + capacity: options?.bufferSize ?? 4096 + }).pipe(Effect.tap(queue => { + MutableHashMap.set(queueMap, key, queue); + return Queue.offer(out, [key, fromQueue(queue)]); + })), queue => { + MutableHashMap.remove(queueMap, key); + return Queue.end(queue); + }), + idleTimeToLive: options?.idleTimeToLive ?? Duration.infinity + }).pipe(Scope.provide(forkedScope)); + yield* Effect.whileLoop({ + while: constTrue, + body: constant(Effect.flatMap(pull, arr => f(arr, queues, queueMap))), + step: constVoid + }).pipe(Effect.catchCause(cause => Queue.failCause(out, cause)), Effect.forkIn(scope)); + return Queue.takeAll(out); +})); +/** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping + * @since 2.0.0 + */ +const groupAdjacentBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let currentKey = undefined; + let group; + let toEmit = Arr.empty(); + const loop = pull.pipe(Effect.flatMap(chunk => { + for (let i = 0; i < chunk.length; i++) { + const item = chunk[i]; + const key = f(item); + if (group === undefined) { + currentKey = key; + group = [item]; + continue; + } else if (Equal.equals(key, currentKey)) { + group.push(item); + continue; + } + toEmit.push([currentKey, group]); + currentKey = key; + group = [item]; + } + if (Arr.isArrayNonEmpty(toEmit)) { + const out = toEmit; + toEmit = []; + return Effect.succeed(out); + } + return loop; + })); + let done = false; + return Pull.catchDone(Effect.suspend(() => done ? Cause.done() : loop), () => { + done = true; + const out = group; + group = undefined; + return out && Arr.isArrayNonEmpty(out) ? Effect.succeed(Arr.of([currentKey, out])) : Cause.done(); + }); +}))))); +/** + * Applies a sink transducer to the stream and emits each sink result. + * + * **Example** (Transducing with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const result = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.transduce(Sink.take(2)), + * Stream.runCollect + * ) + * + * result // => [ [ 1, 2 ], [ 3, 4 ], [] ] + * }) + * await Effect.runPromise(program) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const transduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => transformPull(self, (upstream, scope) => Effect.sync(() => { + let done; + let leftover; + const upstreamWithLeftover = Effect.suspend(() => { + if (leftover !== undefined) { + const chunk = leftover; + leftover = undefined; + return Effect.succeed(chunk); + } + return upstream; + }).pipe(Effect.catch(error => { + done = Exit.fail(error); + return Cause.done(); + })); + const pull = Effect.map(Effect.suspend(() => sink.transform(upstreamWithLeftover, scope)), ([value, leftover_]) => { + leftover = leftover_; + return Arr.of(value); + }); + return Effect.suspend(() => done ? done : pull); +}))))); +/** + * Aggregates elements using the provided sink and emits each sink result as a stream element. + * + * **Details** + * + * The stream runs the upstream and downstream in separate fibers, so the sink can keep + * consuming input while downstream is busy processing the previous output. + * + * **Example** (Aggregating with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const aggregated = yield* Stream.runCollect( + * Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.aggregate( + * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)) + * ) + * ) + * ) + * aggregated // => [ 6, 15 ] + * })) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const aggregate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => aggregateWithin(self, sink, Schedule.forever)))); +/** + * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. + * + * **Details** + * + * The schedule can flush the current aggregation even if the sink has not finished. + * + * **Example** (Aggregating with a sink and schedule) + * + * ```ts import.meta.vitest + * import { Effect, Schedule, Sink, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const aggregated = yield* Stream.runCollect( + * Stream.make(1, 2, 3, 4, 5, 6).pipe( + * Stream.aggregateWithin( + * Sink.foldUntil(() => 0, 3, (sum, n) => Effect.succeed(sum + n)), + * Schedule.forever + * ) + * ) + * ) + * aggregated // => [ 6, 15 ] + * })) + * ``` + * + * @category aggregation + * @since 2.0.0 + */ +const aggregateWithin = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, sink, schedule) => fromChannel(Channel.fromTransformBracket(Effect.fnUntraced(function* (_upstream, _, scope) { + const pull = yield* Channel.toPullScoped(self.channel, _); + const pullLatch = Latch.makeUnsafe(false); + const scheduleStep = Symbol(); + const buffer = yield* Queue.make({ + capacity: 0 + }); + // upstream -> buffer + yield* pull.pipe(pullLatch.whenOpen, Effect.flatMap(arr => { + pullLatch.closeUnsafe(); + return Queue.offer(buffer, arr); + }), Effect.forever, + // don't disable autoYield to prevent choking the schedule + Effect.catchCause(cause => Queue.failCause(buffer, cause)), Effect.forkIn(scope)); + // schedule -> buffer + let lastOutput = Option.none(); + let leftover; + let sinkHasInput = false; + const step = yield* Schedule.toStepWithSleep(schedule); + const stepLoop = Effect.suspend(function loop() { + return Effect.flatMap(step(lastOutput), () => !sinkHasInput ? loop() : Queue.offer(buffer, scheduleStep)); + }); + const stepToBuffer = stepLoop.pipe(Effect.flatMap(() => Effect.never), Pull.catchDone(() => Cause.done())); + // buffer -> sink + const pullFromBuffer = Queue.take(buffer).pipe(Effect.flatMap(arr => { + if (arr === scheduleStep) { + return Cause.done(); + } + sinkHasInput = true; + return Effect.succeed(arr); + })); + const sinkUpstream = Effect.suspend(() => { + if (leftover !== undefined) { + const chunk = leftover; + leftover = undefined; + sinkHasInput = true; + return Effect.succeed(chunk); + } + pullLatch.openUnsafe(); + return pullFromBuffer; + }); + const catchSinkHalt = Effect.flatMap(([value, leftover_]) => { + // ignore the last output if the upstream only pulled a halt + if (!sinkHasInput && buffer.state._tag === "Done") return Cause.done(); + lastOutput = Option.some(value); + leftover = leftover_; + return Effect.succeed(Arr.of(value)); + }); + return Effect.suspend(() => { + // if the buffer has exited and there is no more data to process + if (buffer.state._tag === "Done" && leftover === undefined) { + return buffer.state.exit; + } + sinkHasInput = leftover !== undefined; + return Effect.succeed(Effect.suspend(() => sink.transform(sinkUpstream, scope))); + }).pipe(Effect.flatMap(pull => Effect.raceFirst(catchSinkHalt(pull), stepToBuffer))); +})))))); +/** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * values // => [ [ 1, 2, 3 ], [ 1, 2, 3 ] ] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category broadcasting + * @since 4.0.0 + */ +const broadcastN = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, /*#__PURE__*/Effect.fnUntraced(function* (self, options) { + const pubsub = yield* makePubSub(options); + const streams = new Array(options.n); + const parentScope = yield* Scope.Scope; + for (let i = 0; i < options.n; i++) { + const scope = Scope.forkUnsafe(parentScope); + const subscription = yield* PubSub.subscribe(pubsub).pipe(Effect.provideService(Scope.Scope, scope)); + streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe(Channel.onExit(exit => Scope.close(scope, exit)), fromChannel); + } + yield* Channel.runForEach(self.channel, value => PubSub.publish(pubsub, value)).pipe(Effect.onExit(exit => PubSub.publish(pubsub, exit)), Effect.forkScoped); + return streams; +})))); +const makePubSub = options => Effect.acquireRelease(options.capacity === "unbounded" ? PubSub.unbounded(options) : options.strategy === "dropping" ? PubSub.dropping(options) : options.strategy === "sliding" ? PubSub.sliding(options) : PubSub.bounded(options), PubSub.shutdown); +/** + * Creates a PubSub-backed stream that multicasts the source to all subscribers. + * + * **Details** + * + * The returned stream is scoped and uses the provided PubSub capacity and replay settings. + * + * **Example** (Broadcasting a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function* () { + * const broadcasted = yield* Stream.broadcast(Stream.fromArray([1, 2, 3]), { + * capacity: 8, + * replay: 3 + * }) + * + * const [left, right] = yield* Effect.all([ + * Stream.runCollect(broadcasted), + * Stream.runCollect(broadcasted) + * ], { concurrency: "unbounded" }) + * + * const result = [left, right] // => [[1, 2, 3], [1, 2, 3]] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category broadcasting + * @since 2.0.0 + */ +const broadcast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Effect.map(toPubSubTake(self, options), fromPubSubTake)))); +/** + * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. + * + * **Details** + * + * The upstream continues running while there is at least one consumer and is finalized after the last one exits. + * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from + * the next element instead of restarting. + * + * **Example** (Sharing a stream) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Ref, Stream } from "effect" + * + * const result = await Effect.runPromise( + * Effect.scoped( + * Effect.gen(function*() { + * const firstReady = yield* Deferred.make() + * const secondReady = yield* Deferred.make() + * const acquisitions = yield* Ref.make(0) + * const source = Stream.fromEffect(Ref.update(acquisitions, (n) => n + 1)).pipe( + * Stream.drain, + * Stream.concat(Stream.make(0)), + * Stream.concat( + * Stream.fromEffect(Effect.all([Deferred.await(firstReady), Deferred.await(secondReady)])).pipe(Stream.drain) + * ), + * Stream.concat(Stream.make(1, 2, 3)) + * ) + * const shared = yield* Stream.share(source, { capacity: 16, replay: 1 }) + * const consume = (ready: Deferred.Deferred) => + * shared.pipe( + * Stream.tap((value) => value === 0 ? Deferred.succeed(ready, void 0) : Effect.void), + * Stream.filter((value) => value !== 0), + * Stream.runCollect + * ) + * + * const values = yield* Effect.all([consume(firstReady), consume(secondReady)], { concurrency: "unbounded" }) + * return { values, acquisitions: yield* Ref.get(acquisitions) } + * }) + * ) + * ) + * result // => { values: [[1, 2, 3], [1, 2, 3]], acquisitions: 1 } + * ``` + * + * @category broadcasting + * @since 3.8.0 + */ +const share = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Effect.map(RcRef.make({ + acquire: broadcast(self, options), + idleTimeToLive: options.idleTimeToLive +}), ref => unwrap(RcRef.get(ref)))))); +/** + * Pipes this stream through a channel that consumes and emits chunked elements. + * + * **Details** + * + * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the + * output elements and error type. + * + * **Example** (Piping through a channel) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] + * + * const doubleChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, (n) => n * 2)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.rechunk(2), + * Stream.pipeThroughChannel(doubleChunks), + * Stream.runCollect + * ) + * result // => [ 2, 4, 6 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThroughChannel = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, channel) => fromChannel(Channel.pipeTo(self.channel, channel))))); +/** + * Pipes values through the provided channel while preserving this stream's + * failures alongside any channel failures. + * + * **Details** + * + * Upstream failures are not passed to the channel, so the resulting stream can + * fail with either the original stream error or the channel error. + * + * **Example** (Piping through a channel with failures) + * + * ```ts import.meta.vitest + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] + * + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * const result = yield* Stream.make(1, 2, 3).pipe( + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), + * Stream.runCollect + * ) + * + * result // => ["1", "2", "3"] + * })) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThroughChannelOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, channel) => fromChannel(Channel.pipeToOrFail(self.channel, channel))))); +/** + * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. + * + * **Details** + * + * If the sink completes mid-chunk, the remaining elements become the output stream. + * + * **Example** (Piping through a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const leftovers = yield* Stream.make(1, 2, 3, 4).pipe( + * Stream.pipeThrough(Sink.take(2)), + * Stream.runCollect + * ) + * + * leftovers // => [ 3, 4 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const pipeThrough = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => self.channel.pipe(Channel.pipeToOrFail(Sink.toChannel(sink)), Channel.concatWith(([_, leftover]) => leftover ? Channel.succeed(leftover) : Channel.empty), fromChannel)))); +/** + * Collects all elements into an array and emits it as a single element. + * + * **Example** (Collecting values into a stream element) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.gen(function*() { + * const collected = yield* stream.pipe(Stream.collect, Stream.runCollect) + * collected[0] // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 4.0.0 + */ +const collect = self => fromEffect(runCollect(self)); +/** + * Accumulates elements into a growing array, emitting the cumulative array for each input chunk. + * + * **Example** (Accumulating stream elements) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const accumulated = yield* Stream.runCollect( + * Stream.fromArray([1, 2, 3]).pipe( + * Stream.rechunk(1), + * Stream.accumulate + * ) + * ) + * accumulated // => [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category accumulation + * @since 2.0.0 + */ +const accumulate = self => mapAccumArray(self, Arr.empty, (acc, as) => { + const combined = Arr.appendAll(acc, as); + return [combined, [combined]]; +}); +/** + * Emits only elements that differ from the previous one. + * + * **Example** (Emitting changed values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.fromIterable([1, 1, 2, 2, 3]).pipe( + * Stream.changes, + * Stream.runCollect + * ) + * + * values // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changes = self => changesWith(self, Equal.equals); +/** + * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. + * + * **Example** (Emitting values that changed by equivalence) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("A", "a", "B", "b", "b").pipe( + * Stream.changesWith((left, right) => left.toLowerCase() === right.toLowerCase()) + * ) + * + * await Effect.runPromise( + * Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 'A', 'B' ] + * }) + * ) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changesWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let first = true; + let last; + return Effect.flatMap(pull, function loop(arr) { + const out = []; + let i = 0; + if (first) { + first = false; + last = arr[0]; + i = 1; + out.push(last); + } + for (; i < arr.length; i++) { + const a = arr[i]; + if (f(a, last)) continue; + last = a; + out.push(a); + } + return Arr.isArrayNonEmpty(out) ? Effect.succeed(out) : Effect.flatMap(pull, loop); + }); +}))))); +/** + * Emits only elements that differ from the previous element, using an effectful equality check. + * + * **Details** + * + * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. + * + * **Example** (Effectfully emitting changed values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 1, 2, 2, 3, 3).pipe( + * Stream.changesWithEffect((a, b) => Effect.succeed(a === b)) + * ) + * const result = yield* Stream.runCollect(stream) + * result // => [ 1, 2, 3 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category deduplication + * @since 2.0.0 + */ +const changesWithEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => transformPull(self, (pull, _scope) => Effect.sync(() => { + let first = true; + let last; + return Effect.flatMap(pull, Effect.fnUntraced(function* loop(arr) { + const out = []; + let i = 0; + if (first) { + first = false; + last = arr[0]; + i = 1; + out.push(last); + } + for (; i < arr.length; i++) { + const a = arr[i]; + if (yield* f(a, last)) continue; + last = a; + out.push(a); + } + return Arr.isArrayNonEmpty(out) ? out : yield* Effect.flatMap(pull, Effect.fnUntraced(loop)); + })); +}))))); +/** + * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding. + * + * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const encoder = new TextEncoder() + * const stream = Stream.make( + * encoder.encode("Hello"), + * encoder.encode(" World") + * ) + * + * const program = Effect.gen(function*() { + * const decoded = yield* stream.pipe( + * Stream.decodeText, + * Stream.runCollect + * ) + * decoded // => [ 'Hello', ' World' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeText = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => suspend(() => { + const decoder = new TextDecoder(options?.encoding); + return map(self, chunk => decoder.decode(chunk, { + stream: true + })); +})))); +/** + * Encodes a stream of strings into UTF-8 `Uint8Array` chunks. + * + * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("Hello", " ", "World") + * const program = Effect.gen(function*() { + * const encoded = Stream.encodeText(stream) + * const chunks = yield* Stream.runCollect(encoded) + * const bytes = chunks.map((chunk) => [...chunk]) + * bytes // => [ [ 72, 101, 108, 108, 111 ], [ 32 ], [ 87, 111, 114, 108, 100 ] ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category encoding + * @since 2.0.0 + */ +const encodeText = self => suspend(() => { + const encoder = new TextEncoder(); + return map(self, chunk => encoder.encode(chunk)); +}); +/** + * Splits a stream of strings into lines, handling `\n`, `\r`, and `\r\n` delimiters across chunks. + * + * **Example** (Splitting streamed text into lines) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * await Effect.runPromise(Effect.gen(function* () { + * const lines = yield* Stream.runCollect( + * Stream.make("a\nb\r\n", "c\n").pipe(Stream.splitLines) + * ) + * lines // => [ 'a', 'b', 'c' ] + * })) + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const splitLines = self => self.channel.pipe(Channel.pipeTo(Channel.splitLines()), fromChannel); +/** + * Inserts the provided element between emitted elements. + * + * **Example** (Interspersing stream elements) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4).pipe(Stream.intersperse(0)) + * const result = yield* Stream.runCollect(stream) + * result // => [1, 0, 2, 0, 3, 0, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, element) => mapArray(self, (arr, i) => { + const out = i === 0 ? [] : [element]; + const lastIndex = arr.length - 1; + for (let j = 0; j < arr.length; j++) { + if (j === lastIndex) { + out.push(arr[j]); + } else { + out.push(arr[j], element); + } + } + return out; +})))); +/** + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** + * + * The start and end values are always emitted, even when the stream is empty. + * + * **Example** (Interspersing stream affixes) + * + * ```ts import.meta.vitest + * import { Console, Effect, Stream } from "effect" + * + * const stream = Stream.make("a", "b", "c").pipe( + * Stream.intersperseAffixes({ start: "[", middle: ",", end: "]" }) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => ["[", "a", ",", "b", ",", "c", "]"] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const intersperseAffixes = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => succeed(options.start).pipe(concat(intersperse(self, options.middle)), concat(succeed(options.end)))))); +/** + * Interleaves this stream with the specified stream by alternating pulls from + * each stream; when one ends, the remaining values from the other stream are + * emitted. + * + * **Example** (Interleaving streams) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.interleave( + * Stream.make(2, 3), + * Stream.make(5, 6, 7) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [ 2, 5, 3, 6, 7 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const interleave = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => interleaveWith(self, that, fromIterable(Iterable.forever([true, false])))))); +/** + * Interleaves two streams deterministically by following a boolean decider stream. + * + * **Details** + * + * The decider controls how many elements are pulled; if one side ends, pulls for + * that side are ignored. + * + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const left = Stream.make(1, 3, 5) + * const right = Stream.make(2, 4, 6) + * const decider = Stream.make(true, false, false, true, true) + * + * const values = yield* Stream.runCollect( + * Stream.interleaveWith(left, right, decider) + * ) + * + * values // => [ 1, 2, 4, 3, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category merging + * @since 2.0.0 + */ +const interleaveWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, decider) => fromChannel(Channel.fromTransform(Effect.fnUntraced(function* (upstream, scope) { + const pullDecider = yield* Channel.toTransform(Channel.flattenArray(decider.channel))(upstream, scope); + const retry = Symbol(); + let leftDone = false; + let rightDone = false; + const pullLeft = (yield* Channel.toTransform(Channel.flattenArray(self.channel))(upstream, scope)).pipe(Pull.catchDone(() => { + leftDone = true; + return Effect.succeed(retry); + })); + const pullRight = (yield* Channel.toTransform(Channel.flattenArray(that.channel))(upstream, scope)).pipe(Pull.catchDone(() => { + rightDone = true; + return Effect.succeed(retry); + })); + return Effect.gen(function* () { + while (true) { + if (leftDone && rightDone) { + return yield* Cause.done(); + } + const side = yield* pullDecider; + if (side && leftDone) continue; + if (!side && rightDone) continue; + const elem = yield* side ? pullLeft : pullRight; + if (elem === retry) continue; + return Arr.of(elem); + } + }); +})))))); +/** + * Interrupts the evaluation of this stream when the provided effect + * completes. The given effect will be forked as part of this stream, and its + * success will be discarded. This combinator will also interrupt any + * in-progress element being pulled from upstream. + * + * **Details** + * + * If the effect completes with a failure before the stream completes, the + * returned stream will emit that failure. + * + * **Example** (Interrupting when an effect completes) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const interrupt = yield* Deferred.make() + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.tap((value) => + * value === 2 + * ? Deferred.succeed(interrupt, void 0) + * : Effect.void + * ), + * Stream.interruptWhen(Deferred.await(interrupt)) + * ) + * + * const result = yield* Stream.runCollect(stream) + * result // => [ 1 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptWhen = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, effect) => fromChannel(_Channel_js__rspack_import_1/* .interruptWhen */.S6(self.channel, effect))); +/** + * Stops a stream after the current pull when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt or truncate an in-progress pull. A pull may emit + * multiple elements in a single chunk, in which case the entire chunk is + * emitted. Use {@link interruptWhen} when the stream should be interrupted + * immediately. + * + * **Example** (Halting a stream after an effect completes) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const halt = yield* Deferred.make() + * const values = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.tap((value) => value === 2 ? Deferred.succeed(halt, void 0) : Effect.void), + * Stream.haltWhen(Deferred.await(halt)), + * Stream.runCollect + * ) + * values // => [ 1, 2 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const haltWhen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => fromChannel(Channel.haltWhen(self.channel, effect))))); +/** + * Runs the provided finalizer when the stream exits, passing the exit value. + * + * **Example** (Running a finalizer on exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Stream } from "effect" + * + * const exits: Array = [] + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.onExit((exit) => + * Exit.isSuccess(exit) + * ? Effect.sync(() => exits.push("success")) + * : Effect.sync(() => exits.push("failure")) + * ) + * ) + * + * await Effect.runPromise(Effect.gen(function*() { + * yield* Stream.runCollect(stream) + * })) + * exits // => ["success"] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, finalizer) => fromChannel(_Channel_js__rspack_import_1/* .onExit */.cf(self.channel, finalizer))); +/** + * Runs the provided effect when the stream fails, passing the failure cause. + * + * **Gotchas** + * + * Note: Unlike `Effect.onError` there is no guarantee that the provided + * effect will not be interrupted. + * + * **Example** (Running an effect on errors) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Stream } from "effect" + * + * const errors: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.concat(Stream.fail("boom")), + * Stream.onError((cause) => Effect.sync(() => errors.push(String(Cause.squash(cause))))) + * ) + * + * yield* Stream.runCollect(stream) + * }) + * + * await Effect.runPromise(Effect.exit(program)) + * errors // => ["boom"] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const onError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cleanup) => fromChannel(Channel.onError(self.channel, cleanup))))); +/** + * Runs the provided effect before this stream starts. + * + * **Example** (Running an effect on start) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.fromArray([1, 2, 3]).pipe( + * Stream.onStart(Effect.sync(() => events.push("started"))) + * ) + * + * const values = yield* Stream.runCollect(stream) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["started"] + * ``` + * + * @category sequencing + * @since 3.6.0 + */ +const onStart = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onStart) => fromChannel(Channel.onStart(self.channel, onStart))))); +/** + * Runs the provided effect with the first element emitted by the stream. + * + * **Example** (Running an effect on the first value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const first: Array = [] + * await Effect.runPromise(Effect.gen(function* () { + * yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.onFirst((value) => Effect.sync(() => first.push(value))), + * Stream.runDrain + * ) + * })) + * first // => [1] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const onFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFirst) => fromChannel(Channel.onFirst(self.channel, arr => onFirst(arr[0])))))); +/** + * Runs the provided effect when the stream ends successfully. + * + * **Example** (Running an effect on end) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const values = yield* Stream.make(1, 2, 3).pipe( + * Stream.onEnd(Effect.sync(() => events.push("ended"))), + * Stream.runCollect + * ) + * values // => [1, 2, 3] + * }) + * + * await Effect.runPromise(program) + * events // => ["ended"] + * ``` + * + * @category sequencing + * @since 3.6.0 + */ +const onEnd = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onEnd) => fromChannel(Channel.onEnd(self.channel, onEnd))))); +/** + * Executes the provided finalizer after this stream's finalizers run. + * + * **Example** (Ensuring finalization) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const events: Array = [] + * const stream = Stream.fromArray([1, 2]).pipe( + * Stream.ensuring(Effect.sync(() => events.push("cleanup"))) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [1, 2] + * }) + * + * await Effect.runPromise(program) + * events // => ["cleanup"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, finalizer) => fromChannel(Channel.ensuring(self.channel, finalizer))))); +/** + * Provides a layer or context to the stream, removing the corresponding + * service requirements. Use `options.local` to build the layer every time; by + * default, layers are shared between provide calls. + * + * **Example** (Providing stream requirements) + * + * ```ts import.meta.vitest + * import { Console, Context, Effect, Layer, Stream } from "effect" + * + * class Env extends Context.Service()("Env") {} + * + * const layer = Layer.succeed(Env)({ name: "Ada" }) + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const env = yield* Effect.service(Env) + * return `Hello, ${env.name}` + * }) + * ) + * + * const withEnv = stream.pipe(Stream.provide(layer)) + * + * await Effect.runPromise(Stream.runCollect(withEnv)) // => ["Hello, Ada"] + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, layer, options) => fromChannel(Channel.provide(self.channel, layer, options))))); +/** + * Provides multiple services to the stream using a context. + * + * **Example** (Providing multiple services to the stream using a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Config extends Context.Service()("Config") {} + * class Greeter extends Context.Service string }>()("Greeter") {} + * + * const context = Context.make(Config, { prefix: "Hello" }).pipe( + * Context.add(Greeter, { greet: (name: string) => `${name}!` }) + * ) + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * const greeter = yield* Effect.service(Greeter) + * return greeter.greet(config.prefix) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(Stream.provideContext(stream, context)) + * result // => [ 'Hello!' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => fromChannel(Channel.provideContext(self.channel, context))))); +/** + * Provides the stream with a single required service, eliminating that + * requirement from its environment. + * + * **Example** (Providing a stream service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Greeter extends Context.Service string + * }>()("Greeter") {} + * + * const stream = Stream.fromEffect( + * Effect.service(Greeter).pipe( + * Effect.map((greeter) => greeter.greet("Ada")) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect( + * stream.pipe( + * Stream.provideService(Greeter, { + * greet: (name) => `Hello, ${name}` + * }) + * ) + * ) + * collected // => [ 'Hello, Ada' ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideService = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(3, (self, key, service) => fromChannel(_Channel_js__rspack_import_1/* .provideService */.Pf(self.channel, key, service))); +/** + * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. + * + * **Example** (Providing a stream service effectfully) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class ApiConfig extends Context.Service()("ApiConfig") {} + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const config = yield* Effect.service(ApiConfig) + * return config.baseUrl + * }) + * ) + * + * const events: Array = [] + * const withConfig = stream.pipe( + * Stream.provideServiceEffect( + * ApiConfig, + * Effect.succeed({ baseUrl: "https://example.com" }).pipe( + * Effect.tap(() => Effect.sync(() => events.push("loading"))) + * ) + * ) + * ) + * + * await Effect.runPromise(Stream.runCollect(withConfig)) // => ["https://example.com"] + * events // => ["loading"] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideServiceEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => fromChannel(Channel.provideServiceEffect(self.channel, key, service))))); +/** + * Transforms the stream's required services by mapping the current context + * to a new one. + * + * **Example** (Updating the stream context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Logger extends Context.Service()("Logger") {} + * class Config extends Context.Service()("Config") {} + * + * const stream = Stream.fromEffect( + * Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * const config = yield* Effect.service(Config) + * return `${logger.prefix}${config.name}` + * }) + * ) + * + * const updated = stream.pipe( + * Stream.updateContext((context: Context.Context) => + * Context.add(context, Config, { name: "World" }) + * ) + * ) + * + * const program = Effect.gen(function*() { + * const values = yield* Stream.runCollect(updated) + * values // => [ 'Hello World' ] + * }) + * + * await Effect.runPromise( + * Effect.provideService(program, Logger, { prefix: "Hello " }) + * ) + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromChannel(Channel.updateContext(self.channel, f))))); +/** + * Updates a single service in the stream environment by applying a function. + * + * **Example** (Updating a stream service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Stream } from "effect" + * + * class Counter extends Context.Service()("Counter") {} + * + * const stream = Stream.fromEffect(Effect.service(Counter)).pipe( + * Stream.updateService(Counter, (counter) => ({ count: counter.count + 1 })) + * ) + * + * const program = Effect.gen(function*() { + * const counters = yield* Stream.runCollect(stream) + * const message = `Updated count: ${counters[0].count}` // => "Updated count: 1" + * }) + * + * await Effect.runPromise(Effect.provideService(program, Counter, { count: 0 })) + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, service, f) => updateContext(self, context => Context.add(context, service, f(Context.get(context, service))))))); +/** + * Wraps the stream with a new span for tracing. + * + * **Example** (Wrapping a stream in a span) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.withSpan("numbers")) + * + * await Effect.runPromise( + * Effect.gen(function*() { + * const values = yield* Stream.runCollect(stream) + * values // => [ 1, 2, 3 ] + * }) + * ) + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = isStream(arguments[0]); + const name = dataFirst ? arguments[1] : arguments[0]; + const options = addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return fromChannel(Channel.withSpan(self.channel, name, options)); + } + return self => fromChannel(Channel.withSpan(self.channel, name, options)); +}; +/** + * Provides the entry point for do-notation style stream composition. + * + * **Example** (Starting stream do notation) + * + * ```ts import.meta.vitest + * import { Effect, pipe, Stream } from "effect" + * + * const program = pipe( + * Stream.Do, + * Stream.bind("value", () => Stream.fromArray([1, 2])), + * Stream.let("next", ({ value }) => value + 1) + * ) + * + * const effect = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(program) + * collected // => [ { value: 1, next: 2 }, { value: 2, next: 3 } ] + * }) + * + * await Effect.runPromise(effect) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, name, f) => map(self, a => ({ + ...a, + [name]: f(a) +}))))); + +/** + * Binds the result of a stream to a field in the do-notation record. + * + * **Example** (Binding a stream value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.Do.pipe( + * Stream.bind("a", () => Stream.make(1, 2)), + * Stream.bind("b", ({ a }) => Stream.succeed(a + 1)) + * ) + * + * const result = Stream.runCollect(program) + * + * await Effect.runPromise(result) // => [{ a: 1, b: 2 }, { a: 2, b: 3 }] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, tag, f, options) => flatMap(self, a => map(f(a), b => ({ + ...a, + [tag]: b +})), options)))); +/** + * Binds an Effect-produced value into the do-notation record for each stream element. + * + * **Example** (Binding an effect value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.Do.pipe( + * Stream.bind("value", () => Stream.make(1, 2)), + * Stream.bindEffect("double", ({ value }) => Effect.succeed(value * 2)) + * ) + * + * const program = Effect.gen(function*() { + * const result = yield* Stream.runCollect(stream) + * result // => [ { value: 1, double: 2 }, { value: 2, double: 4 } ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const bindEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, tag, f, options) => mapEffect(self, a => Effect.map(f(a), b => ({ + ...a, + [tag]: b +})), options)))); +/** + * Maps each element into a record keyed by the provided name. + * + * **Example** (Binding values to a record key) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3).pipe(Stream.bindTo("value")) + * + * await Effect.runPromise(Stream.runCollect(stream)) // => [{ value: 1 }, { value: 2 }, { value: 3 }] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, name) => map(self, a => ({ + [name]: a +}))))); +/** + * Runs a stream with a sink and returns the sink result. + * + * **Example** (Running a stream with a sink) + * + * ```ts import.meta.vitest + * import { Effect, Sink, Stream } from "effect" + * + * const program = Stream.run(Stream.make(1, 2, 3), Sink.sum) + * + * await Effect.runPromise(program) // => 6 + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const run = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sink) => Effect.scopedWith(scope => Channel.toPullScoped(self.channel, scope).pipe(Effect.flatMap(upstream => sink.transform(upstream, scope)), Effect.map(([a]) => a)))))); +/** + * Runs the stream and collects all elements into an array. + * + * **Example** (Collecting stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const program = Effect.gen(function*() { + * const collected = yield* Stream.runCollect(stream) + * collected // => [ 1, 2, 3, 4, 5 ] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runCollect = self => Channel.runFold(self.channel, () => [], (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc.push(chunk[i]); + } + return acc; +}); +/** + * Runs the stream and returns the number of elements emitted. + * + * **Example** (Counting stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const program = Effect.gen(function* () { + * const count = yield* Stream.runCount(stream) + * count // => 5 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runCount = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length); +/** + * Runs the stream and returns the numeric sum of its elements. + * + * **Example** (Summing stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runSum(Stream.make(1, 2, 3)) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runSum = self => Channel.runFold(self.channel, () => 0, (acc, chunk) => { + for (let i = 0; i < chunk.length; i++) { + acc += chunk[i]; + } + return acc; +}); +/** + * Runs the stream and folds elements using a pure reducer. + * + * **Example** (Folding stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runFold( + * Stream.make(1, 2, 3), + * () => 0, + * (acc, n) => acc + n + * ) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runFold = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Channel.runFold(self.channel, initial, (acc, arr) => { + for (let i = 0; i < arr.length; i++) { + acc = f(acc, arr[i]); + } + return acc; +})))); +/** + * Runs the stream and folds elements using an effectful reducer. + * + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const total = yield* Stream.runFoldEffect( + * Stream.make(1, 2, 3), + * () => 0, + * (acc, n) => Effect.succeed(acc + n) + * ) + * total // => 6 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runFoldEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, initial, f) => Channel.runFoldEffect(self.channel, initial, (acc, arr) => { + let i = 0; + let s = acc; + return Effect.map(Effect.whileLoop({ + while: () => i < arr.length, + body: () => f(s, arr[i]), + step(z) { + s = z; + i++; + } + }), () => s); +})))); +/** + * Runs the stream and returns the first element as an `Option`. + * + * **Example** (Getting the first stream value) + * + * ```ts import.meta.vitest + * import { Effect, Option, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const head = yield* Stream.runHead(Stream.make(1, 2, 3)) + * Option.getOrThrow(head) // => 1 + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runHead = self => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0))); +/** + * Runs the stream and returns the last element as an `Option`. + * + * **When to use** + * + * Use to consume a finite stream when only the final emitted element matters. + * + * **Details** + * + * `Option.some` contains the last emitted element. `Option.none` means the + * stream completed without emitting. + * + * **Gotchas** + * + * The returned effect waits for the stream to complete before it can produce a + * value. + * + * @see {@link runHead} for consuming only the first emitted element + * @see {@link runCollect} for collecting every emitted element + * @see {@link runDrain} for consuming the stream while discarding emitted elements + * + * @category destructors + * @since 2.0.0 + */ +const runLast = self => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty)); +/** + * Runs the provided effectful callback for each element of the stream. + * + * **Example** (Running an effect for each value) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * const values: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Stream.runForEach(stream, (n) => Effect.sync(() => values.push(`Processing: ${n}`))) + * }) + * + * await Effect.runPromise(program) + * values // => ["Processing: 1", "Processing: 2", "Processing: 3"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runForEach = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => _Channel_js__rspack_import_1/* .runForEach */.o1(self.channel, arr => { + let i = 0; + return _Effect_js__rspack_import_3/* .whileLoop */.iMI({ + while: () => i < arr.length, + body: () => f(arr[i++]), + step: _Function_js__rspack_import_7/* .constVoid */.Yi + }); +})); +/** + * Runs the stream, applying the effectful predicate to each element and + * stopping when it returns `false`. + * + * **Example** (Running effects while a predicate holds) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const values: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * yield* Stream.runForEachWhile(stream, (n) => + * Effect.gen(function*() { + * yield* Effect.sync(() => values.push(n)) + * return n < 3 + * }) + * ) + * }) + * + * await Effect.runPromise(program) + * values // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runForEachWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => Channel.runForEachWhile(self.channel, arr => { + let done = false; + let i = 0; + return Effect.map(Effect.whileLoop({ + while: () => !done && i < arr.length, + body: () => f(arr[i]), + step(b) { + i++; + if (!b) done = true; + } + }), () => !done); +})))); +/** + * Consumes the stream in chunks, passing each non-empty array to the callback. + * + * **Example** (Consuming stream chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const chunks: Array = [] + * const program = Effect.gen(function*() { + * yield* Stream.runForEachArray( + * stream, + * (chunk) => Effect.sync(() => chunks.push(chunk.join(", "))) + * ) + * }) + * + * await Effect.runPromise(program) + * chunks // => ["1, 2, 3, 4, 5"] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const runForEachArray = /*#__PURE__*/(0,_Function_js__rspack_import_7/* .dual */.XY)(2, (self, f) => _Channel_js__rspack_import_1/* .runForEach */.o1(self.channel, f)); +/** + * Runs the stream for its effects, discarding emitted elements. + * + * **Example** (Draining a stream run) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const values: Array = [] + * const program = Effect.gen(function*() { + * const stream = Stream.make(1, 2, 3).pipe( + * Stream.mapEffect((n) => Effect.sync(() => values.push(n))) + * ) + * + * yield* Stream.runDrain(stream) + * }) + * + * await Effect.runPromise(program) + * values // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runDrain = self => Channel.runDrain(self.channel); +/** + * Returns a scoped pull for manually consuming the stream's output chunks. + * + * **Details** + * + * The pull fails with `Cause.Done` when the stream ends and with the stream + * error on failure. + * + * **Example** (Creating a scoped pull) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const pull = yield* Stream.toPull(stream) + * const chunk = yield* pull + * chunk // => [ 1, 2, 3 ] + * }) + * ) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPull = self => Channel.toPull(self.channel); +/** + * Concatenates all emitted strings into a single string. + * + * **Example** (Joining strings from a stream) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make("Hello", " ", "World", "!") + * const program = Effect.gen(function*() { + * const text = yield* Stream.mkString(stream) + * text // => "Hello World!" + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const mkString = self => Channel.runFold(self.channel, () => "", (acc, chunk) => acc + chunk.join("")); +/** + * Concatenates the stream's `Uint8Array` chunks into a single `ArrayBuffer`. + * + * **Example** (Joining byte chunks into an ArrayBuffer) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const program = Stream.make( + * new Uint8Array([1, 2]), + * new Uint8Array([3, 4]) + * ).pipe( + * Stream.mkArrayBuffer, + * Effect.map((buffer) => [...new Uint8Array(buffer)]) + * ) + * + * await Effect.runPromise(program) // => [1, 2, 3, 4] + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source stream must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category destructors + * @since 4.0.0 + */ +const mkArrayBuffer = self => Effect.map(Channel.mkUint8Array(self.channel), bytes => bytes.buffer); +/** + * Concatenates the stream's `Uint8Array` chunks into a single `Uint8Array`. + * + * **Example** (Joining Uint8Array chunks) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(new Uint8Array([1, 2]), new Uint8Array([3, 4])) + * const program = Effect.gen(function*() { + * const bytes = yield* Stream.mkUint8Array(stream) + * const values = Array.from(bytes) // => [1, 2, 3, 4] + * }) + * + * await Effect.runPromise(program) + * ``` + * + * **Gotchas** + * + * This materializes the full content in memory. The source stream must not + * reuse or mutate emitted buffers, which are retained until collection completes. + * + * @category destructors + * @since 4.0.0 + */ +const mkUint8Array = self => Channel.mkUint8Array(self.channel); +/** + * Converts the stream to a `ReadableStream` using the provided services. + * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Converting to a ReadableStream with services) + * + * ```ts import.meta.vitest + * import { Context, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) + * const values = await Array.fromAsync(readableStream) + * values // => [ 1, 2, 3, 4, 5 ] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toReadableStreamWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, context, options) => { + let currentResolve = undefined; + let fiber = undefined; + const latch = Latch.makeUnsafe(false); + return new ReadableStream({ + start(controller) { + fiber = Effect.runFork(Effect.provideContext(runForEachArray(self, chunk => latch.whenOpen(Effect.sync(() => { + latch.closeUnsafe(); + for (let i = 0; i < chunk.length; i++) { + controller.enqueue(chunk[i]); + } + currentResolve(); + currentResolve = undefined; + }))), context)); + fiber.addObserver(exit => { + if (exit._tag === "Failure") { + controller.error(Cause.squash(exit.cause)); + } else { + controller.close(); + } + }); + }, + pull() { + return new Promise(resolve => { + currentResolve = resolve; + latch.openUnsafe(); + }); + }, + cancel() { + if (!fiber) return; + return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber))); + } + }, options?.strategy); +}))); +/** + * Converts a stream to a `ReadableStream`. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Converting a stream to a ReadableStream) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * const readableStream = Stream.toReadableStream(Stream.make(1, 2, 3)) + * const values = await Array.fromAsync(readableStream) + * values // => [ 1, 2, 3 ] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toReadableStream = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => toReadableStreamWith(self, Context.empty(), options)))); +/** + * Creates an Effect that builds a ReadableStream from the stream. + * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * **Example** (Creating a ReadableStream effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3, 4, 5) + * + * const effect = Effect.gen(function*() { + * const readableStream = yield* Stream.toReadableStreamEffect(stream) + * readableStream instanceof ReadableStream // => true + * }) + * + * await Effect.runPromise(effect) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toReadableStreamEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, options) => Effect.map(Effect.context(), context => toReadableStreamWith(self, context, options))))); +/** + * Converts the stream to an `AsyncIterable` using the provided services. + * + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * + * ```ts import.meta.vitest + * import { Context, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * const iterable = Stream.toAsyncIterableWith(stream, Context.empty()) + * + * await Array.fromAsync(iterable) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toAsyncIterableWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, context) => ({ + [Symbol.asyncIterator]() { + const runPromise = Effect.runPromiseWith(context); + const runFork = Effect.runForkWith(context); + const scope = Scope.makeUnsafe(); + let pull; + let currentIter; + let currentFiber; + let closePromise; + const close = exit => { + if (closePromise) return closePromise; + const fiber = currentFiber; + closePromise = runPromise(Effect.as(Effect.andThen(fiber ? Fiber.interrupt(fiber) : Effect.void, Scope.close(scope, exit)), { + done: true, + value: undefined + })); + return closePromise; + }; + const closeAndReportError = async exit => { + try { + await close(exit); + } catch (error) { + await runPromise(Effect.logError("Suppressed error while closing Stream async iterator", error)); + } + }; + return { + async next() { + if (closePromise) return closePromise; + if (currentIter) { + const next = currentIter.next(); + if (!next.done) return next; + currentIter = undefined; + } + const fiber = runFork(pull ?? Effect.flatMap(Channel.toPullScoped(self.channel, scope), nextPull => { + pull = nextPull; + return nextPull; + })); + currentFiber = fiber; + const exit = await runPromise(Fiber.await(fiber)); + if (currentFiber === fiber) { + currentFiber = undefined; + } + if (Exit.isSuccess(exit)) { + currentIter = exit.value[Symbol.iterator](); + return currentIter.next(); + } else if (Pull.isDoneCause(exit.cause)) { + return close(Exit.void); + } + if (closePromise && Cause.hasInterruptsOnly(exit.cause)) { + return closePromise; + } + await closeAndReportError(exit); + throw Cause.squash(exit.cause); + }, + return() { + return close(Exit.void); + }, + async throw(error) { + await closeAndReportError(Exit.die(error)); + throw error; + } + }; + } +})))); +/** + * Creates an effect that yields an `AsyncIterable` using the current services. + * + * **When to use** + * + * Use when the `AsyncIterable` should be created inside Effect with the current + * context supplying the stream's services. + * + * **Example** (Creating an AsyncIterable effect) + * + * ```ts import.meta.vitest + * import { Effect, Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * const program = Effect.gen(function*() { + * const iterable = yield* Stream.toAsyncIterableEffect(stream) + * return yield* Effect.promise(() => Array.fromAsync(iterable)) + * }) + * + * await Effect.runPromise(program) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 3.15.0 + */ +const toAsyncIterableEffect = self => Effect.map(Effect.context(), context => toAsyncIterableWith(self, context)); +/** + * Converts a stream to an `AsyncIterable` for `for await...of` consumption. + * + * **Example** (Converting to an async iterable) + * + * ```ts import.meta.vitest + * import { Stream } from "effect" + * + * const stream = Stream.make(1, 2, 3) + * + * await Array.fromAsync(Stream.toAsyncIterable(stream)) // => [1, 2, 3] + * ``` + * + * @category destructors + * @since 3.15.0 + */ +const toAsyncIterable = self => toAsyncIterableWith(self, Context.empty()); +/** + * Runs the stream, publishing elements into the provided PubSub. + * + * **Details** + * + * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. + * It only shuts down when set to `true`. + * + * **Example** (Running a stream into a PubSub) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function* () { + * const pubsub = yield* PubSub.unbounded() + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* Stream.runIntoPubSub(Stream.fromIterable([1, 2]), pubsub) + * + * const first = yield* PubSub.take(subscription) + * const second = yield* PubSub.take(subscription) + * + * first // => 1 + * second // => 2 + * })) + * + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runIntoPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isStream(args[0]), (self, pubsub, options) => Channel.runIntoPubSubArray(self.channel, pubsub, options)))); +/** + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** + * + * `shutdownOnEnd` indicates whether the PubSub should be shut down when the + * stream ends. By default this is `true`. + * + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.scoped(Effect.gen(function* () { + * const pubsub = yield* Stream.fromArray([1, 2]).pipe( + * Stream.toPubSub({ capacity: 8 }) + * ) + * const subscription = yield* PubSub.subscribe(pubsub) + * const first = yield* PubSub.take(subscription) + * + * first // => 1 + * })) + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toPubSub = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toPubSubArray(self.channel, options)))); +/** + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** + * + * `Take` values include the stream's end and failure signals. + * + * **Example** (Converting to a PubSub of takes) + * + * ```ts import.meta.vitest + * import { Effect, PubSub, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const pubsub = yield* Stream.fromArray([1, 2, 3]).pipe( + * Stream.toPubSubTake({ capacity: 8 }) + * ) + * const subscription = yield* PubSub.subscribe(pubsub) + * const take = yield* PubSub.take(subscription) + * + * if (Array.isArray(take)) { + * take // => [ 1, 2, 3 ] + * } + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toPubSubTake = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toPubSubTake(self.channel, options)))); +/** + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) + * + * ```ts import.meta.vitest + * import { Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function* () { + * const queue = yield* Stream.toQueue(Stream.fromIterable([1, 2, 3]), { capacity: 8 }) + * const chunk = yield* Queue.takeBetween(queue, 1, 3) + * chunk // => [ 1, 2, 3 ] + * }) + * await Effect.runPromise(Effect.scoped(program)) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const toQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => Channel.toQueueArray(self.channel, options)))); +/** + * Runs the stream, offering each element to the provided queue and ending it + * with `Cause.Done` when the stream completes. + * + * **Example** (Running a stream into a queue) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Queue, Stream } from "effect" + * + * const program = Effect.gen(function*() { + * const queue = yield* Queue.bounded(4) + * + * yield* Effect.forkChild( + * Stream.runIntoQueue(Stream.fromIterable([1, 2, 3]), queue) + * ) + * + * const values = [ + * yield* Queue.take(queue), + * yield* Queue.take(queue), + * yield* Queue.take(queue) + * ] + * const done = yield* Effect.flip(Queue.take(queue)) + * + * values // => [ 1, 2, 3 ] + * done._tag === "Done" // => true + * }) + * await Effect.runPromise(program) + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const runIntoQueue = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, queue) => Channel.runIntoQueueArray(self.channel, queue)))); +//# sourceMappingURL=Stream.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + EnV: paginate, + Mim: tap, + PfK: provideService, + QKh: takeUntil, + S67: interruptWhen, + WK$: mapEffect, + cfM: onExit, + ciY: fromArray, + fph: fromReadableStream, + hM$: runForEachArray, + o1d: runForEach, + oAg: unwrap, + sFT: tapError, + t8s: unfold, + xWs: concat +}); + + +}, +"./node_modules/effect/dist/Tracer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Encoding_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Encoding.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/** + * Defines the low-level tracing model used by Effect. + * + * A span records the lifetime of an operation, including its name, parent, + * attributes, links, annotations, sampling decision, kind, and completion + * status. The module also defines the tracer service, parent-span context, + * external span support, trace propagation settings, and the default in-memory + * span implementation. + * + * @since 2.0.0 + */ + + + + +const evaluate = "~effect/Effect/evaluate"; +/** + * 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" + * ``` + * + * @category constants + * @since 4.0.0 + */ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** + * Context service containing the `Span` or `ExternalSpan` to use as the parent + * of newly-created child spans. + * + * **Example** (Accessing the parent span) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the parent span from the context + * const program = Effect.gen(function*() { + * const parentSpan = yield* Effect.service(Tracer.ParentSpan) + * return parentSpan.spanId + * }) + * + * const parent = Tracer.externalSpan({ spanId: "span-123", traceId: "trace-456" }) + * await Effect.runPromise(Effect.provideService(program, Tracer.ParentSpan, parent)) // => "span-123" + * ``` + * + * @category services + * @since 2.0.0 + */ +class ParentSpan extends /*#__PURE__*/_Context_js__rspack_import_0/* .Service */.kl()(ParentSpanKey, { + fiberCached: true +}) {} +/** + * Creates a `Tracer` value from a tracer implementation object. + * + * **When to use** + * + * Use to create a custom tracing backend value that Effect can use when + * creating spans. + * + * **Details** + * + * `make` returns the supplied implementation object unchanged. The object must + * satisfy the `Tracer` contract, including a `span` method that returns a + * `Span`. + * + * @see {@link Span} for the span values returned by tracer implementations + * + * @category constructors + * @since 2.0.0 + */ +const make = options => options; +/** + * Creates an `ExternalSpan` from trace and span identifiers, defaulting + * `sampled` to `true` and annotations to an empty context when they are not + * provided. + * + * **Example** (Creating an external span) + * + * ```ts import.meta.vitest + * import { Effect, Option, Tracer } from "effect" + * + * // Create an external span from another tracing system + * const span = Tracer.externalSpan({ + * spanId: "span-abc-123", + * traceId: "trace-xyz-789", + * sampled: true + * }) + * + * // Use the external span as a parent + * const program = Effect.succeed("Hello").pipe( + * Effect.withSpan("child-operation", { parent: span }) + * ) + * + * const spans: Array = [] + * const tracer = Tracer.make({ + * span(options) { + * const span = new Tracer.NativeSpan(options) + * spans.push(span) + * return span + * } + * }) + * const value = await Effect.runPromise(Effect.provideService(program, Tracer.Tracer, tracer)) + * + * value // => "Hello" + * spans.map((span) => Option.getOrUndefined(span.parent)?.spanId) // => ["span-abc-123"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const externalSpan = options => ({ + _tag: "ExternalSpan", + spanId: options.spanId, + traceId: options.traceId, + sampled: options.sampled ?? true, + annotations: options.annotations ?? Context.empty() +}); +/** + * Context reference for disabling trace propagation. + * + * **When to use** + * + * Use to prevent spans in a scope from propagating tracing context. + * + * **Details** + * + * When enabled on fiber or span annotations, new spans are created as + * non-propagating no-op spans and disabled spans are skipped when deriving a + * parent span. + * + * **Example** (Disabling span propagation) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Disable span propagation for a specific effect + * const program = Tracer.DisablePropagation.pipe( + * Effect.provideService(Tracer.DisablePropagation, true) + * ) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 3.12.0 + */ +const DisablePropagation = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/DisablePropagation", { + defaultValue: _Function_js__rspack_import_1/* .constFalse */.f4 +}); +/** + * Context reference for controlling the current trace level for dynamic filtering. + * + * **When to use** + * + * Use to set the default trace level for spans in a scope when span options do + * not provide `level`. + * + * **Details** + * + * The default value is `"Info"`. Span creation uses `options.level ?? + * CurrentTraceLevel` before applying `MinimumTraceLevel`. + * + * @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled + * + * @category services + * @since 4.0.0 + */ +const CurrentTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/CurrentTraceLevel", { + defaultValue: () => "Info" +}); +/** + * Context reference for setting the minimum trace level threshold. Spans and their + * descendants below this level will have their sampling decision forced to + * false, preventing them from being exported. + * + * **When to use** + * + * Use to set the trace-level threshold that controls whether spans are sampled + * by default. + * + * **Details** + * + * The default value is `"All"`. Span creation compares the span level from + * `options.level ?? CurrentTraceLevel` against this threshold. + * + * **Gotchas** + * + * Explicit `options.sampled` bypasses threshold computation. + * + * @see {@link CurrentTraceLevel} for the default span level used when options do not specify one + * + * @category services + * @since 4.0.0 + */ +const MinimumTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/MinimumTraceLevel", { + defaultValue: () => "All" +}); +/** + * 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. + * + * @category constants + * @since 4.0.0 + */ +const TracerKey = "effect/Tracer"; +/** + * Context reference for the active tracer service. By default it uses the + * native tracer, which creates `NativeSpan` instances. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the current tracer from the context + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.service(Tracer.Tracer) + * // Or use the built-in tracer effect + * const tracerFromAccessor = yield* Effect.tracer + * return tracer === tracerFromAccessor + * }) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 2.0.0 + */ +const Tracer = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or(TracerKey, { + fiberCached: true, + defaultValue: () => make({ + span: options => new NativeSpan(options) + }) +}); +/** + * Default in-memory `Span` implementation used by the native tracer. It + * generates span and trace identifiers, stores attributes, events, and links, + * and records `Started` or `Ended` status. + * + * **Details** + * + * The constructor initializes the span with `Started` status, inherits the + * parent trace id or generates a new one, and always generates a new span id. + * Attributes, events, links, and status are then mutated through `Span` methods. + * + * @see {@link Span} for the interface implemented by native spans + * + * @category models + * @since 4.0.0 + */ +class NativeSpan { + _tag = "Span"; + spanId; + traceId = "native"; + sampled; + name; + parent; + annotations; + links; + startTime; + kind; + status; + attributes; + events = []; + constructor(options) { + this.name = options.name; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = options.links; + this.startTime = options.startTime; + this.kind = options.kind; + this.sampled = options.sampled; + this.status = { + _tag: "Started", + startTime: options.startTime + }; + this.attributes = new Map(); + this.traceId = _Option_js__rspack_import_2.getOrUndefined(options.parent)?.traceId ?? _Encoding_js__rspack_import_3/* .randomHex */.nw(32); + this.spanId = _Encoding_js__rspack_import_3/* .randomHex */.nw(16); + } + end(endTime, exit) { + this.status = { + _tag: "Ended", + endTime, + exit, + startTime: this.status.startTime + }; + } + attribute(key, value) { + this.attributes.set(key, value); + } + event(name, startTime, attributes) { + this.events.push([name, startTime, attributes ?? {}]); + } + addLinks(links) { + // oxlint-disable-next-line no-restricted-syntax + this.links.push(...links); + } +} +//# sourceMappingURL=Tracer.js.map +__webpack_require__.d(__webpack_exports__, { + Tv: () => (ParentSpan) +}, { + DW: DisablePropagation, + EW: MinimumTraceLevel, + RL: TracerKey, + WG: ParentSpanKey, + pX: CurrentTraceLevel, + sh: Tracer +}); + + +}, +"./node_modules/effect/dist/Utils.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Yields its wrapped value exactly once through an `IterableIterator`. + * + * **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 `{ value: self, done: false }`. Every + * subsequent call returns `{ value: a, done: true }` where `a` is the argument + * passed to `next()`. `[Symbol.iterator]()` returns a **new** `SingleShotGen` + * wrapping the same value, so the outer type can be iterated multiple times. + * + * **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", done: false } + * + * gen.next(42) // => { value: 42, done: true } + * ``` + * + * @see {@link Gen} for the type-level signature that relies on `SingleShotGen` + * @category constructors + * @since 2.0.0 + */ +class SingleShotGen { + called = false; + self; + constructor(self) { + this.self = self; + } + /** + * 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) { + return this.called ? { + value: a, + done: true + } : (this.called = true, { + value: this.self, + done: false + }); + } + /** + * Creates a fresh single-shot iterator over the stored value. + * + * **When to use** + * + * Use to iterate the wrapped value again without reusing the consumed + * iterator state. + * + * @since 2.0.0 + */ + [Symbol.iterator]() { + return new SingleShotGen(this.self); + } +} +// the probe is wrapped in a single function call (rather than module-level +// statements) so the whole selection is pure-annotated by the build and +// tree-shakable when `internalCall` is unused. +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { + [InternalTypeId]: body => { + return body(); + } + }; + const forced = { + [InternalTypeId]: body => { + try { + return body(); + } finally { + // + } + } + }; + const isNotOptimizedAway = standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true; + return isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/pickInternalCall(); +//# sourceMappingURL=Utils.js.map +__webpack_require__.d(__webpack_exports__, { + B: () => (SingleShotGen) +}, { + s: internalCall +}); + + +}, +"./node_modules/effect/dist/internal/array.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * @since 2.0.0 + */ +/** @internal */ +const isArrayNonEmpty = self => self.length > 0; +//# sourceMappingURL=array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + C: isArrayNonEmpty +}); + + +}, +"./node_modules/effect/dist/internal/core.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Utils_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _record_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); + + + + + + + + + +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_, + _R: _Function_js__rspack_import_0/* .identity */.D_ +}; +/** @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 (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + }, + toJSON() { + return { + ...this + }; + }, + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } +}; +/** @internal */ +const StructuralProto = { + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .structureKeys */.uN(this, Object.keys(this)); + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + const selfKeys = Object.keys(this); + const thatKeys = Object.keys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (let i = 0; i < selfKeys.length; i++) { + if (selfKeys[i] !== thatKeys[i] || !_Equal_js__rspack_import_5/* .equals */.aI(this[selfKeys[i]], that[selfKeys[i]])) { + return false; + } + } + return true; + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new _Utils_js__rspack_import_6/* .SingleShotGen */.B(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ...(args in this ? { + args: this[args] + } : undefined) + }; + } +}; +/** @internal */ +const isEffect = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, EffectTypeId); +/** @internal */ +const isExit = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, ExitTypeId); +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseTypeId); +/** @internal */ +const isCauseReason = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseReasonTypeId); +/** @internal */ +class CauseImpl { + [CauseTypeId]; + reasons; + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toJSON() { + return { + _id: "Cause", + failures: this.reasons.map(f => f.toJSON()) + }; + } + toString() { + return `Cause(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.reasons)})`; + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => _Equal_js__rspack_import_5/* .equals */.aI(e, that.reasons[i])); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .array */.YO(this.reasons); + } +} +const annotationsMap = /*#__PURE__*/new WeakMap(); +/** @internal */ +class ReasonBase { + [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); + }); + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this); + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toString(); + } +} +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/new Map(); +/** @internal */ +class Fail extends ReasonBase { + error; + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isFailReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.error, that.error) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.error))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeFromReasons = reasons => new CauseImpl(reasons); +/** @internal */ +const causeEmpty = /*#__PURE__*/new CauseImpl([]); +/** @internal */ +const causeFail = error => new CauseImpl([new Fail(error)]); +/** @internal */ +class Die extends ReasonBase { + defect; + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isDieReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.defect, that.defect) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.defect))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeDie = defect => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(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[evaluate] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = options => { + const Proto = makePrimitiveProto(options); + return function () { + const self = Object.create(Proto); + self[args] = options.single === false ? arguments : arguments[0]; + return self; + }; +}; +/** @internal */ +const makeExit = options => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isExit(that) && that._tag === this._tag && _Equal_js__rspack_import_5/* .equals */.aI(this[args], that[args]); + }, + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(options.op), _Hash_js__rspack_import_4/* .hash */.tW(this[args])); + } + }; + return function (value) { + const self = Object.create(Proto); + self[args] = value; + return self; + }; +}; +/** @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.currentStackFrame) { + cause = causeAnnotate(cause, { + mapUnsafe: new Map([[StackTraceKey.key, fiber.currentStackFrame]]) + }); + annotated = true; + } + let cont = fiber.getCont(contE); + while (fiber.interruptible && fiber._interruptedCause && cont) { + cont = fiber.getCont(contE); + } + return cont ? cont[contE](cause, fiber, annotated ? undefined : 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 = /*#__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 + } : undefined); + if (args) { + _record_js__rspack_import_8/* .assignProperties */.z(this, args); + // @effect-diagnostics-next-line floatingEffect:off + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = tag => { + class Base extends Error { + _tag = tag; + } + ; + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const NoSuchElementErrorTypeId = "~effect/Cause/NoSuchElementError"; +/** @internal */ +const isNoSuchElementError = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, NoSuchElementErrorTypeId); +/** @internal */ +class NoSuchElementError extends /*#__PURE__*/TaggedError("NoSuchElementError") { + [NoSuchElementErrorTypeId] = NoSuchElementErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, DoneTypeId); +const DoneVoid = { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value: undefined +}; +/** @internal */ +const Done = value => { + if (value === undefined) return DoneVoid; + return { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value + }; +}; +const doneVoid = /*#__PURE__*/exitFail(DoneVoid); +/** @internal */ +const done = value => { + if (value === undefined) return doneVoid; + return exitFail(Done(value)); +}; +//# sourceMappingURL=core.js.map +__webpack_require__.d(__webpack_exports__, { + ET: () => (ReasonBase), + Xm: () => (NoSuchElementError), + dM: () => (Fail), + s0: () => (CauseImpl) +}, { + $L: isDone, + $n: EffectTypeId, + Aj: isCause, + B4: CauseReasonTypeId, + DH: causeEmpty, + Eh: causeAnnotate, + GN: Yield, + IH: ExitTypeId, + In: StructuralProto, + Iu: causeDie, + OE: causeFail, + PW: isNoSuchElementError, + PX: CauseTypeId, + QJ: InterruptorStackTrace, + R6: withFiber, + RS: Done, + Rk: exitFail, + Sc: contE, + Uf: makePrimitive, + V2: exitDie, + Vw: done, + Wg: isCauseReason, + Xb: isDieReason, + _3: evaluate, + a2: args, + b5: causeFromReasons, + b9: isExit, + cb: exitFailCause, + dO: constEmptyAnnotations, + ee: contA, + fU: PipeInspectableProto, + ik: isInterruptReason, + lC: isFailReason, + qB: NoSuchElementErrorTypeId, + q_: DoneTypeId, + rN: TaggedError, + u4: contAll, + xt: exitSucceed, + yj: makePrimitiveProto, + yw: isEffect, + z8: StackTraceKey +}); + + +}, +"./node_modules/effect/dist/internal/doNotation.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); + +/** @internal */ +const let_ = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => map(self, a => ({ + ...a, + [name]: f(a) +}))); +/** @internal */ +const bindTo = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, name) => map(self, a => ({ + [name]: a +}))); +/** @internal */ +const bind = (map, flatMap) => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => flatMap(self, a => map(f(a), b => ({ + ...a, + [name]: b +})))); +//# sourceMappingURL=doNotation.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Jr: bindTo, + oI: bind, + zM: let_ +}); + + +}, +"./node_modules/effect/dist/internal/effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_20 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Equal_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Filter_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Filter.js"); +/* import */ var _Formatter_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_25 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Iterable_js__rspack_import_23 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Option_js__rspack_import_17 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Order_js__rspack_import_24 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Pipeable_js__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/* import */ var _Scheduler_js__rspack_import_13 = __webpack_require__("./node_modules/effect/dist/Scheduler.js"); +/* import */ var _Tracer_js__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Tracer.js"); +/* import */ var _Utils_js__rspack_import_18 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _doNotation_js__rspack_import_22 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _metric_js__rspack_import_16 = __webpack_require__("./node_modules/effect/dist/internal/metric.js"); +/* import */ var _record_js__rspack_import_21 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _references_js__rspack_import_15 = __webpack_require__("./node_modules/effect/dist/internal/references.js"); +/* import */ var _stackTraceLimit_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/stackTraceLimit.js"); +/* import */ var _tracer_js__rspack_import_19 = __webpack_require__("./node_modules/effect/dist/internal/tracer.js"); + + + + + + + + + + + + + + + + + + + + + + + + + + +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +class Interrupt extends _core_js__rspack_import_0/* .ReasonBase */.ET { + fiberId; + constructor(fiberId, annotations = _core_js__rspack_import_0/* .constEmptyAnnotations */.dO) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [_Equal_js__rspack_import_1/* .symbol */.HR](that) { + return (0,_core_js__rspack_import_0/* .isInterruptReason */.ik)(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [_Hash_js__rspack_import_2/* .symbol */.HR]() { + return _Hash_js__rspack_import_2/* .combine */.kg(_Hash_js__rspack_import_2/* .string */.Yj(`${this._tag}:${this.fiberId}`))(_Hash_js__rspack_import_2/* .random */.yT(this.annotations)); + } +} +/** @internal */ +const makeInterruptReason = fiberId => new Interrupt(fiberId); +/** @internal */ +const causeInterrupt = fiberId => new _core_js__rspack_import_0/* .CauseImpl */.s0([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = self => self.reasons.some(_core_js__rspack_import_0/* .isFailReason */.lC); +/** @internal */ +const findFail = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findError = self => { + for (let i = 0; i < self.reasons.length; i++) { + const reason = self.reasons[i]; + if (reason._tag === "Fail") { + return _Result_js__rspack_import_3/* .succeed */.Py(reason.error); + } + } + return _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findErrorOption = /*#__PURE__*/_Filter_js__rspack_import_4/* .toOption */.zL(findError); +/** @internal */ +const hasDies = self => self.reasons.some(_core_js__rspack_import_0/* .isDieReason */.Xb); +/** @internal */ +const findDie = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findDefect = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason.defect) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const hasInterrupts = self => self.reasons.some(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const findInterrupt = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isInterruptReason */.ik); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeFilterInterruptors = self => { + let interruptors; + for (let i = 0; i < self.reasons.length; i++) { + const f = self.reasons[i]; + if (f._tag !== "Interrupt") continue; + interruptors ??= new Set(); + if (f.fiberId !== undefined) { + interruptors.add(f.fiberId); + } + } + return interruptors ? _Result_js__rspack_import_3/* .succeed */.Py(interruptors) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeInterruptors = self => { + const result = causeFilterInterruptors(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? emptySet : result.success; +}; +const emptySet = /*#__PURE__*/new Set(); +/** @internal */ +const hasInterruptsOnly = self => self.reasons.length > 0 && self.reasons.every(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const reasonAnnotations = self => _Context_js__rspack_import_5/* .makeUnsafe */.LZ(self.annotations); +/** @internal */ +const causeAnnotations = self => { + const map = new Map(); + for (const f of self.reasons) { + if (f.annotations.size > 0) { + for (const [key, value] of f.annotations) { + map.set(key, value); + } + } + } + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(map); +}; +/** @internal */ +const causeCombine = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, that) => { + if (self.reasons.length === 0) { + return that; + } else if (that.reasons.length === 0) { + return self; + } + const newCause = new _core_js__rspack_import_0/* .CauseImpl */.s0(_Array_js__rspack_import_7/* .union */.KC(self.reasons, that.reasons)); + return _Equal_js__rspack_import_1/* .equals */.aI(self, newCause) ? self : newCause; +}); +/** @internal */ +const causeMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + let hasFail = false; + const failures = self.reasons.map(failure => { + if ((0,_core_js__rspack_import_0/* .isFailReason */.lC)(failure)) { + hasFail = true; + return new _core_js__rspack_import_0/* .Fail */.dM(f(failure.error), failure.annotations); + } + return failure; + }); + return hasFail ? (0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures) : self; +}); +/** @internal */ +const causePartition = self => { + const obj = { + Fail: [], + Die: [], + Interrupt: [] + }; + for (let i = 0; i < self.reasons.length; i++) { + obj[self.reasons[i]._tag].push(self.reasons[i]); + } + return obj; +}; +/** @internal */ +const causeSquash = self => { + const partitioned = causePartition(self); + if (partitioned.Fail.length > 0) { + return partitioned.Fail[0].error; + } else if (partitioned.Die.length > 0) { + return partitioned.Die[0].defect; + } else if (partitioned.Interrupt.length > 0) { + return new globalThis.Error("All fibers interrupted without error"); + } + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const causePrettyErrors = (self, options) => { + const errors = []; + const interrupts = []; + if (self.reasons.length === 0) return errors; + const prevStackLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(1); + for (const failure of self.reasons) { + if (failure._tag === "Interrupt") { + interrupts.push(failure); + continue; + } + errors.push(causePrettyError(failure._tag === "Die" ? failure.defect : failure.error, failure.annotations, options)); + } + if (errors.length === 0) { + const cause = new Error("The fiber was interrupted by:"); + cause.name = "InterruptCause"; + cause.stack = interruptCauseStack(cause, interrupts); + const error = new globalThis.Error("All fibers interrupted without error", { + cause + }); + error.name = "InterruptError"; + error.stack = `${error.name}: ${error.message}`; + errors.push(causePrettyError(error, interrupts[0].annotations, options)); + } + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevStackLimit); + return errors; +}; +/** @internal */ +const causePrettyError = (original, annotations, options) => { + const kind = typeof original; + let error; + if (original && kind === "object") { + error = new globalThis.Error(causePrettyMessage(original), { + cause: original.cause ? causePrettyError(original.cause) : undefined + }); + if (typeof original.name === "string") { + error.name = original.name; + } + if (typeof original.stack === "string") { + error.stack = cleanErrorStack(original.stack, error, annotations); + } else { + const stack = `${error.name}: ${error.message}`; + error.stack = annotations ? addStackAnnotations(stack, annotations) : stack; + } + if (options?.includeCauseInStack) { + error.stack = renderPrettyError(error); + } + for (const key of Object.keys(original)) { + if (!(key in error)) { + ; + error[key] = original[key]; + } + } + } else { + error = new globalThis.Error(!original ? `Unknown error: ${original}` : kind === "string" ? original : (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(original)); + } + return error; +}; +const causePrettyMessage = u => { + if (typeof u.message === "string") { + return u.message; + } else if (typeof u.toString === "function" && u.toString !== Object.prototype.toString && u.toString !== Array.prototype.toString) { + try { + return u.toString(); + } catch { + // something's off, rollback to json + } + } + return (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(u); +}; +const locationRegExp = /\((.*)\)/g; +const cleanErrorStack = (stack, error, annotations) => { + const message = `${error.name}: ${error.message}`; + const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split("\n"); + const out = [message]; + for (let i = 1; i < lines.length; i++) { + if (/(?:Generator\.next|~effect\/Effect)/.test(lines[i])) { + break; + } + out.push(lines[i]); + } + return annotations ? addStackAnnotations(out.join("\n"), annotations) : out.join("\n"); +}; +const addStackAnnotations = (stack, annotations) => { + const frame = annotations?.get(_core_js__rspack_import_0/* .StackTraceKey.key */.z8.key); + if (frame) { + stack = `${stack}\n${currentStackTrace(frame)}`; + } + return stack; +}; +const interruptCauseStack = (error, interrupts) => { + const out = [`${error.name}: ${error.message}`]; + for (const current of interrupts) { + const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : "unknown"; + const frame = current.annotations.get(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key); + out.push(` at fiber (${fiberId})`); + if (frame) out.push(currentStackTrace(frame)); + } + return out.join("\n"); +}; +const currentStackTrace = frame => { + const out = []; + let current = frame; + let i = 0; + while (current && i < 10) { + const stack = current.stack(); + if (stack) { + const locationMatchAll = stack.matchAll(locationRegExp); + let match = false; + for (const [, location] of locationMatchAll) { + match = true; + out.push(` at ${current.name} (${location})`); + } + if (!match) { + out.push(` at ${current.name} (${stack.replace(/^at /, "")})`); + } + } else { + out.push(` at ${current.name}`); + } + current = current.parent; + i++; + } + return out.join("\n"); +}; +/** @internal */ +const causePretty = cause => causePrettyErrors(cause).map(renderPrettyError).join("\n"); +const renderPrettyError = e => e.cause ? `${e.stack} {\n${renderErrorCause(e.cause, " ")}\n}` : e.stack; +const renderErrorCause = (cause, prefix) => { + const lines = cause.stack.split("\n"); + let stack = `${prefix}[cause]: ${lines[0]}`; + for (let i = 1, len = lines.length; i < len; i++) { + stack += `\n${prefix}${lines[i]}`; + } + if (cause.cause) { + stack += ` {\n${renderErrorCause(cause.cause, `${prefix} `)}\n${prefix}}`; + } + return stack; +}; +// ---------------------------------------------------------------------------- +// Fiber +// ---------------------------------------------------------------------------- +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: _Function_js__rspack_import_6/* .identity */.D_, + _E: _Function_js__rspack_import_6/* .identity */.D_ +}; +const fiberIdStore = { + id: 0 +}; +/** @internal */ +const getCurrentFiber = () => globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; +/** @internal */ +class FiberImpl { + constructor(context, interruptible = true) { + this[FiberTypeId] = fiberVariance; + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = []; + this._exit = undefined; + this._children = undefined; + this._interruptedCause = undefined; + this._yielded = undefined; + this._running = false; + this._deferredInterrupt = false; + this.runtimeMetrics?.recordFiberStart(this.context); + } + [FiberTypeId]; + id; + interruptible; + currentOpCount; + _stack; + _observers; + _exit; + _children; + _interruptedCause; + _yielded; + _running; + _deferredInterrupt; + // set in setContext + context; + currentScheduler; + currentTracerContext; + currentSpan; + currentLogLevel; + minimumLogLevel; + currentStackFrame; + runtimeMetrics; + maxOpsBeforeYield; + currentPreventYield; + _dispatcher = undefined; + get currentDispatcher() { + return this._dispatcher ??= this.currentScheduler.makeDispatcher(); + } + getRef(ref) { + return _Context_js__rspack_import_5/* .get */.Jt(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return _Function_js__rspack_import_6/* .constVoid */.Yi; + } + this._observers.push(cb); + return () => { + if (this._exit) 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.currentStackFrame) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, _Context_js__rspack_import_5/* .make */.L8(_core_js__rspack_import_0/* .StackTraceKey */.z8, this.currentStackFrame)); + } + if (annotations) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, annotations); + } + this._interruptedCause = this._interruptedCause ? causeCombine(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._yielded !== undefined) { + const yielded = this._yielded; + this._yielded = undefined; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === _core_js__rspack_import_0/* .Yield */.GN) { + return; + } + // the interruptChildren middleware is added in Effect.forkChild, so it can be + // tree-shaken if not used + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== undefined) { + return this.evaluate(flatMap(interruptChildren, () => exit)); + } + this._exit = exit; + this.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + for (let i = 0; i < this._observers.length; i++) { + this._observers[i](exit); + } + this._observers.length = 0; + this._stack.length = 0; + this._children = undefined; + this.context = _Context_js__rspack_import_5/* .empty */.Ie(); + } + runLoop(effect) { + const prevFiber = globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + if (!yielding && !this.currentPreventYield && this.currentScheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = this.currentTracerContext ? this.currentTracerContext(current, this) : current[_core_js__rspack_import_0/* .evaluate */._3](this); + if (current === _core_js__rspack_import_0/* .Yield */.GN) { + const yielded = this._yielded; + if (_core_js__rspack_import_0/* .ExitTypeId */.IH in yielded) { + this._deferredInterrupt = false; + this._yielded = undefined; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = undefined; + yielded(); + continue; + } + return _core_js__rspack_import_0/* .Yield */.GN; + } + } + } catch (error) { + if (!(0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(current, _core_js__rspack_import_0/* .evaluate */._3)) { + return (0,_core_js__rspack_import_0/* .exitDie */.V2)(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + } + return this.runLoop((0,_core_js__rspack_import_0/* .exitDie */.V2)(error)); + } finally { + this._running = prevRunning; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return undefined; + const cont = op[_core_js__rspack_import_0/* .contAll */.u4] && op[_core_js__rspack_import_0/* .contAll */.u4](this); + if (cont) { + ; + cont[symbol] = cont; + return cont; + } + if (op[symbol]) return op; + } + } + yieldWith(value) { + this._yielded = value; + return _core_js__rspack_import_0/* .Yield */.GN; + } + children() { + return this._children ??= new Set(); + } + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + // Every key cached below opts in to Context caching, so contexts related + // only by non-caching adds cannot have changed any of them + if (previous !== undefined && _Context_js__rspack_import_5/* .hasSameCache */.Pf(previous, context)) return; + const scheduler = this.getRef(_Scheduler_js__rspack_import_13/* .Scheduler */._F); + if (scheduler !== this.currentScheduler) { + this.currentScheduler = scheduler; + this._dispatcher = undefined; + } + // The string-keyed lookups keep the Tracer key values (and the native + // tracer behind Tracer.Tracer's default) out of every bundle + this.currentSpan = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .ParentSpanKey */.WG); + this.currentLogLevel = this.getRef(_references_js__rspack_import_15/* .CurrentLogLevel */.Gl); + this.minimumLogLevel = this.getRef(_references_js__rspack_import_15/* .MinimumLogLevel */.zQ); + this.currentStackFrame = this.getRef(_references_js__rspack_import_15/* .CurrentStackFrame */.vA); + this.maxOpsBeforeYield = this.getRef(_Scheduler_js__rspack_import_13/* .MaxOpsBeforeYield */.Zm); + this.currentPreventYield = this.getRef(_Scheduler_js__rspack_import_13/* .PreventSchedulerYield */.hf); + this.runtimeMetrics = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _metric_js__rspack_import_16/* .FiberRuntimeMetricsKey */.F); + const currentTracer = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .TracerKey */.RL); + this.currentTracerContext = currentTracer ? currentTracer["context"] : undefined; + } + get currentSpanLocal() { + return this.currentSpan?._tag === "Span" ? this.currentSpan : undefined; + } +} +const deferredInterruptCont = { + [_core_js__rspack_import_0/* .contA */.ee](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [_core_js__rspack_import_0/* .contE */.Sc](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const fiberMiddleware = { + interruptChildren: undefined +}; +const fiberStackAnnotations = fiber => { + if (!fiber.currentStackFrame) return undefined; + const annotations = new Map(); + annotations.set(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key, fiber.currentStackFrame); + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(annotations); +}; +const fiberInterruptChildren = fiber => { + if (fiber._children === undefined || fiber._children.size === 0) { + return undefined; + } + return fiberInterruptAll(fiber._children); +}; +/** @internal */ +const fiberAwait = self => { + const impl = self; + if (impl._exit) return succeed(impl._exit); + return callback(resume => { + if (impl._exit) return resume(succeed(impl._exit)); + return sync(self.addObserver(exit => resume(succeed(exit)))); + }); +}; +/** @internal */ +const fiberAwaitAll = self => callback(resume => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = undefined; + 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 fiberJoinAll = self => callback(resume => { + const fibers = Array.from(self); + if (fibers.length === 0) return resume(succeed(_Array_js__rspack_import_7/* .empty */.Ie())); + const out = new Array(fibers.length); + const cancels = _Array_js__rspack_import_7/* .empty */.Ie(); + let done = 0; + let failed = false; + for (let i = 0; i < fibers.length; i++) { + if (failed) break; + cancels.push(fibers[i].addObserver(exit => { + done++; + if (exit._tag === "Failure") { + failed = true; + cancels.forEach(cancel => cancel()); + return resume(exit); + } + out[i] = exit.value; + if (done === fibers.length) { + resume(succeed(out)); + } + })); + } + return sync(() => { + failed = true; + cancels.forEach(cancel => cancel()); + }); +}); +/** @internal */ +const fiberInterrupt = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fiberInterruptAs(self, fiber.id)); +/** @internal */ +const fiberInterruptAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(args[0], FiberTypeId), (self, fiberId, annotations) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + let ann = fiberStackAnnotations(parent); + ann = ann && annotations ? _Context_js__rspack_import_5/* .merge */.h1(ann, annotations) : ann ?? annotations; + self.interruptUnsafe(fiberId, ann); + return asVoid(fiberAwait(self)); +})); +/** @internal */ +const fiberInterruptAll = fibers => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const fiberInterruptAllAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (fibers, fiberId) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + const fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(fiberId, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +})); +/** @internal */ +const succeed = _core_js__rspack_import_0/* .exitSucceed */.xt; +/** @internal */ +const failCause = _core_js__rspack_import_0/* .exitFailCause */.cb; +/** @internal */ +const fail = _core_js__rspack_import_0/* .exitFail */.Rk; +/** @internal */ +const sync = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Sync", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const value = this[_core_js__rspack_import_0/* .args */.a2](); + const cont = fiber.getCont(_core_js__rspack_import_0/* .contA */.ee); + return cont ? cont[_core_js__rspack_import_0/* .contA */.ee](value, fiber) : fiber.yieldWith((0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Suspend", + [_core_js__rspack_import_0/* .evaluate */._3](_fiber) { + return this[_core_js__rspack_import_0/* .args */.a2](); + } +}); +/** @internal */ +const fromOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => args.length >= 2 || _Option_js__rspack_import_17.isOption(args[0]), (option, onNone) => _Option_js__rspack_import_17.isNone(option) ? fail(onNone ? onNone() : new _core_js__rspack_import_0/* .NoSuchElementError */.Xm("Effect.fromOption: Option.none")) : succeed(option.value)); +/** @internal */ +const fromResult = /*#__PURE__*/_Result_js__rspack_import_3/* .match */.YW({ + onFailure: fail, + onSuccess: succeed +}); +/** @internal */ +const fromNullishOr = value => value == null ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(value); +/** @internal */ +const yieldNowWith = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Yield", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this[_core_js__rspack_import_0/* .args */.a2] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/yieldNowWith(0); +/** @internal */ +const succeedSome = a => succeed(_Option_js__rspack_import_17.some(a)); +/** @internal */ +const succeedNone = /*#__PURE__*/succeed(/*#__PURE__*/_Option_js__rspack_import_17.none()); +/** @internal */ +const transposeOption = self => _Option_js__rspack_import_17.isNone(self) ? succeedNone : map(self.value, _Option_js__rspack_import_17.some); +/** @internal */ +const failCauseSync = evaluate => suspend(() => failCause((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate))); +/** @internal */ +const die = defect => (0,_core_js__rspack_import_0/* .exitDie */.V2)(defect); +/** @internal */ +const failSync = error => suspend(() => fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(error))); +/** @internal */ +const void_ = /*#__PURE__*/succeed(void 0); +/** @internal */ + +/** @internal */ +const try_ = options => { + const evaluate = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.try") : options.catch; + return suspend(() => { + try { + return succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate)); + } catch (err) { + return fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(err))); + } + }); +}; +/** @internal */ + +/** @internal */ +const promise = evaluate => callbackOptions(function (resume, signal) { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(signal)).then(a => resume(succeed(a)), e => resume(die(e))); +}, evaluate.length !== 0); +/** @internal */ +const tryPromise = options => { + const f = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.tryPromise") : options.catch; + return callbackOptions(function (resume, signal) { + const failWithCatch = cause => { + try { + resume(fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(cause)))); + } catch (err) { + resume(die(err)); + } + }; + try { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(signal)).then(a => resume(succeed(a)), failWithCatch); + } catch (err) { + failWithCatch(err); + } + }, f.length !== 0); +}; +/** @internal */ +const withFiberId = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.id)); +/** @internal */ +const fiber = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(succeed); +/** @internal */ +const fiberId = /*#__PURE__*/withFiberId(succeed); +const callbackOptions = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Async", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const register = (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => this[_core_js__rspack_import_0/* .args */.a2][0].bind(fiber.currentScheduler)); + let resumed = false; + let yielded = false; + const controller = this[_core_js__rspack_import_0/* .args */.a2][1] ? new AbortController() : undefined; + const onCancel = register(effect => { + if (resumed) return; + resumed = true; + if (yielded) { + fiber.evaluate(effect); + } else { + yielded = effect; + } + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber._yielded = () => { + resumed = true; + }; + if (controller === undefined && onCancel === undefined) { + return _core_js__rspack_import_0/* .Yield */.GN; + } + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return _core_js__rspack_import_0/* .Yield */.GN; + } +}); +const asyncFinalizer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "AsyncFinalizer", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(this[_core_js__rspack_import_0/* .args */.a2](), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = register => callbackOptions(register, register.length >= 2); +/** @internal */ +const never = /*#__PURE__*/callback(_Function_js__rspack_import_6/* .constVoid */.Yi); +/** @internal */ +const gen = (...args) => suspend(() => fromIteratorUnsafe(args.length === 1 ? args[0]() : args[1].call(args[0].self))); +/** @internal */ +const fnUntraced = (body, ...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 fnStackCleaner = /*#__PURE__*/(0,_tracer_js__rspack_import_19/* .makeStackCleaner */.R)(2); +/** @internal */ +const fn = function () { + const nameFirst = typeof arguments[0] === "string"; + const name = nameFirst ? arguments[0] : "Effect.fn"; + const spanOptions = nameFirst ? arguments[1] : undefined; + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const defError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + if (nameFirst) { + return (body, ...pipeables) => makeFn(name, body, defError, pipeables, nameFirst, spanOptions); + } + return makeFn(name, arguments[0], defError, Array.prototype.slice.call(arguments, 1), nameFirst, spanOptions); +}; +const makeFn = (name, bodyOrOptions, defError, pipeables, addSpan, spanOptions) => { + const body = typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); + return defineFunctionLength(body.length, function (...args) { + let result = suspend(() => { + const iter = body.apply(this, arguments); + return (0,_core_js__rspack_import_0/* .isEffect */.yw)(iter) ? iter : fromIteratorUnsafe(iter); + }); + for (let i = 0; i < pipeables.length; i++) { + result = pipeables[i](result, ...args); + } + if (!(0,_core_js__rspack_import_0/* .isEffect */.yw)(result)) { + return result; + } + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const callError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + return updateService(addSpan ? useSpan(name, spanOptions, span => provideParentSpan(result, span)) : result, _references_js__rspack_import_15/* .CurrentStackFrame */.vA, prev => ({ + name, + stack: fnStackCleaner(() => callError.stack), + parent: { + name: `${name} (definition)`, + stack: fnStackCleaner(() => defError.stack), + parent: prev + } + })); + }); +}; +/** @internal */ +const fnUntracedEager = (body, ...pipeables) => defineFunctionLength(body.length, pipeables.length === 0 ? function () { + return fromIteratorEagerUnsafe(() => body.apply(this, arguments)); +} : function () { + let effect = fromIteratorEagerUnsafe(() => body.apply(this, arguments)); + for (const pipeable of pipeables) { + effect = pipeable(effect); + } + return effect; +}); +const fromIteratorEagerUnsafe = evaluate => { + try { + const iterator = evaluate(); + let value = undefined; + // Try to resolve synchronously in a loop + while (true) { + const state = iterator.next(value); + if (state.done) { + return succeed(state.value); + } + const primitive = state.value; + if (primitive && primitive._tag === "Success") { + value = primitive.value; + continue; + } else if (primitive && primitive._tag === "Failure") { + return state.value; + } else { + let isFirstExecution = true; + return suspend(() => { + if (isFirstExecution) { + isFirstExecution = false; + return flatMap(state.value, value => fromIteratorUnsafe(iterator, value)); + } else { + return suspend(() => fromIteratorUnsafe(evaluate())); + } + }); + } + } + } catch (error) { + return die(error); + } +}; +const fromIteratorUnsafe = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Iterator", + single: false, + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + const iter = this[_core_js__rspack_import_0/* .args */.a2][0]; + 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; + } + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + return this[_core_js__rspack_import_0/* .contA */.ee](this[_core_js__rspack_import_0/* .args */.a2][1], fiber); + } +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, value) => { + const b = succeed(value); + return flatMap(self, _ => b); +}); +/** @internal */ +const asSome = self => map(self, _Option_js__rspack_import_17.some); +/** @internal */ +const flip = self => matchEffect(self, { + onFailure: succeed, + onSuccess: fail +}); +/** @internal */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => (0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)))); +/** @internal */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => as((0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)), a))); +/** @internal */ +const asVoid = self => flatMap(self, _ => exitVoid); +/** @internal */ +const sandbox = self => catchCause(self, fail); +/** @internal */ +const raceAll = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + const effects = _Array_js__rspack_import_7/* .fromIterable */.Ts(all); + const len = effects.length; + let doneCount = 0; + let done = false; + const fibers = new Set(); + const failures = []; + const onExit = (exit, fiber, i) => { + doneCount++; + if (exit._tag === "Failure") { + failures.push(...exit.cause.reasons); + if (doneCount >= len) { + resume(failCause((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures))); + } + return; + } + const isWinner = !done; + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index: i, + parentFiber: parent + }); + } + }; + for (let i = 0; i < len; i++) { + const fiber = forkUnsafe(parent, effects[i], true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + onExit(exit, fiber, i); + }); + if (done) break; + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const raceAllFirst = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + let done = false; + const fibers = new Set(); + const onExit = exit => { + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + }; + let i = 0; + for (const effect of all) { + if (done) break; + const index = i++; + const fiber = forkUnsafe(parent, effect, true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + const isWinner = !done; + onExit(exit); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index, + parentFiber: parent + }); + } + }); + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const race = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAll([self, that], options)); +/** @internal */ +const raceFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAllFirst([self, that], options)); +/** @internal */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onSuccess = Object.create(OnSuccessProto); + onSuccess[_core_js__rspack_import_0/* .args */.a2] = self; + onSuccess[_core_js__rspack_import_0/* .contA */.ee] = f.length !== 1 ? a => f(a) : f; + return onSuccess; +}); +const OnSuccessProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccess", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCauseEffectEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? options.onSuccess(self.value) : options.onFailure(self.cause); + } + return matchCauseEffect(self, options); +}); +/** @internal */ +const effectIsExit = effect => _core_js__rspack_import_0/* .ExitTypeId */.IH in effect; +/** @internal */ +const flatMapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? f(self.value) : self; + } + return flatMap(self, f); +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const flatten = self => flatMap(self, _Function_js__rspack_import_6/* .identity */.D_); +/** @internal */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a))))); +/** @internal */ +const mapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMap(self, f) : map(self, f)); +/** @internal */ +const mapErrorEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMapError(self, f) : mapError(self, f)); +/** @internal */ +const mapBothEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => effectIsExit(self) ? exitMapBoth(self, options) : mapBoth(self, options)); +/** @internal */ +const catchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return f(error.success); + } + return catch_(self, f); +}); +// ---------------------------------------------------------------------------- +// Exit +// ---------------------------------------------------------------------------- +/** @internal */ +const exitInterrupt = fiberId => (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(causeInterrupt(fiberId)); +/** @internal */ +const exitIsSuccess = self => self._tag === "Success"; +/** @internal */ +const exitFilterSuccess = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterValue = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self.value) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitIsFailure = self => self._tag === "Failure"; +/** @internal */ +const exitFilterFailure = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterCause = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self.cause) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFindError = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findError); +/** @internal */ +const exitFindDefect = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findDefect); +/** @internal */ +const exitHasInterrupts = self => self._tag === "Failure" && hasInterrupts(self.cause); +/** @internal */ +const exitHasDies = self => self._tag === "Failure" && hasDies(self.cause); +/** @internal */ +const exitHasFails = self => self._tag === "Failure" && hasFails(self.cause); +/** @internal */ +const exitVoid = /*#__PURE__*/(0,_core_js__rspack_import_0/* .exitSucceed */.xt)(void 0); +/** @internal */ +const exitMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => self._tag === "Success" ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(f(self.value)) : self); +/** @internal */ +const exitMapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(f(error.success)); +}); +/** @internal */ +const exitMapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(options.onFailure(error.success)); +}); +/** @internal */ +const exitAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, b) => exitIsSuccess(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(b) : self); +/** @internal */ +const exitZipRight = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, that) => exitIsSuccess(self) ? that : self); +/** @internal */ +const exitMatch = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => exitIsSuccess(self) ? options.onSuccess(self.value) : options.onFailure(self.cause)); +/** @internal */ +const exitAsVoid = /*#__PURE__*/exitAs(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 : (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures)); +}; +/** @internal */ +const exitGetSuccess = self => exitIsSuccess(self) ? _Option_js__rspack_import_17.some(self.value) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitGetCause = self => exitIsFailure(self) ? _Option_js__rspack_import_17.some(self.cause) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitFindErrorOption = self => { + const error = exitFindError(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(error) ? _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(error.success); +}; +// ---------------------------------------------------------------------------- +// environment +// ---------------------------------------------------------------------------- +/** @internal */ +const service = service => service; +/** @internal */ +const serviceOption = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const serviceOptional = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fromOption(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const updateContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + return onExitPrimitive(self, () => { + fiber.setContext(prevContext); + return undefined; + }); +})); +/** @internal */ +const updateService = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, f) => updateContext(self, s => { + const prev = _Context_js__rspack_import_5/* .getUnsafe */.fp(s, service); + const next = f(prev); + if (prev === next) return s; + return _Context_js__rspack_import_5/* .add */.WQ(s, service, next); +})); +/** @internal */ +const updateServiceScoped = (service, update, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const original = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + const updated = update(original); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, updated)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + let next; + if (options?.reset === undefined) { + if (current !== updated) return void_; + next = original; + } else { + next = options.reset(original, updated, current); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, next)); + return void_; + }); +})); +/** @internal */ +const context = () => getContext; +const getContext = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.context)); +/** @internal */ +const contextWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.context)); +/** @internal */ +const setContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => updateContext(self, (0,_Function_js__rspack_import_6/* .constant */.dY)(context))); +/** @internal */ +const provideContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, _Context_js__rspack_import_5/* .merge */.h1(context)); +}); +/** @internal */ +const provideService = function () { + if (arguments.length === 1) { + return (0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + } + return (0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, _Context_js__rspack_import_5/* .add */.WQ(service, implementation)); +/** @internal */ +const provideServiceEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, acquire) => flatMap(acquire, implementation => provideService(self, service, implementation))); +// ---------------------------------------------------------------------------- +// zipping +// ---------------------------------------------------------------------------- +/** @internal */ +const zip = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => zipWith(self, that, (a, a2) => [a, a2], options)); +/** @internal */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, f, options) => options?.concurrent +// Use `all` exclusively for concurrent cases, as it introduces additional overhead due to the management of concurrency +? map(all([self, that], { + concurrency: 2 +}), ([a, a2]) => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))) : flatMap(self, a => map(that, a2 => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))))); +// ---------------------------------------------------------------------------- +// filtering & conditionals +// ---------------------------------------------------------------------------- +/* @internal */ +const filterOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, orFailWith) => filterOrElse(self, predicate, orFailWith ? a => fail(orFailWith(a)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const when = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, condition) => flatMap(condition, pass => pass ? asSome(self) : succeedNone)); +// ---------------------------------------------------------------------------- +// repetition +// ---------------------------------------------------------------------------- +/** @internal */ +const replicate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, n) => Array.from({ + length: n +}, () => self)); +/** @internal */ +const replicateEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, n, options) => all(replicate(self, n), options)); +/** @internal */ +const forever = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => whileLoop({ + while: _Function_js__rspack_import_6/* .constTrue */.ue, + body: (0,_Function_js__rspack_import_6/* .constant */.dY)(options?.disableYield ? self : flatMap(self, _ => yieldNow)), + step: _Function_js__rspack_import_6/* .constVoid */.Yi +})); +// ---------------------------------------------------------------------------- +// error handling +// ---------------------------------------------------------------------------- +/** @internal */ +const catchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onFailure = Object.create(OnFailureProto); + onFailure[_core_js__rspack_import_0/* .args */.a2] = self; + onFailure[_core_js__rspack_import_0/* .contE */.Sc] = f.length !== 1 ? cause => f(cause) : f; + return onFailure; +}); +const OnFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const catchCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCause(self, cause => { + if (!predicate(cause)) { + return failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)); +})); +/** @internal */ +const catchCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const eb = filter(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(eb) ? failCause(eb.failure) : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(eb.success, cause)); +})); +/** @internal */ +const catch_ = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findError, e => f(e))); +/** @internal */ +const catchNoSuchElement = self => matchEffect(self, { + onFailure: error => (0,_core_js__rspack_import_0/* .isNoSuchElementError */.PW)(error) ? succeedNone : fail(error), + onSuccess: succeedSome +}); +/** @internal */ +const catchDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findDefect, f)); +/** @internal */ +const tapCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCause(self, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCauseIf(self, predicate, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const result = filter(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return failCause(cause); + } + return andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success, cause)), failCause(cause)); +})); +/** @internal */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findError, e => f(e))); +/** @internal */ +const tapErrorTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, k, f) => { + const predicate = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return tapError(self, error => predicate(error) ? f(error) : void_); +}); +/** @internal */ +const tapDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findDefect, _ => f(_))); +/** @internal */ +const catchIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + if (!predicate(error.success)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(error.success)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(error.success)); +})); +/** @internal */ +const catchFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + const result = filter(error.success); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(result.failure)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success)); +})); +/** @internal */ +const catchTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return catchIf(self, pred, f, orElse); +}); +/** @internal */ +const catchTags = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, cases, orElse) => { + let keys; + return catchFilter(self, e => { + keys ??= Object.keys(cases); + return (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e["_tag"]) && keys.includes(e["_tag"]) ? _Result_js__rspack_import_3/* .succeed */.Py(e) : _Result_js__rspack_import_3/* .fail */.fJ(e); + }, e => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[e["_tag"]](e)), orElse); +}); +/** @internal */ +const catchReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, reasonTag, f, orElse) => catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason"), e => { + const reason = e.reason; + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(reason, reasonTag)) return f(reason, e); + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); +})); +/** @internal */ +const catchReasons = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, cases, orElse) => { + let keys; + return catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason") && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e.reason, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e.reason._tag), e => { + const reason = e.reason; + keys ??= Object.keys(cases); + if (keys.includes(reason._tag)) { + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[reason._tag](reason, e)); + } + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); + }); +}); +/** @internal */ +const unwrapReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, errorTag) => catchFilter(self, e => { + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason")) { + return _Result_js__rspack_import_3/* .succeed */.Py(e.reason); + } + return _Result_js__rspack_import_3/* .fail */.fJ(e); +}, fail)); +/** @internal */ +const mapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, error => failSync(() => f(error)))); +/* @internal */ +const mapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: e => failSync(() => options.onFailure(e)), + onSuccess: a => sync(() => options.onSuccess(a)) +})); +/** @internal */ +const orDie = self => catch_(self, die); +/** @internal */ +const orElseSucceed = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, _ => sync(f))); +/** @internal */ +const firstSuccessOf = effects => suspend(() => { + const iterator = effects[Symbol.iterator](); + let state = iterator.next(); + if (state.done) { + return die(new Error("Received an empty collection of effects")); + } + function loop(current) { + const next = iterator.next(); + if (next.done) return current.value; + return catch_(current.value, _ => loop(next)); + } + return loop(state); +}); +/** @internal */ +const eventually = self => catch_(self, _ => flatMap(yieldNow, () => eventually(self))); +/** @internal */ +const ignore = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure(cause) { + const failure = findFail(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + }, + onSuccess: _ => void_ + }); +}); +/** @internal */ +const ignoreCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: cause => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: _ => void_ + }); +}); +/** @internal */ +const option = self => match(self, { + onFailure: _Option_js__rspack_import_17.none, + onSuccess: _Option_js__rspack_import_17.some +}); +/** @internal */ +const result = self => matchEager(self, { + onFailure: _Result_js__rspack_import_3/* .fail */.fJ, + onSuccess: _Result_js__rspack_import_3/* .succeed */.Py +}); +// ---------------------------------------------------------------------------- +// pattern matching +// ---------------------------------------------------------------------------- +/** @internal */ +const matchCauseEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + const primitive = Object.create(OnSuccessAndFailureProto); + primitive[_core_js__rspack_import_0/* .args */.a2] = self; + primitive[_core_js__rspack_import_0/* .contA */.ee] = options.onSuccess.length !== 1 ? a => options.onSuccess(a) : options.onSuccess; + primitive[_core_js__rspack_import_0/* .contE */.Sc] = options.onFailure.length !== 1 ? cause => options.onFailure(cause) : options.onFailure; + return primitive; +}); +const OnSuccessAndFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccessAndFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => sync(() => options.onFailure(cause)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => { + const fail = cause.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return fail ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => options.onFailure(fail.error)) : failCause(cause); + }, + onSuccess: options.onSuccess +})); +/** @internal */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: error => sync(() => options.onFailure(error)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(error.success)); + } + return match(self, options); +}); +/** @internal */ +const matchCauseEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(self.cause)); + } + return matchCause(self, options); +}); +/** @internal */ +const exit = self => effectIsExit(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Exit", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause)); + } +}); +// ---------------------------------------------------------------------------- +// Condition checking +// ---------------------------------------------------------------------------- +/** @internal */ +const isFailure = /*#__PURE__*/matchEager({ + onFailure: () => true, + onSuccess: () => false +}); +/** @internal */ +const isSuccess = /*#__PURE__*/matchEager({ + onFailure: () => false, + onSuccess: () => true +}); +// ---------------------------------------------------------------------------- +// delays & timeouts +// ---------------------------------------------------------------------------- +/** @internal */ +const delay = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => andThen(sleep(duration), self)); +/** @internal */ +const timeoutOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => raceFirst(self, flatMap(sleep(options.duration), options.orElse))); +/** @internal */ +const timeout = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => timeoutOrElse(self, { + duration, + orElse: () => fail(new TimeoutError()) +})); +/** @internal */ +const timeoutOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => raceFirst(asSome(self), as(sleep(duration), _Option_js__rspack_import_17.none()))); +/** @internal */ +const timed = self => clockWith(clock => { + const start = clock.monotonicTimeNanosUnsafe(); + return map(self, a => [_Duration_js__rspack_import_20/* .nanos */.cF(clock.monotonicTimeNanosUnsafe() - start), a]); +}); +// ---------------------------------------------------------------------------- +// resources & finalization +// ---------------------------------------------------------------------------- +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => suspend(() => scopeCloseUnsafe(self, exit_) ?? void_); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + if (self.state._tag === "Closed") return; + const closed = { + _tag: "Closed", + exit: exit_ + }; + if (self.state._tag === "Empty") { + self.state = closed; + return; + } + const state = self.state; + self.state = closed; + if (state.finalizer !== undefined) { + return state.finalizer(exit_); + } + const finalizers = state.finalizers; + if (finalizers === undefined || finalizers.size === 0) { + return; + } else if (finalizers.size === 1) { + return finalizers.values().next().value(exit_); + } + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, cause => failCause(causeCombine(exit_.cause, cause))); +const scopeCloseFinalizers = /*#__PURE__*/fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers.values()); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const finalizer = arr[i]; + if (self.strategy === "sequential") { + exits.push(yield* exit(finalizer(exit_))); + } else { + fibers.push(forkUnsafe(parent, finalizer(exit_), true, true, "inherit")); + } + } + if (fibers.length > 0) { + exits = yield* fiberAwaitAll(fibers); + } + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeFork = (scope, finalizerStrategy) => sync(() => scopeForkUnsafe(scope, finalizerStrategy)); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const newScope = scopeMakeUnsafe(finalizerStrategy); + if (scope.state._tag === "Closed") { + newScope.state = scope.state; + return newScope; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, exit => scopeClose(newScope, exit)); + scopeAddFinalizerUnsafe(newScope, key, _ => sync(() => scopeRemoveFinalizerUnsafe(scope, key))); + return newScope; +}; +/** @internal */ +const scopeAddFinalizerExit = (scope, finalizer) => { + return suspend(() => { + if (scope.state._tag === "Closed") { + return finalizer(scope.state.exit); + } + scopeAddFinalizerUnsafe(scope, {}, finalizer); + return void_; + }); +}; +/** @internal */ +const scopeAddFinalizer = (scope, finalizer) => scopeAddFinalizerExit(scope, (0,_Function_js__rspack_import_6/* .constant */.dY)(finalizer)); +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") { + scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: undefined + }; + } else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== undefined) { + state.finalizers = new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = undefined; + state.finalizer = undefined; + state.finalizers.set(key, finalizer); + } else if (state.finalizers === undefined) { + state.finalizerKey = key; + state.finalizer = finalizer; + } else { + state.finalizers.set(key, finalizer); + } + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizerKey === key) { + state.finalizerKey = undefined; + state.finalizer = undefined; + } else if (state.finalizers !== undefined) { + state.finalizers.delete(key); + } + } +}; +/** @internal */ +const scopeFinalizerCountUnsafe = scope => scope.state._tag !== "Open" ? 0 : scope.state.finalizer !== undefined ? 1 : scope.state.finalizers?.size ?? 0; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy = "sequential") => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + state: constScopeEmpty +}); +const constScopeEmpty = { + _tag: "Empty" +}; +/** @internal */ +const scopeMake = finalizerStrategy => sync(() => scopeMakeUnsafe(finalizerStrategy)); +/** @internal */ +const scope = scopeTag; +/** @internal */ +const provideScope = /*#__PURE__*/provideService(scopeTag); +/** @internal */ +const scoped = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.context; + const scope = scopeMakeUnsafe(); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, scopeTag, scope)); + return onExitPrimitive(self, exit => { + fiber.setContext(prev); + return scopeCloseUnsafe(scope, exit); + }); +}); +/** @internal */ +const scopeUse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => onExit(provideScope(self, scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_))); +/** @internal */ +const scopedWith = f => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +/** @internal */ +const acquireRelease = (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)))))); +/** @internal */ +const addFinalizer = finalizer => flatMap(scope, scope => contextWith(context => scopeAddFinalizerExit(scope, exit => provideContext(finalizer(exit), context)))); +/** @internal */ +const onExitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "OnExit", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2][0]; + }, + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible && this[_core_js__rspack_import_0/* .args */.a2][2] !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(eff, _ => exit) : exit; + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(combineFinalizerCause(exit, eff), _ => exit) : exit; + } +}); +/** @internal */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, onExitPrimitive); +/** @internal */ +const ensuring = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onExit(self, _ => finalizer)); +/** @internal */ +const onExitIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExit(self, exit => { + if (!predicate(exit)) { + return void_; + } + return f(exit); +})); +/** @internal */ +const onExitFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + const b = filter(exit); + return _Result_js__rspack_import_3/* .isFailure */.N6(b) ? void_ : f(b.success, exit); +})); +/** @internal */ +const onError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => onExitFilter(self, exitFilterCause, f)); +/** @internal */ +const onErrorIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExitIf(self, exit => { + if (exit._tag !== "Failure") { + return false; + } + return predicate(exit.cause); +}, exit => f(exit.cause))); +/** @internal */ +const onErrorFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + if (exit._tag !== "Failure") { + return void_; + } + const result = filter(exit.cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? void_ : f(result.success, exit.cause); +})); +/** @internal */ +const onInterrupt = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onErrorFilter(causeFilterInterruptors, finalizer)(self)); +/** @internal */ +const acquireUseRelease = (acquire, use, release) => uninterruptibleMask(restore => flatMap(acquire, a => onExitPrimitive(restore(use(a)), exit => release(a, exit), true))); +/** @internal */ +const acquireDisposable = acquire => acquireRelease(acquire, resource => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(resource, Symbol.asyncDispose) ? promise(() => resource[Symbol.asyncDispose]()) : sync(() => resource[Symbol.dispose]())); +// ---------------------------------------------------------------------------- +// Caching +// ---------------------------------------------------------------------------- +/** @internal */ +const cachedInvalidateWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, ttl) => sync(() => { + const ttlMillis = _Duration_js__rspack_import_20/* .toMillis */.kE(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(ttl)); + const isFinite = Number.isFinite(ttlMillis); + const latch = makeLatchUnsafe(false); + let expiresAt = 0; + let running = false; + let exit; + const wait = flatMap(latch.await, () => exit); + return [(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const clock = fiber.getRef(ClockRef); + const now = isFinite ? clock.currentTimeMillisUnsafe() : 0; + if (running || now < expiresAt) return exit ?? wait; + running = true; + latch.closeUnsafe(); + exit = undefined; + return onExit(self, exit_ => sync(() => { + running = false; + expiresAt = clock.currentTimeMillisUnsafe() + ttlMillis; + exit = exit_; + latch.openUnsafe(); + })); + }), sync(() => { + expiresAt = 0; + latch.closeUnsafe(); + exit = undefined; + })]; +})); +/** @internal */ +const cachedWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, timeToLive) => map(cachedInvalidateWithTTL(self, timeToLive), tuple => tuple[0])); +/** @internal */ +const cached = self => cachedWithTTL(self, _Duration_js__rspack_import_20/* .infinity */.Tn); +// ---------------------------------------------------------------------------- +// interruption +// ---------------------------------------------------------------------------- +/** @internal */ +const interrupt = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => failCause(causeInterrupt(fiber.id))); +/** @internal */ +const uninterruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptible = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "SetInterruptible", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + fiber.interruptible = this[_core_js__rspack_import_0/* .args */.a2]; + 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); +}; +/** @internal */ +const interruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return self; + return setFiberInterruptible(fiber) ?? self; +}); +/** @internal */ +const uninterruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return f(interruptible); +}); +/** @internal */ +const interruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + const interrupted = setFiberInterruptible(fiber); + const effect = f(uninterruptible); + return interrupted ?? effect; +}); +/** @internal */ +const abortSignal = /*#__PURE__*/map(/*#__PURE__*/acquireRelease(/*#__PURE__*/sync(() => new AbortController()), controller => sync(() => controller.abort())), _ => _.signal); +// ======================================================================== +// collecting & elements +// ======================================================================== +/** @internal */ +const all = (arg, options) => { + if ((0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(arg)) { + return options?.mode === "result" ? forEach(arg, result, options) : forEach(arg, _Function_js__rspack_import_6/* .identity */.D_, options); + } else if (options?.discard) { + return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), _Function_js__rspack_import_6/* .identity */.D_, options); + } + return suspend(() => { + const out = {}; + return as(forEach(Object.entries(arg), ([key, effect]) => map(options?.mode === "result" ? result(effect) : effect, value => { + _record_js__rspack_import_21/* .assignProperty */.x(out, key, value); + }), { + discard: true, + concurrency: options?.concurrency + }), out); + }); +}; +/** @internal */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => map(forEach(elements, (a, i) => result(f(a, i)), options), results => _Array_js__rspack_import_7/* .partition */.jB(results, _Function_js__rspack_import_6/* .identity */.D_))); +/** @internal */ +const reduce = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (elements, zero, f) => { + const arr = _Array_js__rspack_import_7/* .fromIterable */.Ts(elements); + if (arr.length === 0) return sync(zero); + return suspend(() => { + let index = 0; + let state = zero(); + return map(whileLoop({ + while: () => index < arr.length, + body: () => f(state, arr[index], index), + step(next) { + state = next; + index++; + } + }), () => state); + }); +}); +/** @internal */ +const validate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => flatMap(partition(elements, f, { + concurrency: options?.concurrency +}), ([excluded, satisfying]) => { + if (_Array_js__rspack_import_7/* .isArrayNonEmpty */.CZ(excluded)) { + return fail(excluded); + } + return options?.discard ? void_ : succeed(satisfying); +})); +/** @internal */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, 0, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstLoop = (iterator, index, predicate, value) => flatMap(predicate(value, index), keep => { + if (keep) { + return succeed(_Option_js__rspack_import_17.some(value)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, index + 1, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const findFirstFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, 0, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstFilterLoop = (iterator, index, filter, value) => flatMap(filter(value, index), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + return succeed(_Option_js__rspack_import_17.some(result.success)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, index + 1, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const whileLoop = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "While", + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + this[_core_js__rspack_import_0/* .args */.a2].step(value); + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrencyOption = options?.concurrency ?? 1; + const concurrency = concurrencyOption === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrencyOption); + if (concurrency === 1) { + return forEachSequential(iterable, f, options); + } + const items = _Array_js__rspack_import_7/* .fromIterable */.Ts(iterable); + let length = items.length; + if (length === 0) { + return options?.discard ? void_ : succeed([]); + } + const out = options?.discard ? undefined : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { + concurrency + }); + return eff ? as(eff, out) : succeed(out); +})); +/** @internal */ +const head = self => flatMap(self, elements => { + const result = elements[Symbol.iterator]().next(); + return result.done ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(result.value); +}); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? undefined : []; + 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); +}); +const iterateEagerImpl = options => { + const onItem = options.onItem; + const step = options.step; + const runSequential = (state, items, index, end) => { + for (; index < end; index++) { + const item = items[index]; + const effect = onItem(state, item, index); + if (!effectIsExit(effect)) { + return flatMap(exit(effect), itemExit => step(state, item, itemExit, index) ?? runSequential(state, items, index + 1, end) ?? void_); + } + const terminal = step(state, item, effect, index); + if (terminal) return terminal._tag === "Failure" ? terminal : undefined; + } + }; + return (state, items, opts) => { + let index = 0; + const end = opts?.end ?? items.length; + const concurrency = opts?.concurrency ?? 1; + if (concurrency === 1) { + return runSequential(state, items, 0, end); + } + const orderedStep = opts?.orderedStep === true; + let done = false; + let parentFiber; + let fibers; + let resume; + let interrupted = false; + let terminal; + let effect; + let nextIndex = index; + const exits = orderedStep ? new Array(end) : undefined; + const failDefect = error => { + const defect = (0,_core_js__rspack_import_0/* .exitDie */.V2)(error); + terminal = defect; + done = true; + interrupted = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => defect) : defect; + }; + const runStep = (item, exit, currentIndex) => { + if (!orderedStep) return step(state, item, exit, currentIndex); + if (terminal) return terminal; + exits[currentIndex] = exit; + while (nextIndex < end) { + const nextExit = exits[nextIndex]; + if (nextExit === undefined) return; + exits[nextIndex] = undefined; + const index = nextIndex++; + const result = step(state, items[index], nextExit, index); + if (result) return result; + } + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + // fast case (already an exit) + if (effectIsExit(eff)) { + terminal = runStep(item, eff, index); + if (terminal) break; + // We have an effect, so enter "async" mode + } else if (!parentFiber) { + return callback(cb => { + parentFiber = getCurrentFiber(); + fibers = 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; + interrupted = true; + return fibers ? fiberInterruptAll(fibers) : void_; + }); + }); + // Fork the effect with concurrency > 1 + } else { + // Clear the temporary effect from capturing the parentFiber + effect = undefined; + const fiber = forkUnsafe(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = runStep(item, fiber._exit, index); + if (terminal) break; + continue; + } + // Add the fiber to the Set + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver(exit => { + fibers.delete(fiber); + try { + if (terminal) { + if (!interrupted && exit._tag === "Failure") { + for (const reason of exit.cause.reasons) { + if (reason._tag === "Interrupt") continue;else if (terminal._tag === "Failure") { + ; + terminal.cause.reasons.push(reason); + } else { + terminal = (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)([reason])); + } + } + } + } else { + const result = runStep(item, exit, currentIndex); + if (result) { + terminal = result._tag === "Failure" ? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(result.cause.reasons.slice())) : 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)); + } + }); + // Check if we have reached the concurrency limit + 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(); + }; +}; +/** @internal */ +const iterateEager = () => iterateEagerImpl; +const forEachConcurrent = /*#__PURE__*/iterateEagerImpl({ + 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 filterOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, orElse) => flatMap(self, a => predicate(a) ? succeed(a) : orElse(a))); +/** @internal */ +const filterMapOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, orElse) => flatMap(self, a => { + const result = filter(a); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? orElse(result.failure) : succeed(result.success); +})); +/* @internal */ +const filterMapOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, orFailWith) => filterMapOrElse(self, filter, orFailWith ? x => fail(orFailWith(x)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate, options) => suspend(() => { + const out = []; + return as(forEach(elements, (a, i) => { + const result = predicate(a, i); + if (typeof result === "boolean") { + if (result) out.push(a); + return void_; + } + return map(result, keep => { + if (keep) { + out.push(a); + } + }); + }, { + discard: true, + concurrency: options?.concurrency + }), out); +})); +/** @internal */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const out = []; + for (const a of elements) { + const result = filter(a); + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + } + return succeed(out); +})); +/** @internal */ +const filterMapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter, options) => suspend(() => { + const out = []; + return as(forEach(elements, a => map(filter(a), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + }), { + discard: true, + concurrency: options?.concurrency + }), out); +})); +// ---------------------------------------------------------------------------- +// do notation +// ---------------------------------------------------------------------------- +/** @internal */ +const Do = /*#__PURE__*/succeed({}); +/** @internal */ +const bindTo = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bindTo */.Jr(map); +/** @internal */ +const bind = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bind */.oI(map, flatMap); +/** @internal */ +const let_ = /*#__PURE__*/_doNotation_js__rspack_import_22/* .let_ */.zM(map); +/** @internal */ + +// ---------------------------------------------------------------------------- +// fibers & forking +// ---------------------------------------------------------------------------- +/** @internal */ +const forkChild = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + interruptChildrenPatch(); + return succeed(forkUnsafe(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false)); +})); +/** @internal */ +const forkUnsafe = (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 (immediate) { + child.evaluate(effect); + } else { + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + if (!daemon && !child._exit) { + parentRuntime.children().add(child); + child.addObserver(() => parentRuntime._children.delete(child)); + } + return child; +}; +/** @internal */ +const forkDetach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(forkUnsafe(fiber, self, options?.startImmediately, true, options?.uninterruptible)))); +/** @internal */ +const awaitAllChildren = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const initialChildren = fiber._children && new Set(fiber._children); + return onExit(self, _ => { + let children = fiber._children; + if (children === undefined || children.size === 0) { + return void_; + } else if (initialChildren) { + children = _Iterable_js__rspack_import_23/* .filter */.pb(children, child => !initialChildren.has(child)); + } + return asVoid(fiberAwaitAll(children)); + }); +}); +/** @internal */ +const forkIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, scope, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + if (!fiber._exit) { + if (scope.state._tag !== "Closed") { + const key = {}; + const finalizer = () => withFiberId(interruptor => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); + scopeAddFinalizerUnsafe(scope, key, finalizer); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + } else { + fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); + } + } + return succeed(fiber); +})); +/** @internal */ +const forkScoped = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => flatMap(scope, scope => forkIn(self, scope, options))); +// ---------------------------------------------------------------------------- +// execution +// ---------------------------------------------------------------------------- +/** @internal */ +const runForkWith = context => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? _Context_js__rspack_import_5/* .add */.WQ(context, _Scheduler_js__rspack_import_13/* .Scheduler */._F, 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 fiberRunIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => { + if (self._exit) { + return self; + } else if (scope.state._tag === "Closed") { + self.interruptUnsafe(self.id); + return self; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, () => fiberInterrupt(self)); + self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + return self; +}); +/** @internal */ +const runFork = /*#__PURE__*/runForkWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runCallbackWith = context => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + if (options?.onExit) { + fiber.addObserver(options.onExit); + } + return interruptor => { + return fiber.interruptUnsafe(interruptor); + }; + }; +}; +/** @internal */ +const runCallback = /*#__PURE__*/runCallbackWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 runPromiseExit = /*#__PURE__*/runPromiseExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runPromiseWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runSyncExitWith = context => { + const runFork = runForkWith(context); + return effect => { + if (effectIsExit(effect)) return effect; + const scheduler = new _Scheduler_js__rspack_import_13/* .MixedScheduler */.FG("sync"); + const fiber = runFork(effect, { + scheduler + }); + fiber._dispatcher?.flush(); + return fiber._exit ?? (0,_core_js__rspack_import_0/* .exitDie */.V2)(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncExit = /*#__PURE__*/runSyncExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runSyncWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +const succeedTrue = /*#__PURE__*/succeed(true); +const succeedFalse = /*#__PURE__*/succeed(false); +class Latch { + waiters = []; + scheduled = undefined; + _isOpen; + constructor(isOpen) { + this._isOpen = isOpen; + } + scheduleUnsafe(fiber) { + if (this.waiters.length === 0) { + return succeedTrue; + } + if (this.scheduled === undefined) { + this.scheduled = this.waiters; + fiber.currentDispatcher.scheduleTask(this.flushScheduled, 0); + } else { + for (let i = 0; i < this.waiters.length; i++) { + this.scheduled.push(this.waiters[i]); + } + } + this.waiters = []; + return succeedTrue; + } + flushScheduled = () => { + if (this.scheduled === undefined) return; + const waiters = this.scheduled; + this.scheduled = undefined; + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + }; + flushWaiters() { + // swap both arrays out before any resume runs: a resumed waiter can + // reentrantly close the latch and register new waiters, which must not + // be drained by this flush + const waiters = this.waiters; + this.waiters = []; + this.flushScheduled(); + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + } + open = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (this._isOpen) return succeedFalse; + this._isOpen = true; + return this.scheduleUnsafe(fiber); + }); + release = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => this._isOpen ? succeedFalse : this.scheduleUnsafe(fiber)); + openUnsafe() { + if (this._isOpen) return false; + this._isOpen = true; + this.flushWaiters(); + return true; + } + await = /*#__PURE__*/callback(resume => { + if (this._isOpen) { + return resume(void_); + } + this.waiters.push(resume); + return sync(() => { + let index = this.waiters.indexOf(resume); + if (index !== -1) { + this.waiters.splice(index, 1); + } else if (this.scheduled !== undefined) { + index = this.scheduled.indexOf(resume); + if (index !== -1) { + this.scheduled.splice(index, 1); + } + } + }); + }); + closeUnsafe() { + if (!this._isOpen) return false; + this._isOpen = false; + return true; + } + close = /*#__PURE__*/sync(() => this.closeUnsafe()); + whenOpen = self => flatMap(this.await, () => self); + isOpen() { + return this._isOpen; + } +} +/** @internal */ +const makeLatchUnsafe = open => new Latch(open ?? false); +/** @internal */ +const makeLatch = open => sync(() => makeLatchUnsafe(open)); +// ---------------------------------------------------------------------------- +// Tracer +// ---------------------------------------------------------------------------- +/** @internal */ +const tracer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh))); +/** @internal */ +const withTracer = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (effect, tracer) => provideService(effect, _Tracer_js__rspack_import_14/* .Tracer */.sh, tracer)); +/** @internal */ +const withTracerEnabled = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerEnabled */.rf); +/** @internal */ +const withTracerTiming = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); +const bigint0 = /*#__PURE__*/BigInt(0); +const NoopSpanProto = { + _tag: "Span", + spanId: "noop", + traceId: "noop", + sampled: false, + status: { + _tag: "Ended", + startTime: bigint0, + endTime: bigint0, + exit: exitVoid + }, + attributes: /*#__PURE__*/new Map(), + links: [], + kind: "internal", + attribute() {}, + event() {}, + end() {}, + addLinks() {} +}; +/** @internal */ +const noopSpan = options => Object.assign(Object.create(NoopSpanProto), options); +const filterDisablePropagation = span => { + if (!span) return _Option_js__rspack_import_17.none(); + return _Context_js__rspack_import_5/* .get */.Jt(span.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW) ? span._tag === "Span" ? filterDisablePropagation(_Option_js__rspack_import_17.getOrUndefined(span.parent)) : _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(span); +}; +/** @internal */ +const makeSpanUnsafe = (fiber, name, options) => { + const disablePropagation = !fiber.getRef(_references_js__rspack_import_15/* .TracerEnabled */.rf) || options?.annotations && _Context_js__rspack_import_5/* .get */.Jt(options.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW); + const parent = options?.parent !== undefined ? _Option_js__rspack_import_17.some(options.parent) : options?.root ? _Option_js__rspack_import_17.none() : filterDisablePropagation(fiber.currentSpan); + let span; + if (disablePropagation) { + span = noopSpan({ + name, + parent, + annotations: _Context_js__rspack_import_5/* .add */.WQ(options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), _Tracer_js__rspack_import_14/* .DisablePropagation */.DW, true) + }); + } else { + const tracer = fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + const annotationsFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanAnnotations */.ce); + const linksFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanLinks */.ls); + const level = options?.level ?? fiber.getRef(_Tracer_js__rspack_import_14/* .CurrentTraceLevel */.pX); + const links = options?.links !== undefined ? [...linksFromEnv, ...options.links] : linksFromEnv.length === 0 ? [] : linksFromEnv.slice(); + span = tracer.span({ + name, + parent, + annotations: options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), + links, + startTime: timingEnabled ? clock.currentTimeNanosUnsafe() : BigInt(0), + kind: options?.kind ?? "internal", + root: options?.root ?? _Option_js__rspack_import_17.isNone(parent), + sampled: options?.sampled ?? (_Option_js__rspack_import_17.isSome(parent) && parent.value.sampled === false ? false : !isLogLevelGreaterThan(fiber.getRef(_Tracer_js__rspack_import_14/* .MinimumTraceLevel */.EW), level)) + }); + for (const key in annotationsFromEnv) { + span.attribute(key, annotationsFromEnv[key]); + } + if (options?.attributes !== undefined) { + for (const key in options.attributes) { + span.attribute(key, options.attributes[key]); + } + } + } + return span; +}; +/** @internal */ +const makeSpan = (name, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(makeSpanUnsafe(fiber, name, options))); +/** @internal */ +const makeSpanScoped = (name, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const scope = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag); + const span = makeSpanUnsafe(fiber, name, options ?? {}); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return as(scopeAddFinalizerExit(scope, exit => endSpan(span, exit, clock, timingEnabled)), span); +})); +/** @internal */ +const withSpanScoped = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); + } + return self => flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : _Function_js__rspack_import_6/* .constUndefined */.MN; + return updateService(_references_js__rspack_import_15/* .CurrentStackFrame */.vA, parent => ({ + name, + stack, + parent + })); +}; +/** @internal */ +const spanAnnotations = _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce; +/** @internal */ +const spanLinks = _references_js__rspack_import_15/* .TracerSpanLinks */.ls; +/** @internal */ +const linkSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, span, attributes = {}) => { + const spans = Array.isArray(span) ? span : [span]; + const links = spans.map(span => ({ + span, + attributes + })); + return updateService(self, _references_js__rspack_import_15/* .TracerSpanLinks */.ls, current => [...current, ...links]); +}); +/** @internal */ +const endSpan = (span, exit, clock, timingEnabled) => sync(() => { + if (span.status._tag === "Ended") return; + span.end(timingEnabled ? clock.currentTimeNanosUnsafe() : bigint0, exit); +}); +/** @internal */ +const useSpan = (name, ...args) => { + const options = args.length === 1 ? undefined : args[0]; + const evaluate = args[args.length - 1]; + return (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = makeSpanUnsafe(fiber, name, options); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return onExit((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(span)), exit => endSpan(span, exit, clock, timingEnabled)); + }); +}; +const provideParentSpan = /*#__PURE__*/provideService(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +/** @internal */ +const withParentSpan = function () { + const dataFirst = (0,_core_js__rspack_import_0/* .isEffect */.yw)(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = _Function_js__rspack_import_6/* .identity */.D_; + if (span._tag === "Span") { + options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + if (dataFirst) { + return provideParentSpan(provideStackFrame(arguments[0]), span); + } + return self => provideParentSpan(provideStackFrame(self), span); +}; +/** @internal */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const traceOptions = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(arguments[2]); + if (dataFirst) { + const self = arguments[0]; + return useSpan(name, arguments[2], span => withParentSpan(self, span, traceOptions)); + } + const fnArg = typeof arguments[1] === "function" ? arguments[1] : undefined; + const options = fnArg ? undefined : arguments[1]; + return (self, ...args) => useSpan(name, fnArg ? fnArg(...args) : options, span => withParentSpan(self, span, traceOptions)); +}; +/** @internal */ +const annotateSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (effect, ...args) => updateService(effect, _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + _record_js__rspack_import_21/* .assignProperty */.x(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})); +/** @internal */ +const annotateCurrentSpan = (...args) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + if (span) { + if (args.length === 1) { + for (const [key, value] of Object.entries(args[0])) { + span.attribute(key, value); + } + } else { + span.attribute(args[0], args[1]); + } + } + return void_; +}); +/** @internal */ +const currentSpan = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + return span ? succeed(span) : fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()); +}); +/** @internal */ +const currentParentSpan = /*#__PURE__*/serviceOptional(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +// ---------------------------------------------------------------------------- +// Clock +// ---------------------------------------------------------------------------- +/** @internal */ +const ClockRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Clock", { + defaultValue: () => new ClockImpl() +}); +const MAX_TIMER_MILLIS = 2 ** 31 - 1; +class ClockImpl { + currentTimeMillisUnsafe() { + return Date.now(); + } + currentTimeMillis = /*#__PURE__*/sync(() => this.currentTimeMillisUnsafe()); + currentTimeNanosUnsafe() { + return wallTimeNanos(); + } + currentTimeNanos = /*#__PURE__*/sync(() => this.currentTimeNanosUnsafe()); + monotonicTimeNanosUnsafe() { + return monotonicNowNanos(); + } + monotonicTimeNanos = /*#__PURE__*/sync(() => this.monotonicTimeNanosUnsafe()); + sleep(duration) { + return this.sleepMillis(_Duration_js__rspack_import_20/* .toMillis */.kE(duration)); + } + sleepMillis(millis) { + if (millis <= 0) return yieldNow;else if (!Number.isFinite(millis)) return never; + return callback(resume => { + const continuation = millis > MAX_TIMER_MILLIS ? this.sleepMillis(millis - MAX_TIMER_MILLIS) : void_; + const handle = setTimeout(() => resume(continuation), Math.min(millis, MAX_TIMER_MILLIS)); + return sync(() => clearTimeout(handle)); + }); + } +} +const nanosPerMilli = /*#__PURE__*/BigInt(1_000_000); +const monotonicNowNanos = /*#__PURE__*/function () { + const processHrtime = globalThis.process?.hrtime; + if (typeof processHrtime?.bigint === "function") { + return () => processHrtime.bigint(); + } + if (typeof performance !== "undefined" && typeof performance.now === "function") { + return () => BigInt(Math.round(performance.now() * 1_000_000)); + } + let previous = /*#__PURE__*/BigInt(0); + return () => { + const current = BigInt(Date.now()) * nanosPerMilli; + if (current > previous) { + previous = current; + } + return previous; + }; +}(); +const wallTimeNanos = /*#__PURE__*/function () { + const reanchorThresholdNanos = /*#__PURE__*/BigInt(1_000_000_000); + let origin; + return () => { + const monotonic = monotonicNowNanos(); + const wall = BigInt(Date.now()) * nanosPerMilli; + if (origin === undefined) { + origin = wall - monotonic; + } else { + const projected = origin + monotonic; + const skew = wall > projected ? wall - projected : projected - wall; + if (skew > reanchorThresholdNanos) { + origin = wall - monotonic; + } + } + return origin + monotonic; + }; +}(); +/** @internal */ +const clockWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.getRef(ClockRef))); +/** @internal */ +const sleep = duration => clockWith(clock => clock.sleep(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(duration))); +/** @internal */ +const currentTimeMillis = /*#__PURE__*/clockWith(clock => clock.currentTimeMillis); +/** @internal */ +const currentTimeNanos = /*#__PURE__*/clockWith(clock => clock.currentTimeNanos); +/** @internal */ +const monotonicTimeNanos = /*#__PURE__*/clockWith(clock => clock.monotonicTimeNanos); +// ---------------------------------------------------------------------------- +// Errors +// ---------------------------------------------------------------------------- +/** @internal */ +const TimeoutErrorTypeId = "~effect/Cause/TimeoutError"; +/** @internal */ +const isTimeoutError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, TimeoutErrorTypeId); +/** @internal */ +class TimeoutError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("TimeoutError") { + [TimeoutErrorTypeId] = TimeoutErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const IllegalArgumentErrorTypeId = "~effect/Cause/IllegalArgumentError"; +/** @internal */ +const isIllegalArgumentError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, IllegalArgumentErrorTypeId); +/** @internal */ +class IllegalArgumentError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("IllegalArgumentError") { + [IllegalArgumentErrorTypeId] = IllegalArgumentErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const ExceededCapacityErrorTypeId = "~effect/Cause/ExceededCapacityError"; +/** @internal */ +const isExceededCapacityError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, ExceededCapacityErrorTypeId); +/** @internal */ +class ExceededCapacityError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("ExceededCapacityError") { + [ExceededCapacityErrorTypeId] = ExceededCapacityErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +const isAsyncFiberError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, AsyncFiberErrorTypeId); +/** @internal */ +class AsyncFiberError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("AsyncFiberError") { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +} +/** @internal */ +const UnknownErrorTypeId = "~effect/Cause/UnknownError"; +/** @internal */ +const isUnknownError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, UnknownErrorTypeId); +/** @internal */ +class UnknownError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("UnknownError") { + [UnknownErrorTypeId] = UnknownErrorTypeId; + constructor(cause, message) { + super({ + message, + cause + }); + } +} +// ---------------------------------------------------------------------------- +// Console +// ---------------------------------------------------------------------------- +/** @internal */ +const ConsoleRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Console/CurrentConsole", { + defaultValue: () => globalThis.console +}); +// ---------------------------------------------------------------------------- +// LogLevel +// ---------------------------------------------------------------------------- +/** @internal */ +const logLevelToOrder = level => { + switch (level) { + case "All": + return Number.MIN_SAFE_INTEGER; + case "Fatal": + return 50_000; + case "Error": + return 40_000; + case "Warn": + return 30_000; + case "Info": + return 20_000; + case "Debug": + return 10_000; + case "Trace": + return 0; + case "None": + return Number.MAX_SAFE_INTEGER; + } +}; +/** @internal */ +const LogLevelOrder = /*#__PURE__*/_Order_js__rspack_import_24/* .mapInput */.zQ(_Order_js__rspack_import_24/* .Number */.wN, logLevelToOrder); +/** @internal */ +const isLogLevelGreaterThan = /*#__PURE__*/_Order_js__rspack_import_24/* .isGreaterThan */.yJ(LogLevelOrder); +// ---------------------------------------------------------------------------- +// Logger +// ---------------------------------------------------------------------------- +/** @internal */ +const CurrentLoggers = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Loggers/CurrentLoggers", { + defaultValue: () => new Set([defaultLogger, tracerLogger]) +}); +/** @internal */ +const LogToStderr = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Logger/LogToStderr", { + defaultValue: _Function_js__rspack_import_6/* .constFalse */.f4 +}); +/** @internal */ +const annotateLogsScoped = function () { + const entries = typeof arguments[0] === "string" ? [[arguments[0], arguments[1]]] : Object.entries(arguments[0]); + return uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...prev + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + _record_js__rspack_import_21/* .assignProperty */.x(next, key, value); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...current + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + if (current[key] !== value) continue; + if (Object.hasOwn(prev, key)) { + _record_js__rspack_import_21/* .assignProperty */.x(next, key, prev[key]); + } else { + delete next[key]; + } + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return void_; + }); + })); +}; +/** @internal */ +const LoggerTypeId = "~effect/Logger"; +const LoggerProto = { + [LoggerTypeId]: { + _Message: _Function_js__rspack_import_6/* .identity */.D_, + _Output: _Function_js__rspack_import_6/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } +}; +/** @internal */ +const loggerMake = log => { + const self = Object.create(LoggerProto); + self.log = log; + return self; +}; +/** + * Sanitize a given string by replacing spaces, equal signs, and double quotes + * with underscores. + * + * @internal + */ +const formatLabel = key => key.replace(/[\s="]/g, "_"); +/** + * Formats a log span into a ``. + * + * **Example** (Normalizing input) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.ensure("a") // => ["a"] + * Array.ensure(["a", "b", "c"]) // => ["a", "b", "c"] + * ``` + * + * @see {@link of} — always wrap in a single-element array + * @see {@link fromIterable} — convert any iterable + * + * @category constructors + * @since 3.3.0 + */ +const ensure = self => Array.isArray(self) ? self : [self]; +/** + * Converts a record into an array of `[key, value]` tuples. + * + * **When to use** + * + * Use to convert a record into an array of key-value tuples for iteration or + * transformation. + * + * **Details** + * + * Key order follows `Object.entries` semantics. Empty records produce an empty + * array. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromRecord({ a: 1, b: 2, c: 3 }) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @see {@link Record.toEntries} the equivalent function from the Record module + * @see {@link Record.fromEntries} to build a record from an array of tuples + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = _Record_js__rspack_import_0/* .toEntries */.Wo; +/** + * Converts an `Option` to an array: `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use to convert a single `Option` into an array for downstream array operations. + * + * **Example** (Converting an Option to an array) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.fromOption(Option.some(1)) // => [1] + * Array.fromOption(Option.none()) // => [] + * ``` + * + * @see {@link getSomes} — extract `Some` values from an array of Options + * + * @category converting + * @since 2.0.0 + */ +const fromOption = _Option_js__rspack_import_1.toArray; +/** + * Pattern-matches on an array, handling empty and non-empty cases separately. + * + * **When to use** + * + * Use when you need to branch on whether an array is empty. + * + * **Details** + * + * `onNonEmpty` receives a `NonEmptyReadonlyArray`. Supports both data-first and + * data-last usage. + * + * **Example** (Branching on emptiness) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const describe = Array.match({ + * onEmpty: () => "empty", + * onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}` + * }) + * + * describe([]) // => "empty" + * describe([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link matchLeft} — destructures into head + tail + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(self) : onEmpty()))); +/** + * Pattern-matches on an array from the left, providing the first element and + * the remaining elements separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * first element plus the remaining elements. + * + * **Details** + * + * `onNonEmpty` receives `(head, tail)` where `tail` is the rest of the array. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchLeft = Array.matchLeft({ + * onEmpty: () => "empty", + * onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}` + * }) + * + * matchLeft([]) // => "empty" + * matchLeft([1, 2, 3]) // => "head: 1, tail: 2" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchRight} — destructures into init + last + * + * @category pattern matching + * @since 2.0.0 + */ +const matchLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(headNonEmpty(self), tailNonEmpty(self)) : onEmpty()))); +/** + * Pattern-matches on an array from the right, providing all elements except the + * last and the last element separately. + * + * **When to use** + * + * Use when you need to branch on an array and handle the non-empty case as the + * elements before the last plus the last element. + * + * **Details** + * + * `onNonEmpty` receives `(init, last)` where `init` is everything but the last element. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const matchRight = Array.matchRight({ + * onEmpty: () => "empty", + * onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}` + * }) + * + * matchRight([]) // => "empty" + * matchRight([1, 2, 3]) // => "init: 2, last: 3" + * ``` + * + * @see {@link match} — receives the full non-empty array + * @see {@link matchLeft} — destructures into head + tail + * + * @category pattern matching + * @since 2.0.0 + */ +const matchRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onEmpty, + onNonEmpty +}) => isReadonlyArrayNonEmpty(self) ? onNonEmpty(initNonEmpty(self), lastNonEmpty(self)) : onEmpty()))); +/** + * Adds a single element to the front of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * leading value. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prepend([2, 3, 4], 1) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add to the end + * @see {@link prependAll} — prepend multiple elements + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => [head, ...self]))); +/** + * Prepends all elements from a prefix iterable to the front of an array. + * + * **When to use** + * + * Use to prepend multiple elements from an iterable to the front of an array. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Prepending multiple elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.prependAll([2, 3], [0, 1]) // => [0, 1, 2, 3] + * ``` + * + * @see {@link prepend} — add a single element to the front + * @see {@link appendAll} — add elements to the end + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => fromIterable(that).concat(fromIterable(self))))); +/** + * Adds a single element to the end of an iterable, returning a `NonEmptyArray`. + * + * **When to use** + * + * Use when you need to guarantee a non-empty result after adding a required + * trailing value. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.append([1, 2, 3], 4) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} — add to the front + * @see {@link appendAll} — append multiple elements + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => [...self, last]))); +/** + * Concatenates two iterables into a single array. + * + * **When to use** + * + * Use to combine two iterable inputs into a new array with the second input's + * elements after the first. + * + * **Details** + * + * If either input is non-empty, the result is a `NonEmptyArray`. + * + * **Example** (Concatenating arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.appendAll([1, 2], [3, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link append} — add a single element to the end + * @see {@link prependAll} — add elements to the front + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => fromIterable(self).concat(fromIterable(that))); +/** + * Folds left-to-right while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator where each intermediate value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it starts with the initial + * value. The result is always a `NonEmptyArray`. Use `reduce` if you only need + * the final accumulated value. + * + * **Example** (Running totals) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [0, 1, 3, 6, 10] + * ``` + * + * @see {@link scanRight} — right-to-left scan + * @see {@link reduce} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const out = [b]; + let i = 0; + for (const a of self) { + out[i + 1] = f(out[i], a); + i++; + } + return out; +}))); +/** + * Folds right-to-left while keeping every intermediate accumulator value. + * + * **When to use** + * + * Use to compute a running accumulator from right to left where each intermediate + * value is needed. + * + * **Details** + * + * The output length is `input.length + 1` because it ends with the initial + * value. The result is always a `NonEmptyArray`. + * + * **Example** (Scanning running totals in reverse) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value) // => [10, 9, 7, 4, 0] + * ``` + * + * @see {@link scan} — left-to-right scan + * @see {@link reduceRight} — fold without intermediate values + * + * @category folding + * @since 2.0.0 + */ +const scanRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + const input = fromIterable(self); + const out = new Array(input.length + 1); + out[input.length] = b; + for (let i = input.length - 1; i >= 0; i--) { + out[i] = f(out[i + 1], input[i]); + } + return out; +}))); +/** + * Checks whether a value is an `Array`. + * + * **When to use** + * + * Use to verify a value is a mutable array, narrowing its type to `Array`. + * + * **Details** + * + * Acts as a type guard narrowing the input to `Array` and delegates to + * `globalThis.Array.isArray`. + * + * **Example** (Type-guarding an unknown value) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArray(null) // => false + * Array.isArray([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayEmpty} — check for an empty array + * @see {@link isArrayNonEmpty} — check for a non-empty array + * + * @category guards + * @since 2.0.0 + */ +const isArray = Array.isArray; +/** + * Checks whether a mutable `Array` is empty, narrowing the type to `[]`. + * + * **Example** (Checking for an empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayEmpty([]) // => true + * Array.isArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isReadonlyArrayEmpty} — readonly variant + * @see {@link isArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayEmpty = self => self.length === 0; +/** + * Checks whether a `ReadonlyArray` is empty, narrowing the type to `readonly []`. + * + * **Example** (Checking for an empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayEmpty([]) // => true + * Array.isReadonlyArrayEmpty([1, 2, 3]) // => false + * ``` + * + * @see {@link isArrayEmpty} — mutable variant + * @see {@link isReadonlyArrayNonEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayEmpty = (/* unused pure expression or super */ null && (isArrayEmpty)); +/** + * Checks whether a mutable `Array` is non-empty, narrowing the type to + * `NonEmptyArray`. + * + * **When to use** + * + * Use when you need the narrowed value to remain a mutable `Array` after proving + * it has at least one element. + * + * **Example** (Checking for a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isArrayNonEmpty([]) // => false + * Array.isArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isReadonlyArrayNonEmpty} — readonly variant + * @see {@link isArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Checks whether a `ReadonlyArray` is non-empty, narrowing the type to + * `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use when you need to prove a readonly array has at least one element without + * requiring mutable array methods afterward. + * + * **Example** (Checking for a non-empty readonly array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.isReadonlyArrayNonEmpty([]) // => false + * Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true + * ``` + * + * @see {@link isArrayNonEmpty} — mutable variant + * @see {@link isReadonlyArrayEmpty} — opposite check + * + * @category guards + * @since 4.0.0 + */ +const isReadonlyArrayNonEmpty = _internal_array_js__rspack_import_3/* .isArrayNonEmpty */.C; +/** + * Returns the number of elements in a `ReadonlyArray`. + * + * **When to use** + * + * Use when you need length as a composable function rather than a property access. + * + * **Example** (Getting the length) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.length([1, 2, 3]) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const length = self => self.length; +/** @internal */ +function isOutOfBounds(i, as) { + return !Number.isFinite(i) || i < 0 || i >= as.length; +} +const clamp = (i, as) => Math.floor(Math.min(Math.max(0, i), as.length)); +/** + * Reads an element at the given index safely, returning `Option.some` or + * `Option.none` if the index is out of bounds. + * + * **When to use** + * + * Use when you need to read an array element by index and handle an + * out-of-bounds index as `Option.none`. + * + * **Details** + * + * The index is floored to an integer. This never throws. + * + * **Example** (Accessing indexes safely) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.get([1, 2, 3], 1) // => Option.some(2) + * Array.get([1, 2, 3], 10) // => Option.none() + * ``` + * + * @see {@link getUnsafe} for indexed access that throws when the index is out of bounds + * @see {@link head} for reading the first element as an `Option` + * @see {@link last} for reading the last element as an `Option` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + return isOutOfBounds(i, self) ? Option.none() : Option.some(self[i]); +}))); +/** + * Reads an element at the given index, throwing if the index is out of bounds. + * + * **When to use** + * + * Use to read an array element at a known valid index when out-of-bounds would + * be a programming error. + * + * **Details** + * + * Throws an `Error` with the message `"Index out of bounds: "`. Prefer + * `get` for safe access. + * + * **Example** (Accessing indexes unsafely) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.getUnsafe([1, 2, 3], 1) // => 2 + * // Array.getUnsafe([1, 2, 3], 10) // throws Error + * ``` + * + * @see {@link get} — safe version returning `Option` + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, index) => { + const i = Math.floor(index); + if (isOutOfBounds(i, self)) { + throw new Error(`Index out of bounds: ${i}`); + } + return self[i]; +}))); +/** + * Splits a non-empty array into its first element and the remaining elements. + * + * **When to use** + * + * Use when you have a `NonEmptyReadonlyArray` and need both its first element + * and the remaining elements as separate values. + * + * **Details** + * + * Returns a tuple `[head, tail]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring head and tail) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unprepend([1, 2, 3, 4]) // => [1, [2, 3, 4]] + * ``` + * + * @see {@link unappend} for splitting a non-empty array into init and last + * @see {@link headNonEmpty} for getting only the first element + * @see {@link tailNonEmpty} for getting only the elements after the first + * + * @category splitting + * @since 2.0.0 + */ +const unprepend = self => [headNonEmpty(self), tailNonEmpty(self)]; +/** + * Splits a non-empty array into all elements except the last, and the last + * element. + * + * **When to use** + * + * Use when you need to split a non-empty array into the elements before the + * last element and the last element. + * + * **Details** + * + * Returns a tuple `[init, last]` and requires a `NonEmptyReadonlyArray`. + * + * **Example** (Destructuring init and last) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unappend([1, 2, 3, 4]) // => [[1, 2, 3], 4] + * ``` + * + * @see {@link unprepend} for splitting a non-empty array into head and tail + * @see {@link initNonEmpty} for getting only the elements before the last + * @see {@link lastNonEmpty} for getting only the last element + * + * @category splitting + * @since 2.0.0 + */ +const unappend = self => [initNonEmpty(self), lastNonEmpty(self)]; +/** + * Returns the first element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the first element of an array that may be empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.head([1, 2, 3]) // => Option.some(1) + * Array.head([]) // => Option.none() + * ``` + * + * @see {@link headNonEmpty} — direct access when array is known non-empty + * @see {@link last} — get the last element + * + * @category getters + * @since 2.0.0 + */ +const head = /*#__PURE__*/(/* unused pure expression or super */ null && (get(0))); +/** + * Returns the first element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the first element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the head of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.headNonEmpty([1, 2, 3, 4]) // => 1 + * ``` + * + * @see {@link head} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const headNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (getUnsafe(0))); +/** + * Returns the last element of an array safely wrapped in `Option.some`, or + * `Option.none` if the array is empty. + * + * **When to use** + * + * Use to safely get the last element of an array that may be empty. + * + * **Example** (Getting the last element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.last([1, 2, 3]) // => Option.some(3) + * Array.last([]) // => Option.none() + * ``` + * + * @see {@link lastNonEmpty} — direct access when array is known non-empty + * @see {@link head} — get the first element + * + * @category getters + * @since 2.0.0 + */ +const last = self => isReadonlyArrayNonEmpty(self) ? Option.some(lastNonEmpty(self)) : Option.none(); +/** + * Returns the last element of a `NonEmptyReadonlyArray` directly (no `Option` + * wrapper). + * + * **When to use** + * + * Use to get the last element without `Option` wrapping when the array is known + * to be non-empty. + * + * **Example** (Getting the last of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.lastNonEmpty([1, 2, 3, 4]) // => 4 + * ``` + * + * @see {@link last} — safe version for possibly-empty arrays + * + * @category getters + * @since 2.0.0 + */ +const lastNonEmpty = self => self[self.length - 1]; +/** + * Returns all elements except the first safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements after the first when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(1)`. Empty inputs return `Option.none()`. + * + * **Example** (Getting the tail) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.tail([1, 2, 3, 4]) // => Option.some([2, 3, 4]) + * Array.tail([]) // => Option.none() + * ``` + * + * @see {@link tailNonEmpty} — when the array is known non-empty + * @see {@link init} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +function tail(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(tailNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the first of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements after the first when the array is known to be non-empty. + * + * **Example** (Getting the tail of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.tailNonEmpty([1, 2, 3, 4]) // => [2, 3, 4] + * ``` + * + * @see {@link tail} — safe version for possibly-empty arrays + * @see {@link initNonEmpty} — all elements except the last + * + * @category getters + * @since 2.0.0 + */ +const tailNonEmpty = self => self.slice(1); +/** + * Returns all elements except the last safely, wrapped in an `Option`. + * + * **When to use** + * + * Use to safely get all elements before the last when the iterable may be empty. + * + * **Details** + * + * Allocates a new array via `slice(0, -1)`. Empty inputs return + * `Option.none()`. + * + * **Example** (Getting init) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.init([1, 2, 3, 4]) // => Option.some([1, 2, 3]) + * Array.init([]) // => Option.none() + * ``` + * + * @see {@link initNonEmpty} — when the array is known non-empty + * @see {@link tail} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +function init(self) { + const as = fromIterable(self); + return isReadonlyArrayNonEmpty(as) ? Option.some(initNonEmpty(as)) : Option.none(); +} +/** + * Returns all elements except the last of a `NonEmptyReadonlyArray`. + * + * **When to use** + * + * Use to get all elements before the last when the array is known to be non-empty. + * + * **Example** (Getting init of a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.initNonEmpty([1, 2, 3, 4]) // => [1, 2, 3] + * ``` + * + * @see {@link init} — safe version for possibly-empty arrays + * @see {@link tailNonEmpty} — all elements except the first + * + * @category getters + * @since 2.0.0 + */ +const initNonEmpty = self => self.slice(0, -1); +/** + * Keeps the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep up to the first `n` elements from an iterable as a new array. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.take([1, 2, 3, 4, 5], 3) // => [1, 2, 3] + * ``` + * + * @see {@link takeRight} for keeping elements from the end + * @see {@link takeWhile} for keeping an initial prefix while a predicate holds + * @see {@link drop} for removing elements from the start + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, clamp(n, input)); +}))); +/** + * Keeps the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the last `n` elements of an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. Returns an empty array when `n <= 0`. + * + * **Example** (Taking from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeRight([1, 2, 3, 4, 5], 3) // => [3, 4, 5] + * ``` + * + * @see {@link take} — keep from the start + * @see {@link dropRight} — remove from the end + * + * @category getters + * @since 2.0.0 + */ +const takeRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + const i = clamp(n, input); + return i === 0 ? [] : input.slice(-i); +}))); +/** + * Takes elements from the start while the predicate holds, stopping at the + * first element that fails. + * + * **When to use** + * + * Use to keep the leading elements of an iterable while each element satisfies + * a predicate, returning the retained prefix as an array. + * + * **Details** + * + * Supports refinements for type narrowing. The predicate receives + * `(element, index)`. + * + * **Example** (Taking while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4) // => [1, 3, 2] + * ``` + * + * @see {@link take} for keeping a fixed number of leading elements + * @see {@link dropWhile} for removing the matching prefix and keeping the rest + * @see {@link span} for splitting the matching prefix from the remaining elements + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + const out = []; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + out.push(a); + i++; + } + return out; +}))); +/** + * Takes elements from the start while a `Filter` succeeds, collecting transformed values. + * + * **When to use** + * + * Use when you need to take a prefix from an iterable while a function can + * successfully extract or transform elements, stopping at the first element + * that produces a failure result. + * + * **Details** + * + * The filter receives `(element, index)` and processing stops at the first + * filter failure. + * + * @see {@link takeWhile} for taking a prefix based on a boolean predicate + * + * @category getters + * @since 4.0.0 + */ +const takeWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + const out = []; + for (const a of self) { + const result = f(a, i); + if (Result.isFailure(result)) { + break; + } + out.push(result.success); + i++; + } + return out; +}))); +const spanIndex = (self, predicate) => { + let i = 0; + for (const a of self) { + if (!predicate(a, i)) { + break; + } + i++; + } + return i; +}; +/** + * Splits an iterable into two arrays: the longest prefix where the predicate + * holds, and the remaining elements. + * + * **When to use** + * + * Use when you need both the longest predicate-matching prefix and the + * remaining elements. + * + * **Details** + * + * Equivalent to `[takeWhile(pred), dropWhile(pred)]`, but more efficient + * because it runs in a single pass. Supports refinements for type narrowing of + * the prefix. + * + * **Example** (Splitting at predicate boundary) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.span([1, 3, 2, 4, 5], (x) => x % 2 === 1) // => [[1, 3], [2, 4, 5]] + * ``` + * + * @see {@link takeWhile} for keeping only the matching prefix + * @see {@link dropWhile} for keeping only the elements after the matching prefix + * @see {@link splitWhere} for splitting at the first element that satisfies a predicate + * + * @category splitting + * @since 2.0.0 + */ +const span = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + return splitAt(input, spanIndex(input, predicate)); +}))); +/** + * Removes the first `n` elements, creating a new array. + * + * **When to use** + * + * Use to keep the suffix of an iterable after skipping a fixed number of + * leading elements. + * + * **Details** + * + * `n` is clamped to `[0, length]`. When `n <= 0`, this returns a copy of the + * full array. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.drop([1, 2, 3, 4, 5], 2) // => [3, 4, 5] + * ``` + * + * @see {@link dropRight} for removing a fixed number of elements from the end + * @see {@link dropWhile} for removing a prefix based on a predicate instead of a fixed count + * @see {@link take} for keeping a fixed number of elements from the start + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(clamp(n, input), input.length); +}))); +/** + * Removes the last `n` elements, creating a new array. + * + * **When to use** + * + * Use to remove the last `n` elements from an iterable. + * + * **Details** + * + * `n` is clamped to `[0, length]`. + * + * **Example** (Dropping from the end) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropRight([1, 2, 3, 4, 5], 2) // => [1, 2, 3] + * ``` + * + * @see {@link drop} — remove from the start + * @see {@link takeRight} — keep from the end + * + * @category getters + * @since 2.0.0 + */ +const dropRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return input.slice(0, input.length - clamp(n, input)); +}))); +/** + * Drops elements from the start while the predicate holds, returning the rest. + * + * **When to use** + * + * Use to remove a leading prefix of elements that satisfy a predicate. + * + * **Details** + * + * The predicate receives `(element, index)`. + * + * **Example** (Dropping while condition holds) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) // => [4, 5] + * ``` + * + * @see {@link takeWhile} — keep the matching prefix instead + * @see {@link drop} — drop a fixed count + * + * @category getters + * @since 2.0.0 + */ +const dropWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (!predicate(input[i], i)) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Drops elements from the start while a `Filter` succeeds. + * + * **When to use** + * + * Use when you need to drop a prefix from an iterable by computing a `Result` + * per element instead of using a simple boolean predicate. + * + * **Details** + * + * The filter receives `(element, index)`. The result contains the remaining + * original elements after the first filter failure. + * + * @see {@link dropWhile} for dropping a prefix with a simple boolean predicate + * @see {@link takeWhileFilter} for keeping only the matching prefix + * + * @category getters + * @since 4.0.0 + */ +const dropWhileFilter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + let i = 0; + while (i < input.length) { + if (Result.isFailure(f(input[i], i))) { + break; + } + i++; + } + return input.slice(i); +}))); +/** + * Returns the index of the first element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the first matching element from the start of an + * iterable. + * + * **Example** (Finding an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstIndex([5, 3, 8, 9], (x) => x > 5) // => Option.some(2) + * ``` + * + * @see {@link findLastIndex} — search from the end + * @see {@link findFirst} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findFirstIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i)) { + return Option.some(i); + } + i++; + } + return Option.none(); +}))); +/** + * Returns the index of the last element matching the predicate, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find the index of the last matching element from the end of an array. + * + * **Example** (Finding the last matching index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLastIndex([1, 3, 8, 9], (x) => x < 5) // => Option.some(1) + * ``` + * + * @see {@link findFirstIndex} — search from the start + * @see {@link findLast} — get the element itself + * + * @category searching + * @since 2.0.0 + */ +const findLastIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + if (predicate(input[i], i)) { + return Option.some(i); + } + } + return Option.none(); +}))); +/** + * Returns the first element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to scan an iterable in iteration order and return the first selected + * element or mapped value as an `Option`. + * + * **Details** + * + * Accepts a predicate `(a, i) => boolean`, a refinement, or a function + * `(a, i) => Option` for simultaneous find-and-transform. If no element + * matches, this returns `Option.none()`. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some(4) + * ``` + * + * @see {@link findLast} — search from the end + * @see {@link findFirstIndex} — get the index instead + * @see {@link findFirstWithIndex} — get both element and index + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _Iterable_js__rspack_import_4/* .findFirst */.i8; +/** + * Returns the first selected value together with its index, wrapped in an + * `Option`. + * + * **When to use** + * + * Use to find both the first matching element and its index in one pass. + * + * **Details** + * + * Accepts a predicate, a refinement, or a function returning `Option`. For an + * `Option`-returning function, returns `[mappedValue, index]` for the first + * `Some`, or `Option.none()` if no element is selected. + * + * **Example** (Finding element with its index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3) // => Option.some([4, 3]) + * ``` + * + * @see {@link findFirst} — get only the element + * @see {@link findFirstIndex} — get only the index + * + * @category searching + * @since 3.17.0 + */ +const findFirstWithIndex = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some([a, i]); + } + } else { + if (Option.isSome(o)) { + return Option.some([o.value, i]); + } + } + i++; + } + return Option.none(); +}))); +/** + * Returns the last element matching a predicate, refinement, or mapping + * function, wrapped in `Option`. + * + * **When to use** + * + * Use to find the last matching element from the end of an array. + * + * **Details** + * + * Searches from the end of the array. If no element matches, this returns + * `Option.none()`. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => Option.some(4) + * ``` + * + * @see {@link findFirst} — search from the start + * @see {@link findLastIndex} — get the index instead + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + for (let i = input.length - 1; i >= 0; i--) { + const a = input[i]; + const o = f(a, i); + if (typeof o === "boolean") { + if (o) { + return Option.some(a); + } + } else { + if (Option.isSome(o)) { + return o; + } + } + } + return Option.none(); +}))); +/** + * Inserts an element at the specified index safely, returning a new `NonEmptyArray` + * wrapped in an `Option`. + * + * **When to use** + * + * Use to insert a single element at a specific position in an array. + * + * **Details** + * + * Valid indices are `0` to `length`, inclusive. Inserting at `length` appends. + * + * **Example** (Inserting at an index) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.insertAt(["a", "b", "c", "e"], 3, "d") // => Option.some(["a", "b", "c", "d", "e"]) + * ``` + * + * @see {@link replace} — replace an existing element + * @see {@link modify} — transform an element at an index + * + * @category transforming + * @since 2.0.0 + */ +const insertAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => { + const out = Array.from(self); // copy because `splice` mutates the array + const index = Math.floor(i); + if (index !== out.length && isOutOfBounds(index, out)) { + return Option.none(); + } + out.splice(index, 0, b); + return Option.some(out); +}))); +/** + * Replaces the element at the specified index safely with a new value, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to set a fixed replacement value at a specific index. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Replacing an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.replace([1, 2, 3], 1, 4) // => Option.some([1, 4, 3]) + * ``` + * + * @see {@link modify} — transform an element with a function + * @see {@link insertAt} — insert without removing + * + * @category transforming + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, b) => modify(self, i, () => b)))); +/** + * Applies a function to the element at the specified index safely, returning the + * updated array in `Option.some`. + * + * **When to use** + * + * Use to derive a replacement value from an array element at a specific index + * while leaving the other elements unchanged. + * + * **Details** + * + * Returns `Option.none()` when the index is out of bounds. + * + * **Example** (Modifying an element) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const values = [1, 2, 3, 4] + * const double = (n: number) => n * 2 + * + * Array.modify(values, 2, double) // => Option.some([1, 2, 6, 4]) + * Array.modify(values, 5, double) // => Option.none() + * ``` + * + * @see {@link replace} — set a fixed value at an index + * @see {@link modifyHeadNonEmpty} — modify the first element + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, i, f) => { + const arr = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, arr)) { + return Option.none(); + } + const out = arr; + const b = f(arr[index]); + out[index] = b; + return Option.some(out); +}))); +/** + * Removes the element at the specified index, returning a new array. If the + * index is out of bounds, returns a copy of the original. + * + * **When to use** + * + * Use when you want a missing index to be a no-op and need a fresh array result + * instead of an optional failure. + * + * **Example** (Removing an element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.remove([1, 2, 3, 4], 2) // => [1, 2, 4] + * Array.remove([1, 2, 3, 4], 5) // => [1, 2, 3, 4] + * ``` + * + * @see {@link insertAt} — insert an element + * @see {@link filter} — remove elements by predicate + * + * @category transforming + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, i) => { + const out = Array.from(self); + const index = Math.floor(i); + if (isOutOfBounds(index, out)) { + return out; + } + out.splice(index, 1); + return out; +}))); +/** + * Reverses an iterable into a new array. + * + * **When to use** + * + * Use to reverse an iterable into a new array without mutating the original + * input. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. + * + * **Example** (Reversing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reverse([1, 2, 3, 4]) // => [4, 3, 2, 1] + * ``` + * + * @category transforming + * @since 2.0.0 + */ +const reverse = self => Array.from(self).reverse(); +/** + * Sorts an array by the given `Order`, returning a new array. + * + * **When to use** + * + * Use to sort an array using a single `Order` comparator. + * + * **Details** + * + * Preserves `NonEmptyArray` in the return type. Use `sortWith` to sort by a + * derived key, or `sortBy` for multi-key sorting. + * + * **Example** (Sorting numbers) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sort([3, 1, 4, 1, 5], Order.Number) // => [1, 1, 3, 4, 5] + * ``` + * + * @see {@link sortWith} — sort by a mapping function + * @see {@link sortBy} — sort by multiple orders + * + * @category sorting + * @since 2.0.0 + */ +const sort = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => { + const out = Array.from(self); + out.sort(O); + return out; +}))); +/** + * Sorts an array by a derived key using a mapping function and an `Order` for + * that key. + * + * **When to use** + * + * Use when you need to sort values by a derived key, such as a string length or + * object field, while keeping the original values. + * + * **Details** + * + * Equivalent to `sort(Order.mapInput(order, f))`, but more convenient. + * + * **Example** (Sorting strings by length) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.sortWith(["aaa", "b", "cc"], (s) => s.length, Order.Number) // => ["b", "cc", "aaa"] + * ``` + * + * @see {@link sort} for sorting with an `Order` that compares the elements directly + * @see {@link sortBy} for sorting with multiple `Order`s applied in sequence + * + * @category sorting + * @since 2.0.0 + */ +const sortWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, f, order) => Array.from(self).map(a => [a, f(a)]).sort(([, a], [, b]) => order(a, b)).map(([_]) => _)))); +/** + * Sorts an array by multiple `Order`s applied in sequence: the first order is + * used first; ties are broken by the second order, and so on. + * + * **When to use** + * + * Use to sort by multiple criteria where later orders break ties from earlier + * ones. + * + * **Details** + * + * This is data-last only and returns a function. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Sorting by multiple keys) + * + * ```ts import.meta.vitest + * import { Array, Order, pipe } from "effect" + * + * const users = [ + * { name: "Alice", age: 30 }, + * { name: "Bob", age: 25 }, + * { name: "Charlie", age: 30 } + * ] + * + * const sortedUsers = pipe( + * users, + * Array.sortBy( + * Order.mapInput(Order.Number, (user: (typeof users)[number]) => user.age), + * Order.mapInput(Order.String, (user: (typeof users)[number]) => user.name) + * ) + * ) + * + * sortedUsers.map((user) => user.name).join(",") // => "Bob,Alice,Charlie" + * ``` + * + * @see {@link sort} — sort by a single `Order` + * @see {@link sortWith} — sort by a derived key + * + * @category sorting + * @since 2.0.0 + */ +const sortBy = (...orders) => { + const sortByAll = sort(Order.combineAll(orders)); + return self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return sortByAll(input); + } + return []; + }; +}; +/** + * Pairs elements from two iterables by position. If the iterables differ in + * length, the extra elements from the longer one are discarded. + * + * **When to use** + * + * Use when you need simple pairs of corresponding elements from two iterables. + * + * **Details** + * + * Returns `NonEmptyArray` when both inputs are non-empty. + * + * **Example** (Zipping two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zip([1, 2, 3], ["a", "b"]) // => [[1, "a"], [2, "b"]] + * ``` + * + * @see {@link zipWith} — zip with a combiner function + * @see {@link unzip} — inverse operation + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Combines elements from two iterables pairwise using a function. If the + * iterables differ in length, extra elements are discarded. + * + * **When to use** + * + * Use when zipping two iterables in an array pipeline and each pair should + * become a computed array element instead of a tuple. + * + * **Example** (Zipping with addition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b) // => [5, 7, 9] + * ``` + * + * @see {@link zip} — zip into tuples + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => { + const as = fromIterable(self); + const bs = fromIterable(that); + if (isReadonlyArrayNonEmpty(as) && isReadonlyArrayNonEmpty(bs)) { + const out = [f(headNonEmpty(as), headNonEmpty(bs))]; + const len = Math.min(as.length, bs.length); + for (let i = 1; i < len; i++) { + out[i] = f(as[i], bs[i]); + } + return out; + } + return []; +}))); +/** + * Splits an array of pairs into two arrays. Inverse of {@link zip}. + * + * **Example** (Unzipping pairs) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unzip([[1, "a"], [2, "b"], [3, "c"]]) // => [[1, 2, 3], ["a", "b", "c"]] + * ``` + * + * @see {@link zip} — combine two arrays into pairs + * + * @category zipping + * @since 2.0.0 + */ +const unzip = self => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const fa = [input[0][0]]; + const fb = [input[0][1]]; + for (let i = 1; i < input.length; i++) { + fa[i] = input[i][0]; + fb[i] = input[i][1]; + } + return [fa, fb]; + } + return [[], []]; +}; +/** + * Places a separator element between every pair of elements. + * + * **When to use** + * + * Use to insert a separator between elements, for example when preparing data for display or concatenation. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Empty inputs produce an empty + * result. + * + * **Example** (Interspersing a separator) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersperse([1, 2, 3], 0) // => [1, 0, 2, 0, 3] + * ``` + * + * @see {@link join} — intersperse and join into a string + * + * @category transforming + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const tail = tailNonEmpty(input); + for (let i = 0; i < tail.length; i++) { + if (i < tail.length) { + out.push(middle); + } + out.push(tail[i]); + } + return out; + } + return []; +}))); +/** + * Applies a function to the first element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use to transform the first element of a non-empty array while preserving the rest. + * + * **Example** (Modifying the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyHeadNonEmpty([1, 2, 3], (n) => n * 10) // => [10, 2, 3] + * ``` + * + * @see {@link setHeadNonEmpty} — replace with a fixed value + * @see {@link modifyLastNonEmpty} — modify the last element + * + * @category transforming + * @since 4.0.0 + */ +const modifyHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => [f(headNonEmpty(self)), ...tailNonEmpty(self)]))); +/** + * Replaces the first element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current first element. + * + * **Example** (Setting the head) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setHeadNonEmpty([1, 2, 3], 10) // => [10, 2, 3] + * ``` + * + * @see {@link modifyHeadNonEmpty} — transform the head with a function + * @see {@link setLastNonEmpty} — replace the last element + * + * @category transforming + * @since 4.0.0 + */ +const setHeadNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyHeadNonEmpty(self, () => b)))); +/** + * Applies a function to the last element of a non-empty array, returning a + * new array. + * + * **When to use** + * + * Use when you already know the array is non-empty and the new last element + * depends on the current last element. + * + * **Example** (Modifying the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.modifyLastNonEmpty([1, 2, 3], (n) => n * 2) // => [1, 2, 6] + * ``` + * + * @see {@link setLastNonEmpty} — replace with a fixed value + * @see {@link modifyHeadNonEmpty} — modify the first element + * + * @category transforming + * @since 4.0.0 + */ +const modifyLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => append(initNonEmpty(self), f(lastNonEmpty(self)))))); +/** + * Replaces the last element of a non-empty array with a new value. + * + * **When to use** + * + * Use when you already know the array is non-empty and the replacement value + * does not depend on the current last element. + * + * **Example** (Setting the last element) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.setLastNonEmpty([1, 2, 3], 4) // => [1, 2, 4] + * ``` + * + * @see {@link modifyLastNonEmpty} — transform the last element with a function + * @see {@link setHeadNonEmpty} — replace the first element + * + * @category transforming + * @since 4.0.0 + */ +const setLastNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, b) => modifyLastNonEmpty(self, () => b)))); +/** + * Transforms an array by rotating it `n` steps. Positive `n` rotates right; negative `n` + * rotates left. + * + * **When to use** + * + * Use when elements should wrap around the end of the array rather than being + * dropped. + * + * **Details** + * + * `n` is rounded to the nearest integer before rotating. The return type + * preserves `NonEmptyArray`. Empty arrays, or rotations normalized to `0`, + * return a copy. + * + * **Example** (Rotating elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.rotate(["a", "b", "c", "d"], 2) // => ["c", "d", "a", "b"] + * ``` + * + * @see {@link take} for taking a fixed number of elements from the start + * @see {@link drop} for dropping a fixed number of elements from the start + * + * @category transforming + * @since 2.0.0 + */ +const rotate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const len = input.length; + const m = Math.round(n) % len; + if (isOutOfBounds(Math.abs(m), input) || m === 0) { + return copy(input); + } + if (m < 0) { + const [f, s] = splitAtNonEmpty(input, -m); + return appendAll(s, f); + } else { + return rotate(input, m - len); + } + } + return []; +}))); +/** + * Returns a membership-test function using a custom equivalence. + * + * **When to use** + * + * Use when checking membership with caller-provided equality instead of + * `Equal.equivalence()`. + * + * **Example** (Checking with custom equality) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * const containsNumber = Array.containsWith((a: number, b: number) => a === b) + * + * pipe([1, 2, 3, 4], containsNumber(3)) // => true + * ``` + * + * @see {@link contains} for the `Equal.equivalence()` variant + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an array contains a value, using `Equal.equivalence()` for + * comparison. + * + * **When to use** + * + * Use to check whether an iterable contains a value using Effect's default + * equality instead of providing a comparison function. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe(["a", "b", "c", "d"], Array.contains("c")) // => true + * ``` + * + * @see {@link containsWith} — use custom equality + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Applies a function repeatedly to consume prefixes of the array and collect + * the values it produces. + * + * **When to use** + * + * Use when you need custom grouping logic where each step returns both a value + * and the remaining input. + * + * **Details** + * + * The function receives a `NonEmptyReadonlyArray` and returns `[value, rest]`. + * Processing continues until the remaining array is empty. + * + * **Example** (Chopping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chop([1, 2, 3, 4, 5], (as): [number, Array] => [as[0] * 2, as.slice(1)]) // => [2, 4, 6, 8, 10] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * @see {@link splitAt} — split at an index + * + * @category splitting + * @since 2.0.0 + */ +const chop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const [b, rest] = f(input); + const out = [b]; + let next = rest; + while (internalArray.isArrayNonEmpty(next)) { + const [b, rest] = f(next); + out.push(b); + next = rest; + } + return out; + } + return []; +}))); +/** + * Splits an iterable into two arrays at the given index. + * + * **When to use** + * + * Use to divide an array into a prefix and suffix at a specific position. + * + * **Details** + * + * `n` can be `0`, in which case all elements are placed in the second array. + * The index is floored to an integer. + * + * **Example** (Splitting at an index) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAt([1, 2, 3, 4, 5], 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link splitAtNonEmpty} — for non-empty arrays + * @see {@link splitWhere} — split at a predicate boundary + * + * @category splitting + * @since 2.0.0 + */ +const splitAt = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = Array.from(self); + const _n = Math.floor(n); + if (isReadonlyArrayNonEmpty(input)) { + if (_n >= 1) { + return splitAtNonEmpty(input, _n); + } + return [[], input]; + } + return [input, []]; +}))); +/** + * Splits a non-empty array into two parts at the given index. The first part + * is guaranteed to be non-empty (`n` is clamped to >= 1). + * + * **When to use** + * + * Use when downstream code requires the left side of the split to contain at + * least one element. + * + * **Example** (Splitting a non-empty array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitAtNonEmpty(["a", "b", "c", "d", "e"], 3) // => [["a", "b", "c"], ["d", "e"]] + * ``` + * + * @see {@link splitAt} — for possibly-empty arrays + * + * @category splitting + * @since 4.0.0 + */ +const splitAtNonEmpty = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const _n = Math.max(1, Math.floor(n)); + return _n >= self.length ? [copy(self), []] : [prepend(self.slice(1, _n), headNonEmpty(self)), self.slice(_n)]; +}))); +/** + * Splits an iterable into `n` roughly equal-sized chunks. + * + * **When to use** + * + * Use to distribute elements across a fixed number of groups, such as when splitting work across threads. + * + * **Details** + * + * Uses `chunksOf(ceil(length / n))` internally. The last chunk may be shorter. + * + * **Example** (Splitting into groups) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3) // => [[1, 2, 3], [4, 5, 6], [7, 8]] + * ``` + * + * @see {@link chunksOf} — split into fixed-size chunks + * + * @category splitting + * @since 2.0.0 + */ +const split = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + return chunksOf(input, Math.ceil(input.length / Math.floor(n))); +}))); +/** + * Splits an iterable at the first element matching the predicate. The matching + * element is included in the second array. + * + * **When to use** + * + * Use when you need to split an array at the first element that marks a + * condition boundary. + * + * **Example** (Splitting at a condition) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3) // => [[1, 2, 3], [4, 5]] + * ``` + * + * @see {@link span} — splits at the first element that fails the predicate + * @see {@link splitAt} — split at a fixed index + * + * @category splitting + * @since 2.0.0 + */ +const splitWhere = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => span(self, (a, i) => !predicate(a, i))))); +/** + * Creates a shallow copy of an array. + * + * **When to use** + * + * Use to create a distinct array reference for an existing array, for example + * before mutating the returned array. + * + * **Details** + * + * The return type preserves `NonEmptyArray`. Use this when you need a distinct + * reference, for example before mutating the returned array. + * + * **Example** (Copying an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const original = [1, 2, 3] + * const copied = Array.copy(original) + * + * copied // => [1, 2, 3] + * original === copied // => false + * ``` + * + * @see {@link fromIterable} — returns the same reference for arrays + * + * @category transforming + * @since 2.0.0 + */ +const copy = self => self.slice(); +/** + * Pads or truncates an array to exactly `n` elements, filling with `fill` + * if the array is shorter, or slicing if longer. + * + * **When to use** + * + * Use to ensure an array has a specific length, padding with a fill value or truncating as needed. + * + * **Details** + * + * Returns an empty array when `n <= 0`. + * + * **Example** (Padding an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.pad([1, 2, 3], 6, 0) // => [1, 2, 3, 0, 0, 0] + * ``` + * + * @see {@link take} — truncate without padding + * @see {@link replicate} — create an array of a single repeated value + * + * @category transforming + * @since 3.8.4 + */ +const pad = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, n, fill) => { + if (self.length >= n) { + return take(self, n); + } + return appendAll(self, makeBy(n - self.length, () => fill)); +}))); +/** + * Splits an iterable into chunks of length `n`. The last chunk may be shorter + * if `n` does not evenly divide the length. + * + * **When to use** + * + * Use to divide an iterable into a new array of non-overlapping chunks with a + * maximum chunk size. + * + * **Details** + * + * `chunksOf(n)([])` is `[]`, not `[[]]`. Each chunk is a `NonEmptyArray`, and + * the outer return type preserves `NonEmptyArray`. + * + * **Example** (Chunking an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.chunksOf([1, 2, 3, 4, 5], 2) // => [[1, 2], [3, 4], [5]] + * ``` + * + * @see {@link split} — split into a given number of groups + * @see {@link window} — sliding windows + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + return chop(input, splitAtNonEmpty(n)); + } + return []; +}))); +/** + * Creates overlapping sliding windows of size `n`. + * + * **When to use** + * + * Use to process sequences with a moving window, such as for computing running averages or detecting patterns. + * + * **Details** + * + * Returns an empty array if `n <= 0` or the array has fewer than `n` elements. + * Each window is a tuple of exactly `n` elements. + * + * **Example** (Creating sliding windows) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const values = [1, 2, 3, 4, 5] + * + * Array.window(values, 3) // => [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + * Array.window(values, 6) // => [] + * ``` + * + * @see {@link chunksOf} — non-overlapping chunks + * + * @category splitting + * @since 3.13.2 + */ +const window = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const input = fromIterable(self); + if (n > 0 && isReadonlyArrayNonEmpty(input)) { + return Array.from({ + length: input.length - (n - 1) + }, (_, index) => input.slice(index, index + n)); + } + return []; +}))); +/** + * Groups consecutive equal elements using a custom equivalence function. + * + * **When to use** + * + * Use when you already have a non-empty array arranged so matching elements are + * adjacent and need a custom equivalence function. + * + * **Details** + * + * Only adjacent elements are grouped. Non-adjacent duplicates stay separate. + * Requires a `NonEmptyReadonlyArray`. + * + * **Example** (Grouping consecutive equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.groupWith( + * ["a", "a", "b", "b", "b", "c", "a"], + * (x, y) => x === y + * ) // => [["a", "a"], ["b", "b", "b"], ["c"], ["a"]] + * ``` + * + * @see {@link group} for grouping adjacent elements with `Equal.equivalence()` + * @see {@link groupBy} for grouping all elements into a record by key, regardless of adjacency + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => chop(self, as => { + const h = headNonEmpty(as); + const out = [h]; + let i = 1; + for (; i < as.length; i++) { + const a = as[i]; + if (isEquivalent(a, h)) { + out.push(a); + } else { + break; + } + } + return [out, as.slice(i)]; +})))); +/** + * Groups consecutive equal elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you already have adjacent equal values and Effect's default equality + * is the right comparison. + * + * **Details** + * + * Only adjacent elements are grouped. + * + * **Example** (Grouping adjacent equal elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.group([1, 1, 2, 2, 2, 3, 1]) // => [[1, 1], [2, 2, 2], [3], [1]] + * ``` + * + * @see {@link groupWith} — use custom equality + * @see {@link groupBy} — group by a key function into a record + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups elements into a record by a key-returning function. Each key maps + * to a `NonEmptyArray` of elements that produced that key. + * + * **When to use** + * + * Use to build buckets of elements indexed by a computed string or symbol key. + * + * **Details** + * + * Unlike `group` and `groupWith`, elements do not need to be adjacent to be + * grouped together. The key function must return a `string` or `symbol`. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a property) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const people = [ + * { name: "Alice", group: "A" }, + * { name: "Bob", group: "B" }, + * { name: "Charlie", group: "A" } + * ] + * + * Object.keys(Array.groupBy(people, (person) => person.group)).join(",") // => "A,B" + * ``` + * + * @see {@link group} — group adjacent equal elements + * @see {@link groupWith} — group adjacent elements by custom equality + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const hashBucketsAdd = (buckets, value) => { + const hash = _Hash_js__rspack_import_5/* .hash */.tW(value); + const bucket = buckets.get(hash); + if (bucket === undefined) { + buckets.set(hash, [value]); + return true; + } + // Hash collisions still require an Effect equality check. + for (const previous of bucket) { + if (_Equal_js__rspack_import_6/* .equals */.aI(previous, value)) { + return false; + } + } + bucket.push(value); + return true; +}; +const makeHashBuckets = values => { + const buckets = new Map(); + for (const value of values) { + hashBucketsAdd(buckets, value); + } + return buckets; +}; +const hashBucketsHas = (buckets, value) => { + const bucket = buckets.get(Hash.hash(value)); + if (bucket === undefined) { + return false; + } + for (const candidate of bucket) { + if (Equal.equals(candidate, value)) { + return true; + } + } + return false; +}; +/** + * Computes the union of two arrays using a custom equivalence, removing + * duplicates. + * + * **When to use** + * + * Use when you need the union of two arrays but duplicate detection must use a + * custom equivalence instead of the default `Equal.equivalence()`. + * + * **Example** (Computing unions with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.unionWith([1, 2], [2, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link union} for the `Equal.equivalence()` variant + * @see {@link intersectionWith} for keeping elements present in both arrays + * @see {@link differenceWith} for keeping elements present only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const unionWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, isEquivalent) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + if (isReadonlyArrayNonEmpty(b)) { + const dedupe = dedupeWith(isEquivalent); + return dedupe(appendAll(a, b)); + } + return a; + } + return b; +}))); +/** + * Computes the union of two arrays, removing duplicates using + * `Equal.equivalence()`. + * + * **Example** (Computing array unions) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.union([1, 2], [2, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link unionWith} — use custom equality + * @see {@link intersection} — elements in both arrays + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const union = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, that) => { + const a = fromIterable(self); + const b = fromIterable(that); + if (isReadonlyArrayNonEmpty(a)) { + return isReadonlyArrayNonEmpty(b) ? dedupe(appendAll(a, b)) : a; + } + return b; +}); +/** + * Computes the intersection of two arrays using a custom equivalence. Order is + * determined by the first array. + * + * **When to use** + * + * Use when you need to keep only values present in both arrays and equality + * must be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing intersections with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }] + * const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }] + * const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id + * + * Array.intersectionWith(isEquivalent)(array2)(array1) // => [{ id: 1 }, { id: 3 }] + * ``` + * + * @see {@link intersection} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link differenceWith} for keeping values only from the first array with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const intersectionWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => has(thatArray, a)); + }); +}; +/** + * Computes the intersection of two arrays using `Equal.equivalence()`. Order is + * determined by the first array. + * + * **When to use** + * + * Use when Effect equality is the right membership test and you want to keep + * values present in both inputs while preserving the first input's order. + * + * **Example** (Computing array intersections) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.intersection([1, 2, 3], [3, 4, 1]) // => [1, 3] + * ``` + * + * @see {@link intersectionWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link difference} — elements only in the first array + * + * @category set operations + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0 || thatArray.length === 0) { + return []; + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => hashBucketsHas(buckets, value)); +}))); +/** + * Computes elements in the first array that are not in the second, using a + * custom equivalence. + * + * **When to use** + * + * Use when you need to keep only values from the first array and equality must + * be defined by a custom comparator, such as matching objects by id. + * + * **Example** (Computing differences with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.differenceWith((a, b) => a === b)([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link difference} for the `Equal.equivalence()` variant + * @see {@link unionWith} for keeping values from either array with custom equality + * @see {@link intersectionWith} for keeping values present in both arrays with custom equality + * + * @category set operations + * @since 2.0.0 + */ +const differenceWith = isEquivalent => { + const has = containsWith(isEquivalent); + return dual(2, (self, that) => { + const thatArray = fromIterable(that); + return fromIterable(self).filter(a => !has(thatArray, a)); + }); +}; +/** + * Computes elements in the first array that are not in the second, using + * `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to keep values from the first array that are absent from + * the second and the default `Equal.equivalence()` comparison is appropriate. + * + * **Example** (Computing array differences) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.difference([1, 2, 3], [2, 3, 4]) // => [1] + * ``` + * + * @see {@link differenceWith} — use custom equality + * @see {@link union} — elements in either array + * @see {@link intersection} — elements in both arrays + * + * @category set operations + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + const thatArray = fromIterable(that); + const selfArray = fromIterable(self); + if (selfArray.length === 0) { + return []; + } + if (thatArray.length === 0) { + return selfArray.filter(() => true); + } + const buckets = makeHashBuckets(thatArray); + return selfArray.filter(value => !hashBucketsHas(buckets, value)); +}))); +/** + * 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 + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => []; +/** + * Wraps a single value in a `NonEmptyArray`. + * + * **Example** (Creating a single-element array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.of(1) // => [1] + * ``` + * + * @see {@link make} — create from multiple values + * @see {@link empty} — create an empty array + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element using a function, returning a new array. + * + * **When to use** + * + * Use to transform each element independently while preserving the array shape. + * + * **Details** + * + * The function receives `(element, index)`. The return type preserves + * `NonEmptyArray`. + * + * **Example** (Doubling values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6] + * ``` + * + * @see {@link flatMap} — map and flatten + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map(f)))); +/** + * Maps each element to an array and flattens the results into a single array. + * + * **When to use** + * + * Use to map each array element to zero or more values and concatenate the + * results in one pass. + * + * **Details** + * + * The function receives `(element, index)`. This returns `NonEmptyArray` when + * both the input and mapped arrays are non-empty. + * + * **Example** (Flat mapping an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMap([1, 2, 3], (x) => [x, x * 2]) // => [1, 2, 2, 4, 3, 6] + * ``` + * + * @see {@link map} — transform without flattening + * @see {@link flatten} — flatten without mapping + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isReadonlyArrayEmpty(self)) { + return []; + } + const out = []; + for (let i = 0; i < self.length; i++) { + const inner = f(self[i], i); + for (let j = 0; j < inner.length; j++) { + out.push(inner[j]); + } + } + return out; +}))); +/** + * Flattens a nested array of arrays into a single array. + * + * **When to use** + * + * Use to collapse one level of nested arrays when no per-element mapping is + * needed. + * + * **Example** (Flattening nested arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatten([[1, 2], [], [3, 4], [], [5, 6]]) // => [1, 2, 3, 4, 5, 6] + * ``` + * + * @see {@link flatMap} — map then flatten in one step + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(identity))); +/** + * Extracts all `Some` values from an iterable of `Option`s, discarding `None`s. + * + * **When to use** + * + * Use to collect only present values from an iterable of `Option` values while + * discarding `None` values. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.getSomes([Option.some(1), Option.none(), Option.some(2)]) // => [1, 2] + * ``` + * + * @see {@link fromOption} — convert a single Option + * @see {@link getSuccesses} — extract successes from Results + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = []; + for (const a of self) { + if (Option.isSome(a)) { + out.push(a.value); + } + } + return out; +}; +/** + * Extracts all failure values from an iterable of `Result`s, discarding + * successes. + * + * **When to use** + * + * Use when you can drop the success channel and only need the failure + * payloads, not the original result wrappers. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getFailures([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => ["err"] + * ``` + * + * @see {@link getSuccesses} — extract success values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = []; + for (const a of self) { + if (Result.isFailure(a)) { + out.push(a.failure); + } + } + return out; +}; +/** + * Extracts all success values from an iterable of `Result`s, discarding + * failures. + * + * **When to use** + * + * Use when you can drop the failure channel and only need the success + * payloads, not the original result wrappers. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.getSuccesses([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) // => [1, 2] + * ``` + * + * @see {@link getFailures} — extract failure values + * @see {@link separate} — split into failures and successes + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = []; + for (const a of self) { + if (Result.isSuccess(a)) { + out.push(a.success); + } + } + return out; +}; +/** + * Keeps transformed values for elements where a `Filter` succeeds. + * + * **When to use** + * + * Use to filter an iterable with a `Result`-returning transformation while + * discarding failures. + * + * **Details** + * + * The filter receives `(element, index)`. Failures are discarded. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.filterMap([1, 2, 3, 4], (n) => n % 2 === 0 ? Result.succeed(n * 10) : Result.failVoid) // => [20, 40] + * ``` + * + * @see {@link filter} — keep original elements matching a predicate + * @see {@link partition} for keeping both failures and successes + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + const result = f(as[i], i); + if (Result.isSuccess(result)) { + out.push(result.success); + } + } + return out; +}))); +/** + * Keeps only elements satisfying a predicate (or refinement). + * + * **When to use** + * + * Use to filter an iterable into a new array of original elements that satisfy + * a boolean predicate or refinement. + * + * **Details** + * + * The predicate receives `(element, index)`. Refinements are supported for type + * narrowing. + * + * **Example** (Filtering even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.filter([1, 2, 3, 4], (x) => x % 2 === 0) // => [2, 4] + * ``` + * + * @see {@link partition} — split into matching and non-matching + * @see {@link filterMap} for transforming while filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const as = fromIterable(self); + const out = []; + for (let i = 0; i < as.length; i++) { + if (predicate(as[i], i)) { + out.push(as[i]); + } + } + return out; +}))); +/** + * Splits an iterable using a `Filter` into failures and successes. + * + * **When to use** + * + * Use to partition an iterable by evaluating each element with a + * `Result`-returning filter and keeping both failure and success values. + * + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a filter) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.partition([1, -2, 3], (n, i) => + * n > 0 ? Result.succeed(n + i) : Result.fail(`negative:${n}`) + * ) // => [["negative:-2"], [1, 5]] + * ``` + * + * @see {@link filter} — keep only matching elements + * @see {@link filterMap} for discarding failures + * @see {@link separate} — split an iterable of `Result` values + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (self, f) => { + const excluded = []; + const satisfying = []; + let i = 0; + for (const a of self) { + const result = f(a, i++); + if (_Result_js__rspack_import_7/* .isSuccess */.oJ(result)) { + satisfying.push(result.success); + } else { + excluded.push(result.failure); + } + } + return [excluded, satisfying]; +}); +/** + * Separates an iterable of `Result`s into failure values and success values. + * + * **When to use** + * + * Use to split an iterable of `Result` values into failure and success arrays. + * + * **Details** + * + * Returns `[failures, successes]`. This is equivalent to + * `partition(identity)`. + * + * **Example** (Separating Results) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * Array.separate([Result.succeed(1), Result.fail("error"), Result.succeed(2)]) // => [["error"], [1, 2]] + * ``` + * + * @see {@link getFailures} — extract only failures + * @see {@link getSuccesses} — extract only successes + * @see {@link partition} for computing `Result` values while splitting + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Folds an iterable from left to right into a single value. + * + * **When to use** + * + * Use to combine all elements into one accumulated value from left to right. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Summing an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduce([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduceRight} — fold from right to left + * @see {@link scan} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduce((b, a, i) => f(b, a, i), b)))); +/** + * Folds an iterable from right to left into a single value. + * + * **When to use** + * + * Use when you need to fold values from right to left. + * + * **Details** + * + * The function receives `(accumulator, element, index)`. + * + * **Example** (Folding from right to left) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n) // => 6 + * ``` + * + * @see {@link reduce} — fold from left to right + * @see {@link scanRight} — fold keeping intermediate values + * + * @category folding + * @since 2.0.0 + */ +const reduceRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => fromIterable(self).reduceRight((b, a, i) => f(b, a, i), b)))); +/** + * Lifts a predicate into an array: returns `[value]` if the predicate holds, + * `[]` otherwise. + * + * **Example** (Wrapping values conditionally) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const fromEven = Array.liftPredicate((n: number) => n % 2 === 0) + * + * fromEven(1) // => [] + * fromEven(2) // => [2] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = predicate => b => predicate(b) ? [b] : []; +/** + * Lifts an `Option`-returning function into one that returns an array: + * `Some(a)` becomes `[a]`, `None` becomes `[]`. + * + * **When to use** + * + * Use when an optional parser or lookup should participate in array pipelines + * as zero-or-one results. + * + * **Example** (Lifting an Option function) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * const parseNumber = Array.liftOption((s: string) => { + * const n = Number(s) + * return isNaN(n) ? Option.none() : Option.some(n) + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link liftPredicate} — lift a boolean predicate + * @see {@link liftResult} — lift a Result-returning function + * + * @category lifting + * @since 2.0.0 + */ +const liftOption = f => (...a) => fromOption(f(...a)); +/** + * Converts a nullable value to an array: `null`/`undefined` becomes `[]`, + * anything else becomes `[value]`. + * + * **When to use** + * + * Use to treat a nullable single value as zero or one array element. + * + * **Example** (Converting nullable values to an array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.fromNullishOr(1) // => [1] + * Array.fromNullishOr(null) // => [] + * Array.fromNullishOr(undefined) // => [] + * ``` + * + * @see {@link liftNullishOr} — lift a nullable-returning function + * @see {@link fromOption} — convert from Option + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? empty() : [a]; +/** + * Lifts a nullable-returning function into one that returns an array: + * `null`/`undefined` becomes `[]`, anything else becomes `[value]`. + * + * **Example** (Lifting a nullable function) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const parseNumber = Array.liftNullishOr((s: string) => { + * const n = Number(s) + * return isNaN(n) ? null : n + * }) + * + * parseNumber("123") // => [123] + * parseNumber("abc") // => [] + * ``` + * + * @see {@link fromNullishOr} — convert a single nullable value + * @see {@link liftOption} — lift an Option-returning function + * + * @category lifting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Maps each element with a nullable-returning function, keeping only non-null / + * non-undefined results. + * + * **When to use** + * + * Use when you need to map and filter in one step, where the mapper can return + * `null` or `undefined` to skip elements. + * + * **Example** (Flat mapping with nullable values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.flatMapNullishOr([1, 2, 3], (n) => (n % 2 === 0 ? null : n)) // => [1, 3] + * ``` + * + * @see {@link flatMap} for mapping each element to an array and flattening + * @see {@link fromNullishOr} for converting a single nullable value to an array + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => fromNullishOr(f(a)))))); +/** + * Lifts a `Result`-returning function into one that returns an array: failures + * produce `[]`, successes produce `[value]`. + * + * **When to use** + * + * Use when a fallible parser or lookup should participate in array pipelines as + * zero-or-one results and the failure value should be discarded. + * + * **Example** (Lifting a Result function) + * + * ```ts import.meta.vitest + * import { Array, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => + * isNaN(Number(s)) + * ? Result.fail(new Error("Not a number")) + * : Result.succeed(Number(s)) + * + * const liftedParseNumber = Array.liftResult(parseNumber) + * + * liftedParseNumber("42") // => [42] + * liftedParseNumber("not a number") // => [] + * ``` + * + * @see {@link liftOption} — lift an Option-returning function + * @see {@link liftPredicate} — lift a boolean predicate + * + * @category lifting + * @since 4.0.0 + */ +const liftResult = f => (...a) => { + const e = f(...a); + return Result.isFailure(e) ? [] : [e.success]; +}; +/** + * Checks whether all elements satisfy the predicate. Supports refinements for + * type narrowing. + * + * **When to use** + * + * Use to check whether every array element satisfies a predicate, including + * refinement-based type narrowing. + * + * **Example** (Testing all elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.every([2, 4, 6], (x) => x % 2 === 0) // => true + * Array.every([2, 3, 6], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link some} — test if any element matches + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => self.every(refinement)))); +/** + * Checks whether at least one element satisfies the predicate. Narrows the type + * to `NonEmptyReadonlyArray` on success. + * + * **Example** (Testing for any match) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.some([1, 3, 4], (x) => x % 2 === 0) // => true + * Array.some([1, 3, 5], (x) => x % 2 === 0) // => false + * ``` + * + * @see {@link every} — test if all elements match + * @see {@link contains} — test for a specific value + * + * @category guards + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => self.some(predicate)))); +/** + * Applies a function to each suffix of the array (starting from each index), + * collecting the results. + * + * **When to use** + * + * Use when you need to compute a result from every suffix of an array, such as + * cumulative aggregations from each position. + * + * **Details** + * + * For index `i`, the function receives `self.slice(i)`. + * + * **Example** (Computing suffix lengths) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.extend([1, 2, 3], (as) => as.length) // => [3, 2, 1] + * ``` + * + * @see {@link scan} for keeping intermediate accumulator values during a fold + * + * @category mapping + * @since 2.0.0 + */ +const extend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => self.map((_, i, as) => f(as.slice(i)))))); +/** + * Returns the minimum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the minimum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.min([3, 1, 2], Order.Number) // => 1 + * ``` + * + * @see {@link max} — find the maximum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.min(O))))); +/** + * Returns the maximum element of a non-empty array according to the given + * `Order`. + * + * **Example** (Finding the maximum) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * Array.max([3, 1, 2], Order.Number) // => 3 + * ``` + * + * @see {@link min} — find the minimum + * @see {@link sort} — sort the entire array + * + * @category getters + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, O) => self.reduce(Order.max(O))))); +/** + * Builds an array by repeatedly applying a function to a seed value. The + * function returns `Option.some([element, nextSeed])` to continue, or + * `Option.none()` to stop. + * + * **Example** (Generating a sequence) + * + * ```ts import.meta.vitest + * import { Array, Option } from "effect" + * + * Array.unfold(1, (n) => n <= 5 ? Option.some([n, n + 1]) : Option.none()) // => [1, 2, 3, 4, 5] + * ``` + * + * @see {@link makeBy} — generate from index + * @see {@link range} — generate a numeric range + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => { + const out = []; + let next = b; + while (true) { + const o = f(next); + if (Option.isNone(o)) { + break; + } + const [a, b] = o.value; + out.push(a); + next = b; + } + return out; +}; +/** + * Creates an `Order` for arrays based on an element `Order`. Arrays are + * compared element-wise; if all compared elements are equal, shorter arrays + * come first. + * + * **Example** (Comparing arrays) + * + * ```ts import.meta.vitest + * import { Array, Order } from "effect" + * + * const arrayOrder = Array.makeOrder(Order.Number) + * + * arrayOrder([1, 2], [1, 3]) // => -1 + * ``` + * + * @see {@link makeEquivalence} — create an equivalence for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeOrder = _Order_js__rspack_import_8/* .Array */.O3; +/** + * Creates an `Equivalence` for arrays based on an element `Equivalence`. Two + * arrays are equivalent when they have the same length and all elements are + * pairwise equivalent. + * + * **Example** (Comparing arrays for equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const eq = Array.makeEquivalence((a, b) => a === b) + * + * eq([1, 2, 3], [1, 2, 3]) // => true + * ``` + * + * @see {@link makeOrder} — create an ordering for arrays + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = _Equivalence_js__rspack_import_9/* .Array */.O3; +/** + * Runs a side-effect for each element. The callback receives `(element, index)`. + * + * **When to use** + * + * Use to iterate over an array for side-effects only, when no transformed + * result is needed. + * + * **Example** (Iterating with side-effects) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * const visited: Array = [] + * Array.forEach([1, 2, 3], (n) => visited.push(n)) + * + * visited // => [1, 2, 3] + * ``` + * + * @see {@link map} for transforming each element into a new array + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromIterable(self).forEach((a, i) => f(a, i))))); +/** + * Removes duplicates using a custom equivalence, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove all duplicate elements with a custom equivalence when default + * equality is not appropriate. + * + * **Example** (Deduplicating with custom equality) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupe} — uses default equality + * @see {@link dedupeAdjacentWith} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const input = fromIterable(self); + if (isReadonlyArrayNonEmpty(input)) { + const out = [headNonEmpty(input)]; + const rest = tailNonEmpty(input); + for (const r of rest) { + if (out.every(a => !isEquivalent(r, a))) { + out.push(r); + } + } + return out; + } + return []; +}))); +/** + * Removes duplicates using `Equal.equivalence()`, preserving the order of the + * first occurrence. + * + * **When to use** + * + * Use to remove repeated values from an iterable when Effect's default equality + * is the right comparison, preserving the first occurrence. + * + * **Example** (Removing duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupe([1, 2, 1, 3, 2, 4]) // => [1, 2, 3, 4] + * ``` + * + * @see {@link dedupeWith} — use custom equality + * @see {@link dedupeAdjacent} — only dedupes consecutive elements + * + * @category deduplication + * @since 2.0.0 + */ +const dedupe = self => { + const input = fromIterable(self); + if (input.length < 2) { + return [...input]; + } + const buckets = new Map(); + const out = []; + for (const value of input) { + if (hashBucketsAdd(buckets, value)) { + out.push(value); + } + } + return out; +}; +/** + * Removes consecutive duplicate elements using a custom equivalence. + * + * **When to use** + * + * Use when consecutive duplicates should be collapsed using a custom + * equivalence, while equivalent values that appear later should remain in the + * result. + * + * **Details** + * + * Non-adjacent duplicates are preserved. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacent} — uses default equality + * @see {@link dedupeWith} — dedupes all duplicates, not just adjacent + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => { + const out = []; + let lastA = Option.none(); + for (const a of self) { + if (Option.isNone(lastA) || !isEquivalent(a, lastA.value)) { + out.push(a); + lastA = Option.some(a); + } + } + return out; +}))); +/** + * Removes consecutive duplicate elements using `Equal.equivalence()`. + * + * **When to use** + * + * Use when you need to collapse consecutive duplicates while preserving later + * non-consecutive repeats, and the default equality is sufficient. + * + * **Example** (Removing adjacent duplicates) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.dedupeAdjacent([1, 1, 2, 2, 3, 3]) // => [1, 2, 3] + * ``` + * + * @see {@link dedupeAdjacentWith} — use custom equality + * @see {@link dedupe} — remove all duplicates + * + * @category deduplication + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Joins string elements with a separator. + * + * **Example** (Joining strings) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.join(["a", "b", "c"], "-") // => "a-b-c" + * ``` + * + * @see {@link intersperse} — insert separator elements without joining + * + * @category folding + * @since 2.0.0 + */ +const join = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, sep) => fromIterable(self).join(sep)))); +/** + * Maps over an array while threading an accumulator through each step, returning both the final state and the mapped array. + * + * **When to use** + * + * Use when you need to map while threading state through each element and keep + * the final state. + * + * **Details** + * + * Combines `map` and `reduce` in a single pass. The callback receives the + * current state, element, and index, and returns `[nextState, mappedValue]`. + * The result is `[finalState, mappedArray]`. This can be used in both + * data-first and data-last style. + * + * **Example** (Running sum alongside mapped values) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n]) // => [6, [1, 3, 6]] + * ``` + * + * @see {@link scan} — when you only need the accumulated results (not the final state) + * @see {@link reduce} — when you only need the final accumulated value + * + * @category folding + * @since 2.0.0 + */ +const mapAccum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, s, f) => { + let i = 0; + let s1 = s; + const out = []; + for (const a of self) { + const r = f(s1, a, i); + s1 = r[0]; + out.push(r[1]); + i++; + } + return [s1, out]; +}))); +/** + * Computes the cartesian product of two arrays, applying a combiner to each pair. + * + * **When to use** + * + * Use to compute every combination from two arrays and immediately transform + * each pair into a custom result. + * + * **Details** + * + * Produces every combination of an element from `self` with an element from + * `that`, so the result length is `self.length * that.length`. Iteration visits + * every element of `that` for each element of `self`. + * + * **Example** (Combining numbers and letters) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesianWith([1, 2], ["a", "b"], (a, b) => `${a}-${b}`) // => ["1-a", "1-b", "2-a", "2-b"] + * ``` + * + * @see {@link cartesian} for returning tuples instead of applying a combiner + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => flatMap(self, a => map(that, b => f(a, b)))))); +/** + * Computes the cartesian product of two arrays, returning all pairs as tuples. + * + * **When to use** + * + * Use when you need every `[a, b]` pair from two arrays as tuples. + * + * **Details** + * + * Produces every `[a, b]` combination of an element from `self` with an element + * from `that`, so the result length is `self.length * that.length`. + * + * **Example** (Generating all pairs from two arrays) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.cartesian([1, 2], ["a", "b"]) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"]] + * ``` + * + * @see {@link cartesianWith} — apply a combiner to each pair + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do simulation" — an array comprehension pattern. + * + * **When to use** + * + * Use when you want array-comprehension style code with do notation. + * + * **Details** + * + * Use {@link bind} to introduce array variables and {@link let_ let} for plain + * values. Each `bind` produces the cartesian product of all bound variables, + * like nested loops. Use `filter` and `map` in the pipeline to add conditions + * and transformations. + * + * **Example** (Building array comprehensions with do notation) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 3, 5]), + * Array.bind("y", () => [2, 4, 6]), + * Array.filter(({ x, y }) => x < y), + * Array.map(({ x, y }) => [x, y] as const) + * ) // => [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]] + * ``` + * + * @see {@link bind} — introduce an array variable into the scope + * @see {@link bindTo} — start a pipeline by naming the first array + * @see {@link let_ let} — introduce a plain computed value + * + * @category constructors + * @since 3.2.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (of({}))); +/** + * Adds a new array variable to a do-notation scope, producing the cartesian product with all previous bindings. + * + * **When to use** + * + * Use to add another array-producing binding to an `Array.Do` pipeline, pairing + * each existing scope with every value returned by the callback. + * + * **Details** + * + * Each `bind` call adds a named property to the accumulated object. The + * callback receives the current scope and must return an array. This is + * equivalent to `flatMap` plus merging the new value into the scope object. + * + * **Example** (Binding two arrays) + * + * ```ts import.meta.vitest + * import { Array, pipe } from "effect" + * + * pipe( + * Array.Do, + * Array.bind("x", () => [1, 2]), + * Array.bind("y", () => ["a", "b"]) + * ) // => [{ x: 1, y: "a" }, { x: 1, y: "b" }, { x: 2, y: "a" }, { x: 2, y: "b" }] + * ``` + * + * @see {@link Do} — start a do-notation pipeline + * @see {@link bindTo} — name the first array in a pipeline + * @see {@link let_ let} — add a plain computed value + * + * @category sequencing + * @since 3.2.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bind(map, flatMap))); +/** + * Wraps each array element in an object with the given key, starting a do-notation scope. + * + * **When to use** + * + * Use when you already have an array and want to start a do-notation pipeline + * by naming each element. + * + * **Details** + * + * Equivalent to `Array.map(self, (a) => ({ [tag]: a }))`. This is an + * alternative to starting with `Do` plus `bind` when you already have an array. + * + * **Example** (Naming an existing array) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.bindTo([1, 2, 3], "x") // => [{ x: 1 }, { x: 2 }, { x: 3 }] + * ``` + * + * @see {@link Do} — start with an empty scope + * @see {@link bind} — add another array variable to the scope + * + * @category mapping + * @since 3.2.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (internalDoNotation.let_(map))); + +const reducer = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make((a, b) => a.concat(b), []))); +/** + * Returns a `Reducer` that combines `ReadonlyArray` values by concatenation. + * + * @see {@link makeReducerConcat} — mutable `Array` variant + * + * @category folding + * @since 4.0.0 + */ +function getReadonlyReducerConcat() { + return reducer; +} +/** + * Returns a `Reducer` that combines `Array` values by concatenation. + * + * @see {@link getReadonlyReducerConcat} — readonly variant + * + * @category folding + * @since 4.0.0 + */ +function makeReducerConcat() { + return reducer; +} +/** + * Computes the number of elements in an iterable that satisfy a predicate. + * + * **When to use** + * + * Use when you need to count how many elements of an iterable satisfy a + * predicate. + * + * **Details** + * + * The predicate receives both the element and its index. Empty iterables return + * `0`. + * + * **Example** (Counting even numbers) + * + * ```ts import.meta.vitest + * import { Array } from "effect" + * + * Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @see {@link filter} — when you need the matching elements, not just the count + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + const as = fromIterable(self); + for (let i = 0; i < as.length; i++) { + const a = as[i]; + if (f(a, i)) { + count++; + } + } + return count; +}))); +//# sourceMappingURL=Array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + CZ: isArrayNonEmpty, + Ie: empty, + KC: union, + Ts: fromIterable, + jB: partition +}); + + +}, +"./node_modules/effect/dist/Cause.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/** + * Records the full reason an `Effect` failed. + * + * A `Cause` can contain typed failures, unexpected defects, interruptions, + * and annotations. Keeping those details together lets code inspect or format + * failures without first collapsing them to a single error value. This module + * includes the `Cause` and `Reason` data types, helpers for building and + * checking causes, and small error types used by several Effect APIs. + * + * @since 2.0.0 + */ + + + +/** + * Unique brand for `Cause` values, used for runtime type checks via {@link isCause}. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .CauseTypeId */.PX; +/** + * Unique brand for `Reason` values, used for runtime type checks via {@link isReason}. + * + * @category type IDs + * @since 4.0.0 + */ +const ReasonTypeId = _internal_core_js__rspack_import_0/* .CauseReasonTypeId */.B4; +/** + * Checks whether an arbitrary value is a `Cause`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isCause(Cause.fail("error")) // => true + * Cause.isCause("not a cause") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isCause = _internal_core_js__rspack_import_0/* .isCause */.Aj; +/** + * Checks whether an arbitrary value is a `Reason` (`Fail`, `Die`, or `Interrupt`). + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reason = Cause.fail("error").reasons[0] + * Cause.isReason(reason) // => true + * Cause.isReason("not a reason") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isReason = _internal_core_js__rspack_import_0/* .isCauseReason */.Wg; +/** + * Narrows a `Reason` to `Fail`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering fail reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const fails = cause.reasons.filter(Cause.isFailReason) + * fails[0].error // => "error" + * ``` + * + * @see {@link isDieReason} — narrow to `Die` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isFailReason = _internal_core_js__rspack_import_0/* .isFailReason */.lC; +/** + * Narrows a `Reason` to `Die`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Die` (defect) reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering die reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.die("defect") + * const dies = cause.reasons.filter(Cause.isDieReason) + * dies[0].defect // => "defect" + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isInterruptReason} — narrow to `Interrupt` + * + * @category guards + * @since 4.0.0 + */ +const isDieReason = _internal_core_js__rspack_import_0/* .isDieReason */.Xb; +/** + * Narrows a `Reason` to `Interrupt`. + * + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Interrupt` reasons when + * iterating over `cause.reasons`. + * + * **Example** (Filtering interrupt reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.interrupt(123) + * const interrupts = cause.reasons.filter(Cause.isInterruptReason) + * interrupts[0].fiberId // => 123 + * ``` + * + * @see {@link isFailReason} — narrow to `Fail` + * @see {@link isDieReason} — narrow to `Die` + * + * @category guards + * @since 4.0.0 + */ +const isInterruptReason = _internal_core_js__rspack_import_0/* .isInterruptReason */.ik; +/** + * Creates a `Cause` from an array of `Reason` values. + * + * **When to use** + * + * Use when you already have individual reasons (e.g. from filtering or + * transforming another cause's `reasons` array) and need to wrap them back + * into a `Cause`. + * + * **Details** + * + * - Returns a new `Cause`. + * - An empty array produces a cause equivalent to `empty`. + * + * **Gotchas** + * + * The `reasons` array is stored as provided. Treat the array as immutable + * after passing it to this function. + * + * **Example** (Building a cause from reasons) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const reasons = [ + * Cause.makeFailReason("err1"), + * Cause.makeFailReason("err2") + * ] + * Cause.fromReasons(reasons) // => Cause.combine(Cause.fail("err1"), Cause.fail("err2")) + * ``` + * + * @see {@link combine} — merge two existing causes + * + * @category constructors + * @since 4.0.0 + */ +const fromReasons = _internal_core_js__rspack_import_0/* .causeFromReasons */.b5; +/** + * Represents a `Cause` with an empty `reasons` array. + * + * **When to use** + * + * Use to represent the absence of failure when constructing or combining + * causes. + * + * **Details** + * + * Represents the absence of failure. Combining any cause with `empty` via + * {@link combine} returns the original cause unchanged. + * + * **Example** (Combining with the empty cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.combine(Cause.empty, Cause.fail("boom")) // => Cause.fail("boom") + * ``` + * + * @see {@link combine} for merging causes where `empty` acts as the identity + * + * @category constructors + * @since 2.0.0 + */ +const empty = _internal_core_js__rspack_import_0/* .causeEmpty */.DH; +/** + * Creates a `Cause` containing a single `Fail` reason with the + * given typed error. + * + * **When to use** + * + * Use to construct a cause from an expected typed error. + * + * **Example** (Creating a fail cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.fail("Something went wrong") // => Cause.fromReasons([Cause.makeFailReason("Something went wrong")]) + * ``` + * + * @see {@link die} — for untyped defects + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .causeFail */.OE; +/** + * Creates a `Cause` containing a single `Die` reason with the + * given defect. + * + * **When to use** + * + * Use to construct a cause from an untyped defect or unexpected thrown value. + * + * **Example** (Creating a die cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link interrupt} — for fiber interruptions + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .causeDie */.Iu; +/** + * Creates a `Cause` containing a single `Interrupt` reason, + * optionally carrying the interrupting fiber's ID. + * + * **Example** (Creating an interrupt cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.interrupt(123) // => Cause.fromReasons([Cause.makeInterruptReason(123)]) + * ``` + * + * @see {@link fail} — for typed errors + * @see {@link die} — for untyped defects + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .causeInterrupt */.nIy; +/** + * Creates a standalone `Fail` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone typed failure reason for + * {@link fromReasons} or direct comparison. + * + * **Example** (Creating a Fail reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeFailReason("error") // => Cause.fail("error").reasons[0] + * ``` + * + * @see {@link makeDieReason} — create a `Die` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeFailReason = error => new core.Fail(error); +/** + * Creates a standalone `Die` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone defect reason for {@link fromReasons} or + * direct comparison. + * + * **Example** (Creating a Die reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeDieReason("bug") // => Cause.die("bug").reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeInterruptReason} — create an `Interrupt` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeDieReason = defect => new core.Die(defect); +/** + * Creates a standalone `Interrupt` reason (not wrapped in a `Cause`), + * optionally carrying the interrupting fiber's ID. + * + * **When to use** + * + * Use when constructing a standalone interrupt reason for {@link fromReasons} + * or direct comparison. + * + * **Example** (Creating an Interrupt reason) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.makeInterruptReason(42) // => Cause.interrupt(42).reasons[0] + * ``` + * + * @see {@link makeFailReason} — create a `Fail` reason + * @see {@link makeDieReason} — create a `Die` reason + * + * @category constructors + * @since 4.0.0 + */ +const makeInterruptReason = _internal_effect_js__rspack_import_1/* .makeInterruptReason */.ORc; +/** + * Returns `true` if every reason in the cause is an `Interrupt` (and + * there is at least one reason). + * + * **When to use** + * + * Use when you need to detect failures caused only by interruption. + * + * **Example** (Checking interrupt-only causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterruptsOnly(Cause.interrupt(123)) // => true + * Cause.hasInterruptsOnly(Cause.fail("error")) // => false + * Cause.hasInterruptsOnly(Cause.empty) // => false + * ``` + * + * @see {@link hasInterrupts} — `true` if the cause contains *any* interrupts + * + * @category predicates + * @since 4.0.0 + */ +const hasInterruptsOnly = _internal_effect_js__rspack_import_1/* .hasInterruptsOnly */.nn5; +/** + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** + * + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. + * + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. + * + * **Example** (Mapping errors to uppercase) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.fail("error") + * const mapped = Cause.map(cause, (e) => e.toUpperCase()) + * const reason = mapped.reasons[0] + * if (Cause.isFailReason(reason)) { + * reason.error // => "ERROR" + * } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .causeMap */.O$X; +/** + * Merges two causes into a single cause whose `reasons` array is the union + * of both inputs (de-duplicated by value equality). + * + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. + * - If the result is structurally equal to `self`, `self` is returned + * (referential shortcut). + * + * **Example** (Combining two causes) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const combined = Cause.combine(Cause.fail("error1"), Cause.fail("error2")) + * combined // => Cause.fromReasons([Cause.makeFailReason("error1"), Cause.makeFailReason("error2")]) + * ``` + * + * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining + * + * @category combining + * @since 4.0.0 + */ +const combine = _internal_effect_js__rspack_import_1/* .causeCombine */.h2c; +/** + * Collapses a `Cause` into a single `unknown` value, picking the "most + * important" failure in this order: + * + * **When to use** + * + * Use to collapse a structured cause to the single value that synchronous and + * promise runners would throw. + * + * **Details** + * + * 1. First `Fail` error (the `E` value) + * 2. First `Die` defect + * 3. A generic `Error("All fibers interrupted without error")` for interrupt-only causes + * 4. A generic `Error("Empty cause")` for `empty` + * + * This is the function used by `Effect.runPromise` and `Effect.runSync` to + * decide what to throw. + * + * **Gotchas** + * + * This function is lossy. Use {@link prettyErrors} or iterate `cause.reasons` + * when you need all failures. + * + * **Example** (Squashing a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.squash(Cause.fail("error")) // => "error" + * Cause.squash(Cause.die("defect")) // => "defect" + * ``` + * + * @see {@link prettyErrors} — non-lossy conversion to `Array` + * @see {@link pretty} — human-readable string rendering + * + * @category destructors + * @since 2.0.0 + */ +const squash = _internal_effect_js__rspack_import_1/* .causeSquash */.ReC; +/** + * Returns `true` if the cause contains at least one `Fail` reason. + * + * **When to use** + * + * Use to check whether a cause includes typed failures before extracting, + * mapping, or rendering them. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasFails(Cause.fail("error")) // => true + * Cause.hasFails(Cause.die("defect")) // => false + * ``` + * + * @see {@link hasDies} — check for defects + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .hasFails */.myX; +/** + * Returns a `Result` whose success value is the first `Fail` reason in + * the cause, including its annotations. If the cause has no `Fail` reason, the + * failure value is the original cause narrowed to `Cause`, because it + * contains no typed error reasons. + * + * **When to use** + * + * Use when you need the full `Fail` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Fail reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findFail(Cause.fail("error")) // => Result.succeed(Cause.makeFailReason("error")) + * ``` + * + * @see {@link findError} — extract the unwrapped `E` value + * @see {@link findDie} — extract the first `Die` reason + * + * @category filtering + * @since 4.0.0 + */ +const findFail = _internal_effect_js__rspack_import_1/* .findFail */.QE5; +/** + * Returns a `Result` whose success value is the first typed error value `E` + * from a `Fail` reason in the cause. If the cause has no `Fail` reason, + * the failure value is the original cause narrowed to `Cause`, because + * it contains no typed error reasons. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as a `Result` + * that preserves the original cause when no match is found. + * + * **Example** (Extracting the first error value) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findError(Cause.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link findFail} — extract the full `Fail` reason + * @see {@link findErrorOption} — `Option`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .findError */.khU; +/** + * Returns the first typed error value `E` from a cause wrapped in + * `Option.some`, or `Option.none` if no `Fail` reason exists. + * + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as an `Option`, + * discarding the original cause. + * + * **Example** (Extracting an error as Option) + * + * ```ts import.meta.vitest + * import { Cause, Option } from "effect" + * + * Cause.findErrorOption(Cause.fail("error")) // => Option.some("error") + * Cause.findErrorOption(Cause.die("defect")) // => Option.none() + * ``` + * + * @see {@link findError} — `Result`-based variant + * + * @category filtering + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .findErrorOption */.L$u; +/** + * Returns `true` if the cause contains at least one `Die` reason. + * + * **When to use** + * + * Use to check whether a cause includes defects before extracting or rendering + * them. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasDies(Cause.die("defect")) // => true + * Cause.hasDies(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasFails} — check for typed errors + * @see {@link hasInterrupts} — check for interruptions + * + * @category predicates + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .hasDies */.gpn; +/** + * Returns a `Result` whose success value is the first `Die` reason in + * the cause, including its annotations. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the full `Die` reason from a `Cause`, including + * annotations. + * + * **Example** (Extracting the first Die reason) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDie(Cause.die("defect")) // => Result.succeed(Cause.makeDieReason("defect")) + * ``` + * + * @see {@link findDefect} — extract the unwrapped defect value + * @see {@link findFail} — extract the first `Fail` reason + * + * @category filtering + * @since 4.0.0 + */ +const findDie = _internal_effect_js__rspack_import_1/* .findDie */.k7S; +/** + * Returns a `Result` whose success value is the first defect value from a + * `Die` reason in the cause. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** + * + * Use when you need the first defect value from a `Cause` as a `Result`, + * without the full `Die` reason. + * + * **Example** (Extracting the first defect) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findDefect(Cause.die("defect")) // => Result.succeed("defect") + * ``` + * + * @see {@link findDie} — extract the full `Die` reason + * @see {@link findError} — extract the first typed error + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .findDefect */.BbX; +/** + * Returns `true` if the cause contains at least one `Interrupt` reason. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.hasInterrupts(Cause.interrupt(123)) // => true + * Cause.hasInterrupts(Cause.fail("error")) // => false + * ``` + * + * @see {@link hasInterruptsOnly} — `true` only when *all* reasons are interrupts + * @see {@link hasFails} — check for typed errors + * @see {@link hasDies} — check for defects + * + * @category predicates + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .hasInterrupts */.prj; +/** + * Returns a `Result` whose success value is the first `Interrupt` reason + * in the cause, including its annotations. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need the first `Interrupt` reason from a `Cause`, including the + * fiber ID and annotations. + * + * **Example** (Extracting the first interrupt) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.findInterrupt(Cause.interrupt(42)) // => Result.succeed(Cause.makeInterruptReason(42)) + * ``` + * + * @see {@link interruptors} — collect all interrupting fiber IDs as a `Set` + * + * @category filtering + * @since 4.0.0 + */ +const findInterrupt = _internal_effect_js__rspack_import_1/* .findInterrupt */.tU5; +/** + * Collects the defined fiber IDs from all `Interrupt` reasons in the + * cause into a `ReadonlySet`. Interrupt reasons without a `fiberId` are + * ignored. Returns an empty set when the cause has no interrupting fiber IDs. + * + * **When to use** + * + * Use when you need interrupting fiber IDs as a set, with absence represented + * as an empty set. + * + * **Example** (Collecting interruptors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * const cause = Cause.combine( + * Cause.interrupt(1), + * Cause.interrupt(2) + * ) + * + * Cause.interruptors(cause) // => new Set([1, 2]) + * ``` + * + * @see {@link filterInterruptors} — `Result`-based variant + * + * @category getters + * @since 2.0.0 + */ +const interruptors = _internal_effect_js__rspack_import_1/* .causeInterruptors */.h74; +/** + * Returns a `Result` whose success value is the set of defined fiber IDs from + * the cause's `Interrupt` reasons. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need absence of interrupt reasons to fail with the original + * cause. + * + * **Gotchas** + * + * Interrupt reasons without a `fiberId` still count as interrupts, so the + * function succeeds with an empty `Set` when every interrupt reason has an + * undefined fiber ID. + * + * **Example** (Extracting interruptors with Result) + * + * ```ts import.meta.vitest + * import { Cause, Result } from "effect" + * + * Cause.filterInterruptors(Cause.interrupt(1)) // => Result.succeed(new Set([1])) + * ``` + * + * @see {@link interruptors} — always-succeeding variant + * + * @category filtering + * @since 4.0.0 + */ +const filterInterruptors = _internal_effect_js__rspack_import_1/* .causeFilterInterruptors */.Bou; +/** + * Converts a `Cause` into an `Array` suitable for logging or + * rethrowing. + * + * **When to use** + * + * Use to convert every renderable failure in a cause into individual `Error` + * values before logging or rethrowing. + * + * **Details** + * + * Each `Fail` and `Die` reason is converted into a standard + * `Error`: + * + * - **Objects / Error instances** — `message`, `name`, `stack`, and `cause` + * are preserved. Extra enumerable properties are copied. Stack traces are + * cleaned up and enriched with span annotations when available. + * - **Strings** — used directly as the `Error` message. + * - **Other primitives** (`null`, `undefined`, numbers, …) — wrapped in an + * `Error` with message `"Unknown error: "`. + * + * `Interrupt` reasons are collected separately. If the cause contains + * **only** interrupts (no `Fail` or `Die`), a single `InterruptError` is + * returned whose `cause` lists the interrupting fiber IDs. + * + * An empty cause returns an empty array. + * + * **Example** (Converting a cause to errors) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.prettyErrors(Cause.fail(new Error("boom")))[0].message // => "boom" + * ``` + * + * @see {@link pretty} — renders the cause as a single string + * @see {@link squash} — lossy collapse to a single thrown value + * + * @category formatting + * @since 3.2.0 + */ +const prettyErrors = _internal_effect_js__rspack_import_1/* .causePrettyErrors */.RJ6; +/** + * Formats a `Cause` as a human-readable string for logging or debugging. + * + * **When to use** + * + * Use to render a whole cause as one human-readable string for logs or + * diagnostics. + * + * **Details** + * + * Delegates to {@link prettyErrors} to convert each reason to an `Error`, + * then joins their stack traces with newlines. Nested `Error.cause` chains + * are rendered inline with indentation: + * + * ```text + * ErrorName: message + * at ... + * at ... { + * [cause]: NestedError: message + * at ... + * } + * ``` + * + * Span annotations are appended to the relevant stack frames when available. + * + * **Gotchas** + * + * Rendering an empty cause produces an empty string because there are no + * errors to render. + * + * **Example** (Rendering a cause) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.pretty(Cause.fail("something went wrong")).includes("something went wrong") // => true + * ``` + * + * @see {@link prettyErrors} — get the individual `Error` instances + * + * @category formatting + * @since 2.0.0 + */ +const pretty = _internal_effect_js__rspack_import_1/* .causePretty */.GyP; +/** + * Checks whether an arbitrary value is a `NoSuchElementError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isNoSuchElementError(new Cause.NoSuchElementError()) // => true + * Cause.isNoSuchElementError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isNoSuchElementError = _internal_core_js__rspack_import_0/* .isNoSuchElementError */.PW; +/** + * Unique brand for `NoSuchElementError`. + * + * @category type IDs + * @since 4.0.0 + */ +const NoSuchElementErrorTypeId = _internal_core_js__rspack_import_0/* .NoSuchElementErrorTypeId */.qB; +/** + * Constructs a `NoSuchElementError` with an optional message. + * + * **When to use** + * + * Use to create the error value for APIs that intentionally fail when an + * expected element is absent. + * + * **Example** (Creating a NoSuchElementError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.NoSuchElementError("Element not found").message // => "Element not found" + * ``` + * + * @see {@link isNoSuchElementError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const NoSuchElementError = _internal_core_js__rspack_import_0/* .NoSuchElementError */.Xm; +/** + * Checks whether an arbitrary value is a `Done` signal. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isDone(Cause.Done()) // => true + * Cause.isDone("not done") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isDone = _internal_core_js__rspack_import_0/* .isDone */.$L; +/** + * Unique brand for `Done` values. + * + * @category type IDs + * @since 4.0.0 + */ +const DoneTypeId = _internal_core_js__rspack_import_0/* .DoneTypeId */.q_; +/** + * Creates a `Done` signal with an optional value. + * + * **When to use** + * + * Use when you need to construct a low-level pull completion signal directly. + * + * @see {@link done} — create a failing `Effect` with `Done` + * + * @category constructors + * @since 4.0.0 + */ +const Done = _internal_core_js__rspack_import_0/* .Done */.RS; +/** + * Creates an Effect that fails with a `Done` error. Shorthand for + * `Effect.fail(Cause.Done(value))`. + * + * **When to use** + * + * Use when you model stream or queue completion through the error channel. + * + * **Example** (Failing with Done) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const program = Cause.done("finished") + * + * await Effect.runPromiseExit(program) // => Exit.fail(Cause.Done("finished")) + * ``` + * + * @see {@link Done} — create the signal value without an Effect + * + * @category constructors + * @since 4.0.0 + */ +const done = _internal_core_js__rspack_import_0/* .done */.Vw; +/** + * Unique brand for `TimeoutError`. + * + * @category type IDs + * @since 4.0.0 + */ +const TimeoutErrorTypeId = _internal_effect_js__rspack_import_1/* .TimeoutErrorTypeId */.DQo; +/** + * Checks whether an arbitrary value is a `TimeoutError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isTimeoutError(new Cause.TimeoutError()) // => true + * Cause.isTimeoutError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isTimeoutError = _internal_effect_js__rspack_import_1/* .isTimeoutError */.c8t; +/** + * Constructs a `TimeoutError` with an optional message. + * + * **Example** (Creating a TimeoutError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.TimeoutError("Operation timed out").message // => "Operation timed out" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const TimeoutError = _internal_effect_js__rspack_import_1/* .TimeoutError */.MUS; +/** + * Unique brand for `IllegalArgumentError`. + * + * @category type IDs + * @since 4.0.0 + */ +const IllegalArgumentErrorTypeId = _internal_effect_js__rspack_import_1/* .IllegalArgumentErrorTypeId */.t8c; +/** + * Checks whether an arbitrary value is an `IllegalArgumentError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isIllegalArgumentError(new Cause.IllegalArgumentError()) // => true + * Cause.isIllegalArgumentError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isIllegalArgumentError = _internal_effect_js__rspack_import_1/* .isIllegalArgumentError */._y; +/** + * Constructs an `IllegalArgumentError` with an optional message. + * + * **Example** (Creating an IllegalArgumentError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.IllegalArgumentError("Invalid argument").message // => "Invalid argument" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const IllegalArgumentError = _internal_effect_js__rspack_import_1/* .IllegalArgumentError */.qwd; +/** + * Checks whether an arbitrary value is an `ExceededCapacityError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isExceededCapacityError(new Cause.ExceededCapacityError()) // => true + * Cause.isExceededCapacityError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isExceededCapacityError = _internal_effect_js__rspack_import_1/* .isExceededCapacityError */.ASO; +/** + * Unique brand for `ExceededCapacityError`. + * + * @category type IDs + * @since 4.0.0 + */ +const ExceededCapacityErrorTypeId = _internal_effect_js__rspack_import_1/* .ExceededCapacityErrorTypeId */.F7W; +/** + * Constructs an `ExceededCapacityError` with an optional message. + * + * **When to use** + * + * Use to create the error value for bounded-resource capacity failures. + * + * **Example** (Creating an ExceededCapacityError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.ExceededCapacityError("Queue full").message // => "Queue full" + * ``` + * + * @see {@link isExceededCapacityError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const ExceededCapacityError = _internal_effect_js__rspack_import_1/* .ExceededCapacityError */.Aub; +/** + * Unique brand present on `AsyncFiberError` values and used by + * `isAsyncFiberError` for runtime checks. + * + * @category type IDs + * @since 4.0.0 + */ +const AsyncFiberErrorTypeId = _internal_effect_js__rspack_import_1/* .AsyncFiberErrorTypeId */.cOF; +/** + * Checks whether an arbitrary value is an `AsyncFiberError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * const error = new Cause.AsyncFiberError(fiber) + * Cause.isAsyncFiberError(error) // => true + * Cause.isAsyncFiberError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isAsyncFiberError = _internal_effect_js__rspack_import_1/* .isAsyncFiberError */.Rft; +/** + * Constructs an `AsyncFiberError` for a fiber that could not be resolved + * synchronously. + * + * **When to use** + * + * Use to create the error value for a fiber that could not be completed by a + * synchronous runner. + * + * **Example** (Creating an AsyncFiberError) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const fiber = Effect.runFork(Effect.void) + * + * new Cause.AsyncFiberError(fiber).message // => "An asynchronous Effect was executed with Effect.runSync" + * ``` + * + * @see {@link isAsyncFiberError} for checking unknown values + * + * @category constructors + * @since 4.0.0 + */ +const AsyncFiberError = _internal_effect_js__rspack_import_1/* .AsyncFiberError */.RD4; +/** + * Unique brand for `UnknownError`. + * + * @category type IDs + * @since 4.0.0 + */ +const UnknownErrorTypeId = _internal_effect_js__rspack_import_1/* .UnknownErrorTypeId */.Kkt; +/** + * Checks whether an arbitrary value is an `UnknownError`. + * + * **Example** (Checking the runtime type) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * Cause.isUnknownError(new Cause.UnknownError("x")) // => true + * Cause.isUnknownError("nope") // => false + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isUnknownError = _internal_effect_js__rspack_import_1/* .isUnknownError */.PnV; +/** + * Constructs an `UnknownError`. The first argument is the original + * cause (stored in `Error.cause`); the second is an optional human-readable + * message. + * + * **Example** (Creating an UnknownError) + * + * ```ts import.meta.vitest + * import { Cause } from "effect" + * + * new Cause.UnknownError({ raw: true }, "Unexpected value").message // => "Unexpected value" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const UnknownError = _internal_effect_js__rspack_import_1/* .UnknownError */.Bk6; +/** + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** + * + * Annotations are stored as a `Context` on each reason and can be + * retrieved later via {@link reasonAnnotations} or {@link annotations}. + * The runtime uses this to attach stack traces and spans. + * + * - Returns a new `Cause`. + * - By default, existing keys are preserved. Pass `{ overwrite: true }` to + * replace them. + * + * **Example** (Annotating a cause) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const annotated = Cause.annotate(Cause.fail("error"), Context.make(RequestId, "req-1")) + * Context.getOrUndefined(Cause.annotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotate = _internal_core_js__rspack_import_0/* .causeAnnotate */.Eh; +/** + * Reads the annotations from a single `Reason` as a `Context`. + * + * **When to use** + * + * Use when you need tracing metadata (e.g. `StackTrace`) from + * a specific reason rather than the whole cause. + * + * **Example** (Reading reason annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const reason = Cause.makeFailReason("error") + * const annotated = reason.annotate(Context.make(RequestId, "req-1")) + * + * Context.getOrUndefined(Cause.reasonAnnotations(annotated), RequestId) // => "req-1" + * ``` + * + * @see {@link annotations} — merged annotations from all reasons in a cause + * + * @category annotations + * @since 4.0.0 + */ +const reasonAnnotations = _internal_effect_js__rspack_import_1/* .reasonAnnotations */.tQ6; +/** + * Reads the merged annotations from all reasons in a `Cause`. + * + * **When to use** + * + * Use to read diagnostic metadata merged from the whole cause. + * + * **Gotchas** + * + * When multiple reasons contain the same annotation key, the value from the + * later reason wins. + * + * **Example** (Reading merged annotations) + * + * ```ts import.meta.vitest + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const cause = Cause.annotate( + * Cause.fail("error"), + * Context.make(RequestId, "req-1") + * ) + * + * Context.getOrUndefined(Cause.annotations(cause), RequestId) // => "req-1" + * ``` + * + * @see {@link reasonAnnotations} — annotations from a single reason + * + * @category annotations + * @since 4.0.0 + */ +const annotations = _internal_effect_js__rspack_import_1/* .causeAnnotations */.On5; +/** + * Context annotation used to store the stack frame captured at the point of failure. + * + * **When to use** + * + * Use to read the failure stack-frame annotation from a `Reason` when building + * diagnostics, logging, or custom cause renderers. + * + * **Details** + * + * The runtime annotates every reason with this when a stack frame is + * available. Retrieve it via + * `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`. + * + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link InterruptorStackTrace} for the interrupt-specific stack-frame annotation + * + * @category services + * @since 4.0.0 + */ +class StackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/StackTrace"))) {} +/** + * Context annotation used to store the stack frame captured at the point of + * interruption. + * + * **When to use** + * + * Use when you need the stack-frame annotation used by interrupt-only cause + * rendering. + * + * **Details** + * + * Similar to `StackTrace` but specific to `Interrupt` reasons. + * + * @see {@link StackTrace} for stack frames attached to failures + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotate} for attaching annotations to a cause + * + * @category services + * @since 4.0.0 + */ +class InterruptorStackTrace extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Cause/InterruptorStackTrace"))) {} +//# sourceMappingURL=Cause.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + $L: isDone, + Vw: done, + iw: squash, + kO: fromReasons, + nn: hasInterruptsOnly +}); + + +}, +"./node_modules/effect/dist/Combiner.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Creates a `Combiner` from a binary function. + * + * **When to use** + * + * Use when you have a custom combining operation that is not covered by + * the built-in constructors (`min`, `max`, `first`, `last`, `constant`). + * + * **Details** + * + * The returned combiner's `combine` method delegates to the provided function. + * Any purity, associativity, or mutation behavior comes from that function. + * + * **Example** (Multiplying numbers) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Product = Combiner.make((self, that) => self * that) + * + * Product.combine(3, 5) // => 15 + * ``` + * + * @see {@link Combiner} – the interface this creates + * @category constructors + * @since 4.0.0 + */ +function make(combine) { + return { + combine + }; +} +/** + * Reverses the argument order of a combiner's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative combiner such as string concatenation. + * + * **Details** + * + * Returns a new `Combiner` where `combine(self, that)` calls the original + * combiner as `combine(that, self)`. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const Prepend = Combiner.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function flip(combiner) { + return make((self, that) => combiner.combine(that, self)); +} +/** + * Creates a `Combiner` that returns the smaller of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the minimum value across a collection or + * build a `Reducer` that tracks the running minimum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the minimum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Min = Combiner.min(Number.Order) + * + * Min.combine(3, 1) // => 1 + * Min.combine(1, 3) // => 1 + * ``` + * + * @see {@link max} + * @category constructors + * @since 4.0.0 + */ +function min(order) { + return make((self, that) => order(self, that) === -1 ? self : that); +} +/** + * Creates a `Combiner` that returns the larger of two values according to + * the provided `Order`. + * + * **When to use** + * + * Use when you want to accumulate the maximum value across a collection or + * build a `Reducer` that tracks the running maximum. + * + * **Details** + * + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). + * + * **Example** (Selecting the maximum of two numbers) + * + * ```ts import.meta.vitest + * import { Combiner, Number } from "effect" + * + * const Max = Combiner.max(Number.Order) + * + * Max.combine(3, 1) // => 3 + * Max.combine(1, 3) // => 3 + * ``` + * + * @see {@link min} + * @category constructors + * @since 4.0.0 + */ +function max(order) { + return make((self, that) => order(self, that) === 1 ? self : that); +} +/** + * Creates a `Combiner` that always returns the first (left) argument. + * + * **When to use** + * + * Use when you want "first write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `self` and ignores `that`. + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const First = Combiner.first() + * + * First.combine(1, 2) // => 1 + * ``` + * + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function first() { + return make((self, _) => self); +} +/** + * Creates a `Combiner` that always returns the last (right) argument. + * + * **When to use** + * + * Use when you want "last write wins" semantics while merging values. + * + * **Details** + * + * `combine(self, that)` returns `that` and ignores `self`. + * + * **Example** (Keeping the last value) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Last = Combiner.last() + * + * Last.combine(1, 2) // => 2 + * ``` + * + * @see {@link first} + * @category constructors + * @since 4.0.0 + */ +function last() { + return make((_, that) => that); +} +/** + * Creates a `Combiner` that ignores both arguments and always returns the + * given constant value. + * + * **When to use** + * + * Use when you need a combiner that always returns a fixed value, including + * when a generic API requires a combiner but the result is predetermined. + * + * **Details** + * + * `combine(self, that)` returns the constant `a` and ignores both arguments. + * + * **Example** (Always returning zero) + * + * ```ts import.meta.vitest + * import { Combiner } from "effect" + * + * const Zero = Combiner.constant(0) + * + * Zero.combine(42, 99) // => 0 + * ``` + * + * @see {@link first} + * @see {@link last} + * @category constructors + * @since 4.0.0 + */ +function constant(a) { + return make(() => a); +} +/** + * Wraps a `Combiner` so that a separator value is inserted between every + * pair of combined elements. + * + * **When to use** + * + * Use when you need to inject a fixed separator between accumulated values, + * such as when building delimited strings, paths, or CSV-like output by + * repeated combination. + * + * **Details** + * + * `intercalate(middle)(combiner).combine(self, that)` is equivalent to + * `combiner.combine(self, combiner.combine(middle, that))`. This function is + * curried: first provide the separator, then the base combiner. + * + * **Example** (Joining strings with a separator) + * + * ```ts import.meta.vitest + * import { Combiner, String } from "effect" + * + * const commaSep = Combiner.intercalate(",")(String.ReducerConcat) + * + * commaSep.combine("a", "b") // => "a,b" + * ``` + * + * @see {@link make} + * @category combinators + * @since 4.0.0 + */ +function intercalate(middle) { + return combiner => make((self, that) => combiner.combine(self, combiner.combine(middle, that))); +} +//# sourceMappingURL=Combiner.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make) +}); + + +}, +"./node_modules/effect/dist/Context.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Effectable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Effectable.js"); +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _Option_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); + + + + + + + +/** + * Runtime type identifier attached to `Context` service keys and used by + * `isKey` to recognize them. + * + * @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 + * + * @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__*/_Effectable_js__rspack_import_0/* .Prototype */.b({ + label: "Service", + evaluate(fiber) { + return (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => f(get(fiber.context, this))); + }, + useSync(f) { + return (0,_internal_core_js__rspack_import_1/* .withFiber */.R6)(fiber => (0,_internal_core_js__rspack_import_1/* .exitSucceed */.xt)(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId = "~effect/Context"; +const MaxDepth = 8; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = undefined; + self.baseHits = 0; + 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 makeUnsafe(map); +}; +// A private symbol so user code cannot forge a value that reads as absent +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); + // Misses must not advance the counter: reference-default lookups miss the + // base on every fiber cache refresh, which would flatten every short-lived + // request context and reintroduce the O(services) per-request cost + if (value === undefined && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = undefined; + 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. + * + * **Gotchas** + * + * 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 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = mapUnsafe => makeImpl(undefined, mapUnsafe, undefined, 0); +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ..._internal_core_js__rspack_import_1/* .PipeInspectableProto */.fU, + [TypeId]: { + _Services: _ => _ + }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](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) || !_Equal_js__rspack_import_2/* .equals */.aI(value, other.get(key))) return false; + } + return true; + }, + [_Hash_js__rspack_import_3/* .symbol */.HR]() { + return _Hash_js__rspack_import_3/* .number */.ai(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 + * + * @category guards + * @since 2.0.0 + */ +const isContext = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether the provided argument is a `Key`. + * + * **Example** (Checking for keys) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * Context.isKey(Context.Service("Service")) // => true + * ``` + * + * @category guards + * @since 4.0.0 + */ +const isKey = u => hasProperty(u, ServiceTypeId); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => emptyContext; +const emptyContext = /*#__PURE__*/makeUnsafe(/*#__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 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = (key, service) => makeUnsafe(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` + * + * @category combining + * @since 2.0.0 + */ +const add = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** + * Adds a service by key to a given `Context` using a string key. + * + * @category combining + * @since 4.0.0 + */ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? undefined : impl.cacheRoot; + if (impl.depth >= MaxDepth) { + // Rebase the overlay chain into a flat map, keeping the cacheRoot so a + // rebase on an ordinary key does not invalidate fiber caches + const map = new Map(impl.mapUnsafe); + map.set(key, service); + return makeImpl(cacheRoot, map, undefined, 0); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1); +}; +/** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts import.meta.vitest + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * Context.getOption(withPort, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(withoutPort, Port) // => Option.none() + * ``` + * + * @see {@link add} for always storing a service value + * + * @category combining + * @since 4.0.0 + */ +const addOrOmit = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, service) => service._tag === "None" ? omit(key)(self) : add(self, key, service.value)))); +/** + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) + * + * ```ts import.meta.vitest + * import { Context } from "effect" + * + * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") + * const Database = Context.Service<{ query: (sql: string) => string }>( + * "Database" + * ) + * + * const context = Context.make(Logger, { log: (_msg: string) => {} }) + * + * const logger = Context.getOrElse(context, Logger, () => ({ log: () => {} })) + * const database = Context.getOrElse( + * context, + * Database, + * () => ({ query: () => "fallback" }) + * ) + * + * logger === Context.get(context, Logger) // => true + * database.query("SELECT 1") // => "fallback" + * ``` + * + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, orElse) => { + const value = lookup(self, key.key); + if (value !== notFound) return value; + return isReference(key) ? getDefaultValue(key) : orElse(); +}))); +/** + * 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 + * + * @category getters + * @since 4.0.0 + */ +const getOrUndefined = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? undefined : 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 + * + * @category unsafe + * @since 4.0.0 + */ +const getUnsafe = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @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 = 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 + * + * @category getters + * @since 2.0.0 + */ +const getOption = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, service) => { + const value = lookup(self, service.key); + if (value !== notFound) return _Option_js__rspack_import_6.some(value); + return isReference(service) ? _Option_js__rspack_import_6.some(getDefaultValue(service)) : _Option_js__rspack_import_6.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 + * + * @category combining + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(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 + * + * @category combining + * @since 3.12.0 + */ +const mergeAll = (...ctxs) => { + const map = new Map(); + for (let i = 0; i < ctxs.length; i++) { + ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + } + return makeUnsafe(map); +}; +/** + * Returns a new `Context` that contains only the specified services. + * + * **When to use** + * + * Use when you want to keep an allowlist of services in a `Context`. + * + * **Example** (Picking services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.pick(Port)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link omit} for removing selected services + * + * @category filtering + * @since 2.0.0 + */ +const pick = (...services) => self => { + const keep = new Set(services.map(key => key.key)); + return withFlat(self, map => map.forEach((_, key) => { + if (!keep.has(key)) map.delete(key); + })); +}; +/** + * Returns a new `Context` with the specified service keys removed. + * + * **When to use** + * + * Use when you want to remove a denylist of services from a `Context`. + * + * **Example** (Omitting services from a context) + * + * ```ts import.meta.vitest + * import { Context, Option, pipe } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") + * + * const someContext = pipe( + * Context.make(Port, { PORT: 8080 }), + * Context.add(Timeout, { TIMEOUT: 5000 }) + * ) + * + * const context = pipe(someContext, Context.omit(Timeout)) + * + * Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) + * Context.getOption(context, Timeout) // => Option.none() + * ``` + * + * @see {@link pick} for keeping selected services + * + * @category filtering + * @since 2.0.0 + */ +const omit = (...keys) => self => withFlat(self, map => { + for (let i = 0; i < keys.length; i++) { + map.delete(keys[i].key); + } +}); +/** + * 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 + * + * @category services + * @since 3.11.0 + */ +const Reference = Service; +//# sourceMappingURL=Context.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Ie: empty, + Jt: get, + L8: make, + LZ: makeUnsafe, + Or: Reference, + Pf: hasSameCache, + Ub: getOrUndefinedUnsafe, + Um: mergeAll, + WQ: add, + Y6: getOrUndefined, + aE: isContext, + fp: getUnsafe, + h1: merge, + kl: Service, + om: getOption +}); + + +}, +"./node_modules/effect/dist/Deferred.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); + + + + + + +const TypeId = "~effect/Deferred"; +/** + * Checks whether a value is a `Deferred`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Deferred` values. + * + * @category guards + * @since 4.0.0 + */ +const isDeferred = u => hasProperty(u, TypeId); +const DeferredProto = { + [TypeId]: { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const makeUnsafe = () => { + const self = Object.create(DeferredProto); + self.resumes = undefined; + self.effect = undefined; + return self; +}; +/** + * Creates a new `Deferred`. + * + * **When to use** + * + * Use to allocate an empty `Deferred` inside an `Effect` workflow. + * + * **Example** (Creating a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = () => internalEffect.sync(() => makeUnsafe()); +const _await = self => _internal_effect_js__rspack_import_2/* .callback */.E2r(resume => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return _internal_effect_js__rspack_import_2/* .sync */.OH5(() => { + // Completion resumes all waiters and clears `resumes`, so a cleanup + // running after completion has nothing to unregister. + const resumes = self.resumes; + if (resumes === undefined) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); + +/** + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. + * + * **When to use** + * + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.complete(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.suspend(() => self.effect ? internalEffect.succeed(false) : into(effect, self))))); +/** + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const completed = yield* Deferred.completeWith(deferred, Effect.succeed(42)) + * const value = yield* Deferred.await(deferred) + * return [completed, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion + * @since 2.0.0 + */ +const completeWith = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, effect) => _internal_effect_js__rspack_import_2/* .sync */.OH5(() => doneUnsafe(self, effect))); +/** + * Completes the `Deferred` with the specified `Exit` value, which will be + * propagated to all fibers waiting on the value of the `Deferred`. + * + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.done(deferred, Exit.succeed(42)) + * return yield* Effect.exit(Deferred.await(deferred)) + * }) + * + * await Effect.runPromise(program) // => Exit.succeed(42) + * ``` + * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion + * @since 2.0.0 + */ +const done = completeWith; +/** + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.fail(deferred, "Operation failed") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Operation failed")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, error) => done(self, core.exitFail(error))))); +/** + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failSync(deferred, () => "Lazy error") + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.fail("Lazy error")] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => fail(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCause(deferred, Cause.fail("Operation failed")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Operation failed"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => done(self, core.exitFailCause(cause))))); +/** + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) + * + * ```ts import.meta.vitest + * import { Cause, Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.failCauseSync(deferred, () => Cause.fail("Lazy error")) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.failCause(Cause.fail("Lazy error"))] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const failCauseSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => failCause(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Something went wrong") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.die(deferred, defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const die = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, defect) => done(self, core.exitDie(defect))))); +/** + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const defect = new Error("Lazy error") + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.dieSync(deferred, () => defect) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.die(defect)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const dieSync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => die(self, evaluate()))))); +/** + * Attempts to complete the `Deferred` with interruption by the current fiber. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by the current fiber. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with the current fiber id + * only if this call completes it. The returned effect succeeds with `true` + * when this call completed the `Deferred`, or `false` if it was already + * completed. + * + * **Example** (Interrupting a Deferred) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interrupt(deferred) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] as const + * }) + * + * const [success, exit] = await Effect.runPromise(program) + * success // => true + * Exit.hasInterrupts(exit) // => true + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interrupt = self => core.withFiber(fiber => interruptWith(self, fiber.id)); +/** + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Exit } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const success = yield* Deferred.interruptWith(deferred, 42) + * const exit = yield* Effect.exit(Deferred.await(deferred)) + * return [success, exit] + * }) + * + * await Effect.runPromise(program) // => [true, Exit.interrupt(42)] + * ``` + * + * @category completion + * @since 2.0.0 + */ +const interruptWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, fiberId) => failCause(self, internalEffect.causeInterrupt(fiberId))))); +/** + * Returns `true` if this `Deferred` has already been completed with a value or + * an error, `false` otherwise. + * + * **When to use** + * + * Use to check completion status inside an `Effect` workflow. + * + * **Example** (Checking Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.isDone(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.isDone(deferred) + * return [beforeCompletion, afterCompletion] + * }) + * + * await Effect.runPromise(program) // => [false, true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isDone = self => internalEffect.sync(() => isDoneUnsafe(self)); +/** + * Returns whether this `Deferred` has already been completed synchronously. + * + * **When to use** + * + * Use to check `Deferred` completion synchronously in code that cannot return + * an `Effect`, such as low-level integration code. + * + * @see {@link isDone} for checking completion inside `Effect` + * @see {@link poll} for reading the completed effect when available + * + * @category predicates + * @since 4.0.0 + */ +const isDoneUnsafe = self => self.effect !== undefined; +/** + * Returns the current completion effect as an `Option`. This returns + * `Option.some(effect)` when the `Deferred` is completed, `Option.none()` + * otherwise. + * + * **When to use** + * + * Use to inspect whether a `Deferred` is already completed and retrieve its + * stored completion effect when available. + * + * **Example** (Polling Deferred completion) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, Option } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const beforeCompletion = yield* Deferred.poll(deferred) + * yield* Deferred.succeed(deferred, 42) + * const afterCompletion = yield* Deferred.poll(deferred) + * const afterValue = yield* Effect.transposeOption(afterCompletion) + * return [beforeCompletion, afterValue] + * }) + * + * await Effect.runPromise(program) // => [Option.none(), Option.some(42)] + * ``` + * + * @category getters + * @since 2.0.0 + */ +function poll(self) { + return internalEffect.sync(() => Option.fromUndefinedOr(self.effect)); +} +/** + * Attempts to complete the `Deferred` with the specified value. + * + * **When to use** + * + * Use to complete a `Deferred` with a successful value. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.succeed(deferred, 42) + * + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, value) => done(self, core.exitSucceed(value))))); +/** + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * yield* Deferred.sync(deferred, () => 42) + * return yield* Deferred.await(deferred) + * }) + * + * await Effect.runPromise(program) // => 42 + * ``` + * + * @category completion + * @since 2.0.0 + */ +const sync = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, evaluate) => internalEffect.suspend(() => succeed(self, evaluate()))))); +/** + * 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 + * ``` + * + * @category unsafe + * @since 4.0.0 + */ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + // Clear `resumes` before resuming: a waiter resumed with an interrupt + // cause dies synchronously inside `resume`, and its await cleanup would + // otherwise splice this array mid-iteration and skip the next waiter. + const resumes = self.resumes; + self.resumes = undefined; + for (let i = 0; i < resumes.length; i++) { + resumes[i](effect); + } + } + return true; +}; +/** + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. + * + * **Details** + * + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) + * + * ```ts import.meta.vitest + * import { Deferred, Effect } from "effect" + * + * const successEffect = Effect.succeed(42) + * + * const program = Effect.gen(function*() { + * const deferred = yield* Deferred.make() + * const isCompleted = yield* Deferred.into(successEffect, deferred) + * const value = yield* Deferred.await(deferred) + * return [isCompleted, value] + * }) + * + * await Effect.runPromise(program) // => [true, 42] + * ``` + * + * @category completion + * @since 4.0.0 + */ +const into = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, deferred) => internalEffect.uninterruptibleMask(restore => internalEffect.flatMap(internalEffect.exit(restore(self)), exit => done(deferred, exit)))))); +//# sourceMappingURL=Deferred.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + LZ: makeUnsafe, + Tx: _await, + Vw: done +}); + + +}, +"./node_modules/effect/dist/Duration.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Function_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Represents immutable spans of time. + * + * A `Duration` can be finite, positive infinity, or negative infinity. It is + * the standard representation for delays, timeouts, intervals, and + * time-to-live values across Effect APIs. This module includes constructors + * from common input shapes, unit conversions, comparisons, arithmetic, + * formatting, and reusable reducer or combiner helpers. + * + * @since 2.0.0 + */ + + + + + + + + + + +const TypeId = "~effect/time/Duration"; +const bigint0 = /*#__PURE__*/BigInt(0); +const bigint1 = /*#__PURE__*/BigInt(1); +const bigint2 = /*#__PURE__*/BigInt(2); +const bigint10 = /*#__PURE__*/BigInt(10); +const bigint24 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(24))); +const bigint60 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(60))); +const bigint1e3 = /*#__PURE__*/BigInt(1_000); +const bigint1e6 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000))); +const bigint1e9 = /*#__PURE__*/(/* unused pure expression or super */ null && (BigInt(1_000_000_000))); +const roundTiesAwayFromZero = input => BigInt(input < 0 ? Math.ceil(input - 0.5) : Math.floor(input + 0.5)); +const roundMillisToNanos = millis => roundTiesAwayFromZero(millis * 1_000_000); +const parseNanos = (input, scale) => { + const decimalIndex = input.indexOf("."); + if (decimalIndex === -1) return BigInt(input) * scale; + const isNegative = input[0] === "-"; + const fractional = input.slice(decimalIndex + 1); + const fractionalScale = bigint10 ** BigInt(fractional.length); + const scaled = (BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) * scale; + const rounded = scaled / fractionalScale + (scaled % fractionalScale * bigint2 >= fractionalScale ? bigint1 : bigint0); + return isNegative ? -rounded : rounded; +}; +const nanosToHrTime = nanos => { + const sign = nanos < bigint0 ? -bigint1 : bigint1; + const absolute = nanos < bigint0 ? -nanos : nanos; + return [Number(sign * (absolute / bigint1e9)), Number(sign * (absolute % bigint1e9))]; +}; +const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/; +/** + * Decodes a `Duration.Input` into a `Duration`. + * + * **When to use** + * + * Use when the input has already been validated or comes from a trusted source + * and throwing is acceptable for invalid duration syntax. + * + * **Gotchas** + * + * If the input is not a valid `Duration.Input`, it throws an error. + * + * **Example** (Decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.fromInputUnsafe(1000) // => Duration.millis(1000) + * Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5) + * Duration.fromInputUnsafe("Infinity") // => Duration.infinity + * Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInputUnsafe = input => { + switch (typeof input) { + case "number": + return millis(input); + case "bigint": + return nanos(input); + case "string": + { + if (input === "Infinity") { + return infinity; + } + if (input === "-Infinity") { + return negativeInfinity; + } + const match = DURATION_REGEXP.exec(input); + if (!match) break; + const [_, valueStr, unit] = match; + if (unit === "nano" || unit === "nanos") { + return nanos(parseNanos(valueStr, bigint1)); + } + if (unit === "micro" || unit === "micros") { + return nanos(parseNanos(valueStr, bigint1e3)); + } + const value = Number(valueStr); + switch (unit) { + case "milli": + case "millis": + return millis(value); + case "second": + case "seconds": + return seconds(value); + case "minute": + case "minutes": + return minutes(value); + case "hour": + case "hours": + return hours(value); + case "day": + case "days": + return days(value); + case "week": + case "weeks": + return weeks(value); + } + break; + } + case "object": + { + if (input === null) break; + if (TypeId in input) return input; + if (Array.isArray(input)) { + if (input.length !== 2 || !input.every(_Predicate_js__rspack_import_0/* .isNumber */.Et)) { + return invalid(input); + } + if (Number.isNaN(input[0]) || Number.isNaN(input[1])) { + return zero; + } + if (input[0] === -Infinity || input[1] === -Infinity) { + return negativeInfinity; + } + if (input[0] === Infinity || input[1] === Infinity) { + return infinity; + } + return make(roundTiesAwayFromZero(input[0] * 1_000_000_000 + input[1])); + } + const obj = input; + let millis = 0; + // we can use truthy checks here, because 0 can be ignored + if (obj.weeks) millis += obj.weeks * 604_800_000; + if (obj.days) millis += obj.days * 86_400_000; + if (obj.hours) millis += obj.hours * 3_600_000; + if (obj.minutes) millis += obj.minutes * 60_000; + if (obj.seconds) millis += obj.seconds * 1_000; + if (obj.milliseconds) millis += obj.milliseconds; + if (!obj.microseconds && !obj.nanoseconds) return make(millis); + return make(roundTiesAwayFromZero(millis * 1_000_000 + (obj.microseconds ?? 0) * 1_000 + (obj.nanoseconds ?? 0))); + } + } + return invalid(input); +}; +const invalid = input => { + throw new Error(`Invalid Input: ${input}`); +}; +/** + * Decodes a `Input` value into a `Duration` safely, returning + * `Option.none()` if decoding fails. + * + * **Example** (Safely decoding duration inputs) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.fromInput(1000) // => Option.some(Duration.seconds(1)) + * Duration.fromInput("invalid" as any) // => Option.none() + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromInput = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(fromInputUnsafe))); +const zeroDurationValue = { + _tag: "Millis", + millis: 0 +}; +const infinityDurationValue = { + _tag: "Infinity" +}; +const negativeInfinityDurationValue = { + _tag: "NegativeInfinity" +}; +const DurationProto = { + [TypeId]: TypeId, + [_Hash_js__rspack_import_1/* .symbol */.HR]() { + // Hash equal finite durations using the same canonical nanoseconds + // representation used by `equals`. + switch (this.value._tag) { + case "Millis": + { + const nanos = this.value.millis * 1_000_000; + return Number.isFinite(nanos) ? _Hash_js__rspack_import_1/* .hash */.tW(roundTiesAwayFromZero(nanos)) : _Hash_js__rspack_import_1/* .number */.ai(this.value.millis); + } + case "Nanos": + return _Hash_js__rspack_import_1/* .hash */.tW(this.value.nanos); + default: + return _Hash_js__rspack_import_1/* .structure */.QK(this.value); + } + }, + [_Equal_js__rspack_import_2/* .symbol */.HR](that) { + return isDuration(that) && equals(this, that); + }, + toString() { + switch (this.value._tag) { + case "Infinity": + return "Infinity"; + case "NegativeInfinity": + return "-Infinity"; + case "Nanos": + return `${this.value.nanos} nanos`; + case "Millis": + return `${this.value.millis} millis`; + } + }, + toJSON() { + switch (this.value._tag) { + case "Millis": + return { + _id: "Duration", + _tag: "Millis", + millis: this.value.millis + }; + case "Nanos": + return { + _id: "Duration", + _tag: "Nanos", + nanos: String(this.value.nanos) + }; + case "Infinity": + return { + _id: "Duration", + _tag: "Infinity" + }; + case "NegativeInfinity": + return { + _id: "Duration", + _tag: "NegativeInfinity" + }; + } + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + }, + pipe() { + return (0,_Pipeable_js__rspack_import_4/* .pipeArguments */.tT)(this, arguments); + } +}; +const make = input => { + const duration = Object.create(DurationProto); + if (typeof input === "number") { + if (isNaN(input) || input === 0 || Object.is(input, -0)) { + duration.value = zeroDurationValue; + } else if (!Number.isFinite(input)) { + duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue; + } else if (!Number.isInteger(input)) { + duration.value = { + _tag: "Nanos", + nanos: roundMillisToNanos(input) + }; + } else { + duration.value = { + _tag: "Millis", + millis: input + }; + } + } else if (input === bigint0) { + duration.value = zeroDurationValue; + } else { + duration.value = { + _tag: "Nanos", + nanos: input + }; + } + return duration; +}; +/** + * Checks whether a value is a Duration. + * + * **Example** (Checking for durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isDuration(Duration.seconds(1)) // => true + * Duration.isDuration(1000) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isDuration = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(u, TypeId); +/** + * Checks whether a Duration is finite (not infinite). + * + * **Example** (Checking finite durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isFinite(Duration.seconds(5)) // => true + * Duration.isFinite(Duration.infinity) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFinite = self => self.value._tag !== "Infinity" && self.value._tag !== "NegativeInfinity"; +/** + * Checks whether a Duration is zero. + * + * **Example** (Checking for zero durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isZero(Duration.zero) // => true + * Duration.isZero(Duration.seconds(1)) // => false + * ``` + * + * @category predicates + * @since 3.5.0 + */ +const isZero = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis === 0; + case "Nanos": + return self.value.nanos === bigint0; + case "Infinity": + case "NegativeInfinity": + return false; + } +}; +/** + * Returns `true` if the duration is negative (strictly less than zero). + * + * **Example** (Checking for negative durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isNegative(Duration.seconds(-5)) // => true + * Duration.isNegative(Duration.zero) // => false + * Duration.isNegative(Duration.negativeInfinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isNegative = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis < 0; + case "Nanos": + return self.value.nanos < bigint0; + case "NegativeInfinity": + return true; + case "Infinity": + return false; + } +}; +/** + * Returns `true` if the duration is positive (strictly greater than zero). + * + * **Example** (Checking for positive durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isPositive(Duration.seconds(5)) // => true + * Duration.isPositive(Duration.zero) // => false + * Duration.isPositive(Duration.infinity) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isPositive = self => { + switch (self.value._tag) { + case "Millis": + return self.value.millis > 0; + case "Nanos": + return self.value.nanos > bigint0; + case "Infinity": + return true; + case "NegativeInfinity": + return false; + } +}; +/** + * Returns the absolute value of the duration. + * + * **Example** (Taking absolute duration values) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.abs(Duration.seconds(-5)) // => Duration.seconds(5) + * Duration.abs(Duration.negativeInfinity) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const abs = self => { + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis < 0 ? make(-self.value.millis) : self; + case "Nanos": + return self.value.nanos < bigint0 ? make(-self.value.nanos) : self; + } +}; +/** + * Returns the negated duration. + * + * **Example** (Negating durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.negate(Duration.seconds(5)) // => Duration.seconds(-5) + * Duration.negate(Duration.infinity) // => Duration.negativeInfinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const negate = self => { + switch (self.value._tag) { + case "Infinity": + return negativeInfinity; + case "NegativeInfinity": + return infinity; + case "Millis": + return self.value.millis === 0 ? self : make(-self.value.millis); + case "Nanos": + return self.value.nanos === bigint0 ? self : make(-self.value.nanos); + } +}; +/** + * A Duration representing zero time. + * + * **Example** (Referencing the zero duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.zero) // => 0 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const zero = /*#__PURE__*/make(0); +/** + * A Duration representing infinite time. + * + * **Example** (Referencing infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.infinity) // => Infinity + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const infinity = /*#__PURE__*/make(Infinity); +/** + * A Duration representing negative infinite time. + * + * **Example** (Referencing negative infinite duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.negativeInfinity) // => -Infinity + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const negativeInfinity = /*#__PURE__*/make(-Infinity); +/** + * Creates a Duration from nanoseconds. + * + * **Example** (Creating durations from nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const nanos = nanos => make(nanos); +/** + * Creates a Duration from microseconds. + * + * **Example** (Creating durations from microseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.micros(500_000n) // => Duration.nanos(500_000_000n) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const micros = micros => make(micros * bigint1e3); +/** + * Creates a Duration from milliseconds. + * + * **Example** (Creating durations from milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.millis(1000)) // => 1000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const millis = millis => make(millis); +/** + * Creates a Duration from seconds. + * + * **Example** (Creating durations from seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(30)) // => 30_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const seconds = seconds => make(seconds * 1000); +/** + * Creates a Duration from minutes. + * + * **Example** (Creating durations from minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.minutes(5)) // => 300_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const minutes = minutes => make(minutes * 60_000); +/** + * Creates a Duration from hours. + * + * **Example** (Creating durations from hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.hours(2)) // => 7_200_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const hours = hours => make(hours * 3_600_000); +/** + * Creates a Duration from days. + * + * **Example** (Creating durations from days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.days(1)) // => 86_400_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const days = days => make(days * 86_400_000); +/** + * Creates a Duration from weeks. + * + * **Example** (Creating durations from weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.weeks(1)) // => 604_800_000 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const weeks = weeks => make(weeks * 604_800_000); +/** + * Converts a Duration to milliseconds. + * + * **Example** (Converting durations to milliseconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMillis(Duration.seconds(5)) // => 5000 + * Duration.toMillis(Duration.minutes(2)) // => 120_000 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toMillis = self => match(fromInputUnsafe(self), { + onMillis: _Function_js__rspack_import_5/* .identity */.D_, + onNanos: nanos => Number(nanos) / 1_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to seconds. + * + * **Example** (Converting durations to seconds) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toSeconds(Duration.millis(5000)) // => 5 + * Duration.toSeconds(Duration.minutes(2)) // => 120 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toSeconds = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 1_000, + onNanos: nanos => Number(nanos) / 1_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to minutes. + * + * **Example** (Converting durations to minutes) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toMinutes(Duration.seconds(120)) // => 2 + * Duration.toMinutes(Duration.hours(1)) // => 60 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toMinutes = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 60_000, + onNanos: nanos => Number(nanos) / 60_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to hours. + * + * **Example** (Converting durations to hours) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHours(Duration.minutes(120)) // => 2 + * Duration.toHours(Duration.days(1)) // => 24 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toHours = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 3_600_000, + onNanos: nanos => Number(nanos) / 3_600_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to days. + * + * **Example** (Converting durations to days) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toDays(Duration.hours(48)) // => 2 + * Duration.toDays(Duration.weeks(1)) // => 7 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toDays = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 86_400_000, + onNanos: nanos => Number(nanos) / 86_400_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Converts a Duration to weeks. + * + * **Example** (Converting durations to weeks) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toWeeks(Duration.days(14)) // => 2 + * Duration.toWeeks(Duration.days(7)) // => 1 + * ``` + * + * @category getters + * @since 3.8.0 + */ +const toWeeks = self => match(fromInputUnsafe(self), { + onMillis: millis => millis / 604_800_000, + onNanos: nanos => Number(nanos) / 604_800_000_000_000, + onInfinity: () => Infinity, + onNegativeInfinity: () => -Infinity +}); +/** + * Gets the duration in nanoseconds as a bigint. + * + * **When to use** + * + * Use when the duration is known to be finite and you need the nanosecond value + * as a `bigint`. + * + * **Details** + * + * Millisecond-backed fractional durations are rounded to the nearest + * nanosecond, with ties away from zero. + * + * **Gotchas** + * + * If the duration is infinite, it throws an error. + * + * **Example** (Reading nanoseconds unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n + * + * // Duration.toNanosUnsafe(Duration.infinity) + * // throws Error: "Cannot convert infinite duration to nanos" + * ``` + * + * @category getters + * @since 4.0.0 + */ +const toNanosUnsafe = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + case "NegativeInfinity": + throw new Error("Cannot convert infinite duration to nanos"); + case "Nanos": + return self.value.nanos; + case "Millis": + return roundMillisToNanos(self.value.millis); + } +}; +/** + * Gets the duration in nanoseconds safely as an `Option`. + * + * **Details** + * + * If the duration is infinite, returns `Option.none()`. + * + * **Example** (Safely reading nanoseconds) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.toNanos(Duration.seconds(1)) // => Option.some(1_000_000_000n) + * Duration.toNanos(Duration.infinity) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toNanos = /*#__PURE__*/(/* unused pure expression or super */ null && (Option.liftThrowable(toNanosUnsafe))); +/** + * Converts a Duration to high-resolution time format [seconds, nanoseconds]. + * + * **Example** (Converting durations to high-resolution time) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.toHrTime(Duration.millis(1500)) // => [1, 500_000_000] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const toHrTime = input => { + const self = fromInputUnsafe(input); + switch (self.value._tag) { + case "Infinity": + return [Infinity, 0]; + case "NegativeInfinity": + return [-Infinity, 0]; + case "Nanos": + return nanosToHrTime(self.value.nanos); + case "Millis": + return nanosToHrTime(roundMillisToNanos(self.value.millis)); + } +}; +/** + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.match(Duration.seconds(5), { + * onMillis: (millis) => `${millis} milliseconds`, + * onNanos: (nanos) => `${nanos} nanoseconds`, + * onInfinity: () => "infinite" + * }) // => "5000 milliseconds" + * ``` + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, options) => { + switch (self.value._tag) { + case "Millis": + return options.onMillis(self.value.millis); + case "Nanos": + return options.onNanos(self.value.nanos); + case "Infinity": + return options.onInfinity(); + case "NegativeInfinity": + return (options.onNegativeInfinity ?? options.onInfinity)(); + } +}); +/** + * Pattern matches on two `Duration`s, providing handlers that receive both values. + * + * **Example** (Pattern matching on duration pairs) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.matchPair(Duration.seconds(3), Duration.seconds(2), { + * onMillis: (a, b) => a + b, + * onNanos: (a, b) => Number(a + b), + * onInfinity: () => Infinity + * }) // => 5000 + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchPair = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(3, (self, that, options) => { + if (self.value._tag === "Infinity" || self.value._tag === "NegativeInfinity" || that.value._tag === "Infinity" || that.value._tag === "NegativeInfinity") return options.onInfinity(self, that); + if (self.value._tag === "Millis") { + return that.value._tag === "Millis" ? options.onMillis(self.value.millis, that.value.millis) : options.onNanos(toNanosUnsafe(self), that.value.nanos); + } else { + return options.onNanos(self.value.nanos, toNanosUnsafe(that)); + } +}); +/** + * Provides an `Order` instance for comparing `Duration` values. + * + * **Details** + * + * `NegativeInfinity` < any finite value < `Infinity`. + * + * **Example** (Sorting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * const durations = [ + * Duration.seconds(3), + * Duration.seconds(1), + * Duration.seconds(2) + * ] + * durations.sort((a, b) => Duration.Order(a, b)).map(Duration.toSeconds) // => [1, 2, 3] + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Order = /*#__PURE__*/(/* unused pure expression or super */ null && (order.make((self, that) => matchPair(self, that, { + onMillis: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onNanos: (self, that) => self < that ? -1 : self > that ? 1 : 0, + onInfinity: (self, that) => { + if (self.value._tag === that.value._tag) return 0; + if (self.value._tag === "Infinity") return 1; + if (self.value._tag === "NegativeInfinity") return -1; + // self is finite + if (that.value._tag === "Infinity") return -1; + // that is NegativeInfinity + return 1; + } +})))); +/** + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.between(Duration.seconds(3), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => true + * ``` + * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * + * @category predicates + * @since 2.0.0 + */ +const between = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isBetween(Order))); +/** + * Provides an `Equivalence` instance for comparing `Duration` values. + * + * **Example** (Comparing durations for equivalence) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category instances + * @since 2.0.0 + */ +const Equivalence = (self, that) => matchPair(self, that, { + onMillis: (self, that) => self === that, + onNanos: (self, that) => self === that, + onInfinity: (self, that) => self.value._tag === that.value._tag +}); +/** + * Returns the smaller of two Durations. + * + * **Example** (Selecting the shorter duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.min(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(3) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const min = /*#__PURE__*/(/* unused pure expression or super */ null && (order.min(Order))); +/** + * Returns the larger of two Durations. + * + * **Example** (Selecting the longer duration) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.max(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const max = /*#__PURE__*/(/* unused pure expression or super */ null && (order.max(Order))); +/** + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.clamp(Duration.seconds(10), { + * minimum: Duration.seconds(2), + * maximum: Duration.seconds(5) + * }) // => Duration.seconds(5) + * ``` + * + * @category ordering + * @since 2.0.0 + */ +const clamp = /*#__PURE__*/(/* unused pure expression or super */ null && (order.clamp(Order))); +/** + * Divides a `Duration` by a finite, non-zero number safely. + * + * **Details** + * + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) + * + * ```ts import.meta.vitest + * import { Duration, Option } from "effect" + * + * Duration.divide(Duration.seconds(10), 2) // => Option.some(Duration.seconds(5)) + * Duration.divide(Duration.seconds(10), 0) // => Option.none() + * ``` + * + * @category math + * @since 2.4.19 + */ +const divide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return Option.none(); + if (by === 0 || Object.is(by, -0)) return Option.none(); + return match(self, { + onMillis: millis => Option.some(make(millis / by)), + onNanos: nanos => { + try { + return Option.some(make(nanos / BigInt(by))); + } catch { + return Option.none(); + } + }, + onInfinity: () => Option.some(by > 0 ? infinity : negativeInfinity), + onNegativeInfinity: () => Option.some(by > 0 ? negativeInfinity : infinity) + }); +}))); +/** + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.divideUnsafe(Duration.seconds(10), 2) // => Duration.seconds(5) + * Duration.divideUnsafe(Duration.seconds(10), 0) // => Duration.infinity + * ``` + * + * @category math + * @since 4.0.0 + */ +const divideUnsafe = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, by) => { + if (!Number.isFinite(by)) return zero; + return match(self, { + onMillis: millis => make(millis / by), + onNanos: nanos => { + if (Object.is(by, 0) || Object.is(by, -0)) { + if (nanos === bigint0) return zero; + // match IEEE 754: same sign → +infinity, different sign → -infinity + const positiveNanos = nanos > bigint0; + const positiveZero = Object.is(by, 0); + return positiveNanos === positiveZero ? infinity : negativeInfinity; + } + try { + return make(nanos / BigInt(by)); + } catch { + return zero; + } + }, + onInfinity: () => by > 0 ? infinity : by < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => by > 0 ? negativeInfinity : by < 0 ? infinity : zero + }); +}))); +/** + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.times(Duration.seconds(5), 2) // => Duration.seconds(10) + * ``` + * + * @category math + * @since 2.0.0 + */ +const times = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, times) => match(self, { + onMillis: millis => make(millis * times), + onNanos: nanos => make(nanos * BigInt(times)), + onInfinity: () => times > 0 ? infinity : times < 0 ? negativeInfinity : zero, + onNegativeInfinity: () => times > 0 ? negativeInfinity : times < 0 ? infinity : zero +})))); +/** + * Subtracts one Duration from another. The result can be negative. + * + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.subtract(Duration.seconds(10), Duration.seconds(3)) // => Duration.seconds(7) + * ``` + * + * @category math + * @since 2.0.0 + */ +const subtract = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self - that), + onNanos: (self, that) => make(self - that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity") return t === "Infinity" ? zero : infinity; + if (s === "NegativeInfinity") return t === "NegativeInfinity" ? zero : negativeInfinity; + return t === "Infinity" ? negativeInfinity : infinity; + } +})))); +/** + * Adds two Durations together. + * + * **Details** + * + * Infinity addition follows these rules: + * + * - infinity + infinity = infinity + * - infinity + negativeInfinity = zero + * - infinity + finite = infinity + * - negativeInfinity + negativeInfinity = negativeInfinity + * - negativeInfinity + finite = negativeInfinity + * + * **Example** (Adding durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.sum(Duration.seconds(5), Duration.seconds(3)) // => Duration.seconds(8) + * ``` + * + * @category math + * @since 2.0.0 + */ +const sum = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => matchPair(self, that, { + onMillis: (self, that) => make(self + that), + onNanos: (self, that) => make(self + that), + onInfinity: (self, that) => { + const s = self.value._tag; + const t = that.value._tag; + if (s === "Infinity" && t === "NegativeInfinity") return zero; + if (s === "NegativeInfinity" && t === "Infinity") return zero; + if (s === "Infinity" || t === "Infinity") return infinity; + if (s === "NegativeInfinity" || t === "NegativeInfinity") return negativeInfinity; + // unreachable, but satisfy TS + return zero; + } +})))); +/** + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThan(Duration.seconds(3), Duration.seconds(5)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThan(Order))); +/** + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isLessThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isLessThanOrEqualTo(Order))); +/** + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThan(Duration.seconds(5), Duration.seconds(3)) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThan(Order))); +/** + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.isGreaterThanOrEqualTo( + * Duration.seconds(5), + * Duration.seconds(5) + * ) // => true + * ``` + * + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = /*#__PURE__*/(/* unused pure expression or super */ null && (order.isGreaterThanOrEqualTo(Order))); +/** + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const equals = /*#__PURE__*/(0,_Function_js__rspack_import_5/* .dual */.XY)(2, (self, that) => Equivalence(self, that)); +/** + * Decomposes a `Duration` into normalized signed components. + * + * **Details** + * + * Finite durations are returned as `{ days, hours, minutes, seconds, millis, + * nanos }`. Infinite durations return every component as `Infinity` or + * `-Infinity`. + * + * **Example** (Decomposing durations into parts) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * // Create a complex duration by adding multiple parts + * const duration = Duration.sum( + * Duration.sum( + * Duration.sum(Duration.days(1), Duration.hours(2)), + * Duration.sum(Duration.minutes(30), Duration.seconds(45)) + * ), + * Duration.millis(123) + * ) + * Duration.parts(duration) // => ({ days: 1, hours: 2, minutes: 30, seconds: 45, millis: 123, nanos: 0 }) + * + * const complex = Duration.sum(Duration.hours(25), Duration.minutes(90)) + * Duration.parts(complex) // => ({ days: 1, hours: 2, minutes: 30, seconds: 0, millis: 0, nanos: 0 }) + * ``` + * + * @category converting + * @since 3.8.0 + */ +const parts = self => { + if (self.value._tag === "Infinity") { + return { + days: Infinity, + hours: Infinity, + minutes: Infinity, + seconds: Infinity, + millis: Infinity, + nanos: Infinity + }; + } + if (self.value._tag === "NegativeInfinity") { + return { + days: -Infinity, + hours: -Infinity, + minutes: -Infinity, + seconds: -Infinity, + millis: -Infinity, + nanos: -Infinity + }; + } + const n = toNanosUnsafe(self); + const neg = n < bigint0; + const a = neg ? -n : n; + const ms = a / bigint1e6; + const sec = ms / bigint1e3; + const min = sec / bigint60; + const hr = min / bigint60; + const d = hr / bigint24; + const sign = neg ? -1 : 1; + return { + days: sign * Number(d), + hours: sign * Number(hr % bigint24), + minutes: sign * Number(min % bigint60), + seconds: sign * Number(sec % bigint60), + millis: sign * Number(ms % bigint1e3), + nanos: sign * Number(a % bigint1e6) + }; +}; +/** + * Converts a `Duration` to a human readable string. + * + * **Example** (Formatting durations) + * + * ```ts import.meta.vitest + * import { Duration } from "effect" + * + * Duration.format(Duration.millis(1000)) // => "1s" + * Duration.format(Duration.millis(1001)) // => "1s 1ms" + * ``` + * + * @category converting + * @since 2.0.0 + */ +const format = self => { + if (self.value._tag === "Infinity") { + return "Infinity"; + } + if (self.value._tag === "NegativeInfinity") { + return "-Infinity"; + } + if (isZero(self)) { + return "0"; + } + if (isNegative(self)) { + return "-" + format(abs(self)); + } + const fragments = parts(self); + const pieces = []; + if (fragments.days !== 0) { + pieces.push(`${fragments.days}d`); + } + if (fragments.hours !== 0) { + pieces.push(`${fragments.hours}h`); + } + if (fragments.minutes !== 0) { + pieces.push(`${fragments.minutes}m`); + } + if (fragments.seconds !== 0) { + pieces.push(`${fragments.seconds}s`); + } + if (fragments.millis !== 0) { + pieces.push(`${fragments.millis}ms`); + } + if (fragments.nanos !== 0) { + pieces.push(`${fragments.nanos}ns`); + } + return pieces.join(" "); +}; +/** + * Reducer for summing `Duration`s. + * + * **When to use** + * + * Use to sum many `Duration` values through APIs that consume a `Reducer`. + * + * **Details** + * + * `ReducerSum` uses `sum` and starts from `zero`, so `combineAll([])` returns + * `zero`. + * + * @see {@link sum} for adding two duration values directly + * @see {@link CombinerMax} for keeping the longest duration instead of summing + * @see {@link CombinerMin} for keeping the shortest duration instead of summing + * + * @category math + * @since 4.0.0 + */ +const ReducerSum = /*#__PURE__*/(/* unused pure expression or super */ null && (Reducer.make(sum, zero))); +/** + * Combiner that returns the maximum `Duration`. + * + * **When to use** + * + * Use to keep the longest `Duration` when an API consumes a `Combiner`. + * + * @see {@link CombinerMin} for keeping the shortest `Duration` + * @see {@link max} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMax = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.max(Order))); +/** + * Combiner that returns the minimum `Duration`. + * + * **When to use** + * + * Use to keep the shortest `Duration` through APIs that consume a `Combiner`. + * + * @see {@link CombinerMax} for keeping the longest `Duration` + * @see {@link min} for comparing two `Duration` values directly + * + * @category math + * @since 4.0.0 + */ +const CombinerMin = /*#__PURE__*/(/* unused pure expression or super */ null && (Combiner.min(Order))); +//# sourceMappingURL=Duration.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Tn: infinity, + bN: fromInputUnsafe, + cF: nanos, + kE: toMillis, + ne: millis, + v_: zero +}); + + +}, +"./node_modules/effect/dist/Effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _internal_executionPlan_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/internal/executionPlan.js"); +/* import */ var _internal_layer_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/layer.js"); +/* import */ var _internal_request_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/request.js"); +/* import */ var _internal_schedule_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/schedule.js"); + + + + + + + + + + + + + + +/** + * Runtime identifier used to recognize `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +const TypeId = _internal_core_js__rspack_import_0/* .EffectTypeId */.$n; +/** + * Checks whether a value is an `Effect`. + * + * **Example** (Checking whether a value is an Effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * Effect.isEffect(Effect.succeed(1)) // => true + * Effect.isEffect("hello") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEffect = _internal_core_js__rspack_import_0/* .isEffect */.yw; +/** + * 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. + * @category combining + * @since 2.0.0 + */ +const all = _internal_effect_js__rspack_import_1/* .all */.Q7R; +/** + * Applies an effectful function to each element and partitions failures and + * successes. + * + * **Details** + * + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. + * + * This function runs every effect and never fails. Use `concurrency` to control + * parallelism. + * + * **Example** (Separating successes and failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.partition([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromise(program) // => [['0 is even', '2 is even'], [1, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = _internal_effect_js__rspack_import_1/* .partition */.jBG; +/** + * Reduces elements from left to right with an effectful accumulator function. + * + * **When to use** + * + * Use when each accumulation step is effectful and must run sequentially in + * iteration order. + * + * **Details** + * + * The accumulator function receives the current accumulator, the current + * element, and its zero-based index. The `zero` function is evaluated each + * time the effect runs. An empty iterable succeeds with its result. If a step + * fails, remaining elements are not processed. + * + * **Example** (Summing values sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.reduce( + * [1, 2, 3], + * () => 0, + * (total, value, index) => + * Effect.sync(() => { output.push(`Adding ${value} at index ${index}`) }).pipe( + * Effect.as(total + value) + * ) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Adding 1 at index 0", "Adding 2 at index 1", "Adding 3 at index 2", 6] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = _internal_effect_js__rspack_import_1/* .reduce */.TSs; +/** + * Applies an effectful function to each element and accumulates all failures. + * + * **Details** + * + * This function always evaluates every element. If at least one effect fails, + * all failures are returned as a non-empty array and successes are discarded. + * If all effects succeed, it returns all collected successes. + * + * Use `discard: true` to ignore successful values while still validating all + * elements. + * + * **Example** (Validating every element) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const program = Effect.validate([0, 1, 2, 3], (n) => + * n % 2 === 0 ? Effect.fail(`${n} is even`) : Effect.succeed(n) + * ) + * + * await Effect.runPromiseExit(program) // => Exit.fail(["0 is even", "2 is even"]) + * ``` + * + * @category validation + * @since 2.0.0 + */ +const validate = _internal_effect_js__rspack_import_1/* .validate */.tfT; +/** + * Returns the first element that satisfies an effectful predicate. + * + * **Details** + * + * The predicate receives the element and its index. Evaluation short-circuits + * as soon as an element matches. + * + * **Example** (Finding the first successful match) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.findFirst([1, 2, 3, 4], (n) => Effect.succeed(n > 2)) + * + * await Effect.runPromise(program) // => Option.some(3) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = _internal_effect_js__rspack_import_1/* .findFirst */.i8i; +/** + * Returns the first value that passes an effectful `FilterEffect`. + * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * + * The filter receives the element and index. Evaluation short-circuits on the + * first `Result.succeed` and returns the transformed value in `Option.some`. + * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category searching + * @since 4.0.0 + */ +const findFirstFilter = _internal_effect_js__rspack_import_1/* .findFirstFilter */.kAe; +/** + * Executes an effectful operation for each element in an `Iterable`. + * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * + * **Details** + * + * The `forEach` function applies a provided operation to each element in the + * iterable, producing a new effect that returns an array of results. + * + * If any effect fails, the iteration stops immediately (short-circuiting), and + * the error is propagated. + * + * Concurrency: + * + * The `concurrency` option controls how many operations are performed + * concurrently. By default, the operations are performed sequentially. + * + * Discarding Results: + * + * If the `discard` option is set to `true`, the intermediate results are not + * collected, and the final result of the operation is `void`. + * + * **Example** (Mapping over an iterable with effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)) + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", [2, 4, 6, 8, 10]] + * ``` + * + * **Example** (Running effects without collecting results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Apply effects but discard the results + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Effect.sync(() => { output.push(`Currently at index ${index}`) }).pipe(Effect.as(n * 2)), + * { discard: true } + * ) + * + * void output.push(await Effect.runPromise(result)) + * output // => ["Currently at index 0", "Currently at index 1", "Currently at index 2", "Currently at index 3", "Currently at index 4", undefined] + * ``` + * + * @see {@link all} for combining multiple effects into one. + * @category sequencing + * @since 2.0.0 + */ +const forEach = _internal_effect_js__rspack_import_1/* .forEach */.jJl; +/** + * Returns the first element of the iterable produced by an effect, or fails + * with `NoSuchElementError` if the iterable is empty. + * + * **When to use** + * + * Use when an effect produces a collection that must contain at least one + * element and absence should be represented in the typed error channel. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const first = await Effect.runPromise(Effect.head(Effect.succeed([1, 2, 3]))) + * first // => 1 + * + * const empty = Effect.head(Effect.succeed([] as Array)).pipe(Effect.catchNoSuchElement) + * await Effect.runPromise(empty) // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = _internal_effect_js__rspack_import_1/* .head */.d5f; +/** + * Executes a body effect repeatedly while a condition holds true. + * + * **Example** (Repeating an effectful loop) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let counter = 0 + * + * const program = Effect.whileLoop({ + * while: () => counter < 5, + * body: () => Effect.sync(() => ++counter), + * step: (n) => void output.push(`Current count: ${n}`) + * }) + * + * await Effect.runPromise(program) + * output // => ["Current count: 1", "Current count: 2", "Current count: 3", "Current count: 4", "Current count: 5"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const whileLoop = _internal_effect_js__rspack_import_1/* .whileLoop */.iMI; +// ----------------------------------------------------------------------------- +// Creating Effects +// ----------------------------------------------------------------------------- +/** + * Creates an `Effect` that represents an asynchronous computation guaranteed to + * succeed. + * + * **When to use** + * + * Use to convert a `Promise` into an `Effect` when the async operation is + * guaranteed to succeed and will not reject. + * + * **Details** + * + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. + * + * **Gotchas** + * + * The `Promise` must not reject. If it rejects, the rejection is treated as a + * defect, not as a typed failure. Use `tryPromise` when rejection is expected. + * + * Interruption aborts the provided `AbortSignal`, but the underlying + * asynchronous operation only stops if it observes that signal. + * + * **Example** (Wrapping a non-rejecting Promise) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const succeedAsync = (message: string) => + * Effect.promise(() => Promise.resolve(message)) + * + * // ┌─── Effect + * // ▼ + * const program = succeedAsync("Async operation completed successfully!") + * await Effect.runPromise(program) // => "Async operation completed successfully!" + * ``` + * + * @see {@link tryPromise} for a version that can handle failures. + * @category constructors + * @since 2.0.0 + */ +const promise = _internal_effect_js__rspack_import_1/* .promise */.ivC; +/** + * Creates an `Effect` from an asynchronous computation that may throw or + * reject, mapping failures into the error channel. + * + * **When to use** + * + * Use when you need to perform asynchronous operations that might fail, such + * as fetching data from an API, and want thrown exceptions or rejected promises + * captured as Effect errors. + * + * **Details** + * + * The promise thunk is evaluated when the effect runs. If it returns a promise + * that resolves, the resolved value becomes the success value. If the thunk + * throws before returning a promise, or if the returned promise rejects, the + * thrown or rejected value is mapped into the error channel. + * + * Passing the thunk directly maps failures to {@link Cause.UnknownError}. + * Passing `{ try, catch }` uses `catch` to map failures to an error of type + * `E`. + * + * The thunk receives an `AbortSignal` that is aborted if the effect is + * interrupted. The underlying asynchronous operation only stops if it observes + * that signal. + * + * **Gotchas** + * + * If `catch` throws while mapping the error, that thrown value is treated as a + * defect. Return the error value you want in the error channel instead of + * throwing it. + * + * **Example** (Wrapping a fetch request that may fail) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const getTodo = (id: number) => + * Effect.tryPromise(() => Promise.resolve({ id, completed: false })) + * + * // ┌─── Effect<{ id: number; completed: boolean }, UnknownError, never> + * // ▼ + * const program = getTodo(1) + * await Effect.runPromise(program) // => { id: 1, completed: false } + * ``` + * + * **Example** (Mapping Promise rejections to a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TodoFetchError extends Data.TaggedError("TodoFetchError")<{ readonly cause: unknown }> {} + * + * const getTodo = (id: number) => + * Effect.tryPromise({ + * try: () => Promise.reject(`Todo ${id} is unavailable`), + * // remap the error + * catch: (cause) => new TodoFetchError({ cause }) + * }) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.flip(getTodo(1)) + * const error = await Effect.runPromise(program) + * error._tag // => "TodoFetchError" + * ``` + * + * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. + * @category constructors + * @since 2.0.0 + */ +const tryPromise = _internal_effect_js__rspack_import_1/* .tryPromise */.$mh; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_effect_js__rspack_import_1/* .succeed */.PyW; +/** + * Returns an effect which succeeds with `None`. + * + * **Example** (Succeeding with Option.none) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedNone + * + * Effect.runSync(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedNone = _internal_effect_js__rspack_import_1/* .succeedNone */.lwU; +/** + * Returns an effect which succeeds with the value wrapped in a `Some`. + * + * **Example** (Succeeding with Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.succeedSome(42) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const succeedSome = _internal_effect_js__rspack_import_1/* .succeedSome */.nGE; +/** + * Creates an `Effect` lazily, delaying construction until it is needed. + * + * **When to use** + * + * Use when you need to defer the evaluation of an effect until it is required. + * + * **Details** + * + * `suspend` takes a thunk that represents an effect and delays creating it + * until the suspended effect is evaluated. This is useful for optimizing + * expensive computations, managing circular dependencies such as recursive + * functions, and helping TypeScript unify return types when branches construct + * different effects. Any side effects or scoped captures inside the thunk are + * re-executed on each invocation. + * + * **Example** (Lazily evaluating side effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * let i = 0 + * + * const bad = Effect.succeed(i++) + * + * const good = Effect.suspend(() => Effect.succeed(i++)) + * + * Effect.runSync(bad) // => 0 + * Effect.runSync(bad) // => 0 + * + * Effect.runSync(good) // => 1 + * Effect.runSync(good) // => 2 + * ``` + * + * **Example** (Suspending recursive Fibonacci evaluation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const blowsUp = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b) + * + * // console.log(Effect.runSync(blowsUp(32))) + * // crash: JavaScript heap out of memory + * + * const allGood = (n: number): Effect.Effect => + * n < 2 + * ? Effect.succeed(1) + * : Effect.zipWith( + * Effect.suspend(() => allGood(n - 1)), + * Effect.suspend(() => allGood(n - 2)), + * (a, b) => a + b + * ) + * + * Effect.runSync(allGood(16)) // => 1597 + * ``` + * + * **Example** (Helping TypeScript infer recursive effect types) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Without suspend, TypeScript may struggle with type inference. + * // Inferred type: + * // (a: number, b: number) => + * // Effect | Effect + * const withoutSuspend = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * + * // Using suspend to unify return types. + * // Inferred type: + * // (a: number, b: number) => Effect + * const withSuspend = (a: number, b: number) => + * Effect.suspend(() => + * b === 0 + * ? Effect.fail(new Error("Cannot divide by zero")) + * : Effect.succeed(a / b) + * ) + * + * Effect.runSync(withSuspend(6, 2)) // => 3 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = _internal_effect_js__rspack_import_1/* .suspend */.DYE; +/** + * 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. + * @category constructors + * @since 2.0.0 + */ +const sync = _internal_effect_js__rspack_import_1/* .sync */.OH5; +const void_ = _internal_effect_js__rspack_import_1/* ["void"] */.rIH; + +const undefined_ = _internal_effect_js__rspack_import_1/* .undefined */.Vxk; + +/** + * Creates an `Effect` from a callback-based asynchronous API. + * + * **When to use** + * + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. + * + * **Details** + * + * The registration function receives a `resume` callback and, when requested, + * an `AbortSignal`. Call `resume` at most once with the effect that should + * complete the fiber; later calls are ignored. Return an optional cleanup + * effect from the registration function to run if the fiber is interrupted. + * + * **Example** (Integrating callback APIs) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fromCallback = (message: string) => + * Effect.callback((resume) => { + * queueMicrotask(() => { + * void output.push(message) + * resume(Effect.void) + * }) + * }) + * + * await Effect.runPromise(fromCallback("callback completed")) + * output // => ["callback completed"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const callback = _internal_effect_js__rspack_import_1/* .callback */.E2r; +/** + * Returns an effect that will never produce anything. The moral equivalent of + * `while(true) {}`, only without the wasted CPU cycles. + * + * **Example** (Creating a never-ending effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.timeoutOption(Effect.never, 0) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const never = _internal_effect_js__rspack_import_1/* .never */.ZmZ; +/** + * Effect that succeeds with an empty record `{}`, used as the starting point + * for do notation chains. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * const program = pipe( + * Effect.Do, + * Effect.bind("x", () => Effect.succeed(2)), + * Effect.bind("y", ({ x }) => Effect.succeed(x + 1)), + * Effect.let("sum", ({ x, y }) => x + y) + * ) + * + * Effect.runSync(program) // => { x: 2, y: 3, sum: 5 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Do = _internal_effect_js__rspack_import_1.Do; +/** + * Gives a name to the success value of an `Effect`, creating a single-key + * record used in do notation pipelines. + * + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = _internal_effect_js__rspack_import_1/* .bindTo */.JrD; +const let_ = _internal_effect_js__rspack_import_1/* ["let"] */.uVU; + +/** + * Adds an `Effect` value to the do notation record under a given name. + * + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category sequencing + * @since 2.0.0 + */ +const bind = _internal_effect_js__rspack_import_1/* .bind */.oIE; +/** + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const gen = _internal_effect_js__rspack_import_1/* .gen */.JkU; +/** + * Creates an `Effect` that represents a recoverable error. + * + * **When to use** + * + * Use to explicitly signal a recoverable error in an `Effect`. + * + * **Details** + * + * The error keeps propagating unless it is handled. You can handle tagged + * errors with functions like {@link catchTag} or {@link catchTags}. + * + * **Example** (Creating a failed effect) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {} + * + * // ┌─── Effect + * // ▼ + * const failure = Effect.fail( + * new OperationFailedError() + * ) + * Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError" + * ``` + * + * @see {@link succeed} to create an effect that represents a successful value. + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_effect_js__rspack_import_1/* .fail */.fJG; +/** + * Creates an `Effect` that represents a recoverable error using a lazy evaluation. + * + * **When to use** + * + * Use to defer computing a recoverable error value until the effect is run. + * + * **Details** + * + * The error-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating failures) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ProgramError extends Data.TaggedError("ProgramError")<{ readonly operation: string }> {} + * + * const program = Effect.failSync(() => new ProgramError({ operation: "sync" })) + * + * Effect.runSync(Effect.flip(program)).operation // => "sync" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failSync = _internal_effect_js__rspack_import_1/* .failSync */.gOk; +/** + * Creates an `Effect` that represents a failure with a specific `Cause`. + * + * **When to use** + * + * Use when you already have a full `Cause` and need to preserve defects, + * interruptions, annotations, or combined failures in the effect's failure + * channel. + * + * **Details** + * + * This function allows you to create effects that fail with complex error + * structures, including multiple errors, defects, interruptions, and more. + * + * **Example** (Failing with a full Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCause( + * Cause.fail("Network error") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Network error" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_effect_js__rspack_import_1/* .failCause */.ATB; +/** + * Creates an `Effect` that represents a failure with a `Cause` computed lazily. + * + * **When to use** + * + * Use to defer computing a full `Cause` until the effect is run. + * + * **Details** + * + * The cause-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const program = Effect.failCauseSync(() => + * Cause.fail("Error computed at runtime") + * ) + * + * Effect.runSync(Effect.flip(program)) // => "Error computed at runtime" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const failCauseSync = _internal_effect_js__rspack_import_1/* .failCauseSync */.pVV; +/** + * Creates an effect that terminates a fiber with a specified error. + * + * **When to use** + * + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. + * + * **Details** + * + * The `die` function is used to signal a defect, which represents a critical + * and unexpected error in the code. When invoked, it produces an effect that + * does not handle the error and instead terminates the fiber. + * + * The error channel of the resulting effect is of type `never`, indicating that + * it cannot recover from this failure. + * + * **Example** (Failing on division by zero) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const defect = new Error("Cannot divide by zero") + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.die(defect) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = divide(1, 0) + * + * Effect.runSyncExit(program) // => Exit.die(defect) + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_effect_js__rspack_import_1/* .die */.F_Q; +const try_ = _internal_effect_js__rspack_import_1/* ["try"] */.SvU; + +/** + * Yields control back to the Effect runtime, allowing other fibers to execute. + * + * **Example** (Yielding to other fibers) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("Before yield") + * yield* Effect.yieldNow + * void output.push("After yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["Before yield", "After yield"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const yieldNow = _internal_effect_js__rspack_import_1/* .yieldNow */.m9E; +/** + * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute. + * + * **Example** (Yielding with priority) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * void output.push("High priority task") + * yield* Effect.yieldNowWith(10) // Higher priority + * void output.push("Continued after yield") + * }) + * + * await Effect.runPromise(program) + * output // => ["High priority task", "Continued after yield"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const yieldNowWith = _internal_effect_js__rspack_import_1/* .yieldNowWith */.KN3; +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const withFiber = _internal_core_js__rspack_import_0/* .withFiber */.R6; +// ----------------------------------------------------------------------------- +// Conversions +// ----------------------------------------------------------------------------- +/** + * Converts a `Result` to an `Effect`. + * + * **Example** (Converting a Result into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * const output: Array = [] + * + * const success = Result.succeed(42) + * const failure = Result.fail("Something went wrong") + * + * const effect1 = Effect.fromResult(success) + * const effect2 = Effect.fromResult(failure) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))) + * output // => [42, "Something went wrong"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromResult = _internal_effect_js__rspack_import_1/* .fromResult */.yUA; +/** + * Converts an `Option` into an `Effect`. + * + * **When to use** + * + * Use when absence should become a typed `NoSuchElementError` in the effect error + * channel. + * + * **Details** + * + * `Option.some` becomes a successful effect with the contained value, while + * `Option.none` becomes a failed effect. By default the failure is a + * `NoSuchElementError`, but you can provide an `onNone` callback to customize + * the error value. + * + * **Example** (Converting an Option into an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Option.some(42) + * const none = Option.none() + * + * const effect1 = Effect.fromOption(some) + * const effect2 = Effect.fromOption(none) + * const effect3 = Effect.fromOption(none, () => new Error("missing")) + * + * void output.push(Effect.runSync(effect1)) + * void output.push(Effect.runSync(Effect.flip(effect2))._tag) + * void output.push(Effect.runSync(Effect.flip(effect3)).message) + * output // => [42, "NoSuchElementError", "missing"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromOption = _internal_effect_js__rspack_import_1/* .fromOption */.sVm; +/** + * Converts an `Option` of an `Effect` into an `Effect` of an `Option`. + * + * **When to use** + * + * Use when an effect should run only when an optional value is present, while + * preserving absence as a successful `None`. + * + * **Details** + * + * - `None` becomes an effect that succeeds with `None` + * - `Some(effect)` runs the inner effect and wraps its success value in `Some` + * - Inner failures are preserved in the resulting effect + * + * **Example** (Transposing an Option of an Effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const some = Option.some(Effect.succeed(42)) + * + * // ┌─── Effect, never, never> + * // ▼ + * const program = Effect.transposeOption(some) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category converting + * @since 3.13.0 + */ +const transposeOption = _internal_effect_js__rspack_import_1/* .transposeOption */.pkL; +/** + * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` + * when the value is `null` or `undefined`. + * + * **Example** (Failing on nullish values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.fn(function*(input: string | null) { + * const value = yield* Effect.fromNullishOr(input) + * yield* Effect.sync(() => { output.push(value) }) + * }, + * Effect.catch(() => Effect.sync(() => { output.push("missing") })) + * ) + * + * await Effect.runPromise(program(null)) + * await Effect.runPromise(program("hello")) + * output // => ["missing", "hello"] + * ``` + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = _internal_effect_js__rspack_import_1/* .fromNullishOr */.bJ; +// ----------------------------------------------------------------------------- +// Mapping +// ----------------------------------------------------------------------------- +/** + * Chains effects to produce new `Effect` instances, useful for combining + * operations that depend on previous results. + * + * **When to use** + * + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. + * + * **Details** + * + * `flatMap` lets you sequence effects so that the result of one effect can be + * used in the next step. It is similar to `flatMap` used with arrays but works + * specifically with `Effect` instances, allowing you to avoid deeply nested + * effect structures. + * + * Since effects are immutable, `flatMap` always returns a new effect instead of + * changing the original one. + * + * **Example** (Choosing flatMap syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * + * void output.push(Effect.runSync(Effect.all([ + * flatMappedWithPipe, + * flatMappedWithDataFirst, + * flatMappedWithMethod + * ]))) + * output // => [[2, 2, 2]] + * ``` + * + * **Example** (Sequencing dependent effects) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Chaining the fetch and discount application using `flatMap` + * const finalAmount = pipe( + * fetchTransactionAmount, + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(finalAmount) // => 95 + * ``` + * + * @see {@link tap} for a version that ignores the result of the effect. + * @category sequencing + * @since 2.0.0 + */ +const flatMap = _internal_effect_js__rspack_import_1/* .flatMap */.qIB; +/** + * Flattens an `Effect` that produces another `Effect` into a single effect. + * + * **Example** (Flattening nested effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const nested = Effect.succeed(Effect.succeed("hello")) + * + * const program = Effect.gen(function*() { + * const value = yield* Effect.flatten(nested) + * yield* Effect.sync(() => { output.push(value) }) + * }) + * + * Effect.runSync(program) + * output // => ["hello"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = _internal_effect_js__rspack_import_1/* .flatten */.Bqz; +/** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. + * + * **When to use** + * + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. + * + * **Details** + * + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. + * + * **Example** (Choosing andThen syntax variants) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * const output: Array = [] + * + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") + * + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * + * void output.push(Effect.runSync(Effect.all([ + * transformedWithPipe, + * transformedWithDataFirst, + * transformedWithMethod + * ]))) + * output // => [['done', 'done', 'done']] + * ``` + * + * **Example** (Sequencing a discount calculation after fetching a total) + * + * ```ts import.meta.vitest + * import { Data, Effect, pipe } from "effect" + * + * 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)) + * + * // Using Effect.map and Effect.flatMap + * const result1 = pipe( + * fetchTransactionAmount, + * Effect.map((amount) => amount * 2), + * Effect.flatMap((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result1) // => 190 + * + * // Using Effect.andThen + * const result2 = pipe( + * fetchTransactionAmount, + * Effect.andThen((amount) => Effect.succeed(amount * 2)), + * Effect.andThen((amount) => applyDiscount(amount, 5)) + * ) + * + * await Effect.runPromise(result2) // => 190 + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = _internal_effect_js__rspack_import_1/* .andThen */.hgn; +/** + * 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] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tap = _internal_effect_js__rspack_import_1/* .tap */.Mim; +/** + * Converts both success and failure of an `Effect` into a `Result` type. + * + * **When to use** + * + * Use when you want an `Effect`'s typed failures to be handled as `Result` + * data while preserving the original error value. + * + * **Details** + * + * This function converts an effect that may fail into an effect that always + * succeeds, wrapping the outcome in a `Result` type. The result will be + * `Result.Failure` if the effect fails, containing the recoverable error, or + * `Result.Success` if it succeeds, containing the result. + * + * Using this function, you can handle recoverable errors explicitly without + * causing the effect to fail. This is particularly useful in scenarios where + * you want to chain effects and manage both success and failure in the same + * logical flow. + * + * The resulting effect cannot fail directly because all recoverable failures + * are represented inside the `Result` type. + * + * **Gotchas** + * + * `result` only captures typed, recoverable failures. Defects and + * interruptions are not captured inside the `Result` and still fail the + * effect. + * + * **Example** (Capturing success or failure as Result) + * + * ```ts import.meta.vitest + * import { Effect, Result } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.result(success) + * const program2 = Effect.result(failure) + * + * Effect.runSync(program1) // => Result.succeed(42) + * + * Effect.runSync(program2) // => Result.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 4.0.0 + */ +const result = _internal_effect_js__rspack_import_1/* .result */.Ket; +/** + * Converts success to `Option.some` and failure to `Option.none`. + * + * **When to use** + * + * Use when you only care whether an effect succeeds and want recoverable + * failures represented as `Option.none`. + * + * **Details** + * + * Success values become `Option.some`, recoverable failures become + * `Option.none`, and defects still fail the effect. + * + * **Gotchas** + * + * `option` only captures typed, recoverable failures as `Option.none`. + * Defects and interruptions are not captured inside the `Option` and still + * fail the effect. + * + * `option` also discards typed failure values. Use `result` if the failure + * value matters. + * + * **Example** (Capturing success or failure as Option) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.all([ + * Effect.option(Effect.succeed(1)), + * Effect.option(Effect.fail("missing")) + * ]) + * + * Effect.runSync(program) // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link result} for a version that uses `Result` instead. + * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. + * + * @category error handling + * @since 2.0.0 + */ +const option = _internal_effect_js__rspack_import_1/* .option */.uKv; +/** + * Transforms an effect to encapsulate both failure and success using the `Exit` + * data type. + * + * **When to use** + * + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. + * + * **Details** + * + * `exit` wraps an effect's success or failure inside an `Exit` type, allowing + * you to handle both cases explicitly. + * + * The resulting effect cannot fail because the failure is encapsulated within + * the `Exit.Failure` type. The error type is set to `never`, indicating that + * the effect is structured to never fail directly. + * + * **Example** (Capturing completion as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const success = Effect.succeed(42) + * const failure = Effect.fail("Something went wrong") + * + * const program1 = Effect.exit(success) + * const program2 = Effect.exit(failure) + * + * Effect.runSync(program1) // => Exit.succeed(42) + * + * Effect.runSync(program2) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link option} for a version that uses `Option` instead. + * @see {@link result} for a version that uses `Result` instead. + * + * @category error handling + * @since 2.0.0 + */ +const exit = _internal_effect_js__rspack_import_1/* .exit */.NS5; +/** + * 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. + * @category mapping + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .map */.TjK; +/** + * Replaces the value inside an effect with a constant value. + * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * + * `as` allows you to ignore the original value inside an effect and + * replace it with a new constant value. + * + * **Example** (Replacing a success value) + * + * ```ts import.meta.vitest + * import { Effect, pipe } from "effect" + * + * // Replaces the value 5 with the constant "new value" + * const program = pipe(Effect.succeed(5), Effect.as("new value")) + * + * Effect.runSync(program) // => "new value" + * ``` + * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping + * @since 2.0.0 + */ +const as = _internal_effect_js__rspack_import_1.as; +/** + * Maps the success value of an `Effect` to `Some`, preserving failures. + * + * **Example** (Wrapping success in Option.some) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.asSome(Effect.succeed(42)) + * + * Effect.runSync(program) // => Option.some(42) + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asSome = _internal_effect_js__rspack_import_1/* .asSome */.Xx$; +/** + * Maps the success value of an `Effect` to `void`, preserving failures. + * + * **Example** (Discarding success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.asVoid(Effect.succeed(42)) + * + * Effect.runSync(program) // => undefined + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .asVoid */.NLW; +/** + * Swaps an effect's success and failure channels. + * + * **When to use** + * + * Use to swap an `Effect`'s success and failure channels. + * + * **Details** + * + * For an `Effect`, the returned effect has type `Effect`. + * + * **Example** (Swapping success and failure channels) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const program = Effect.fail("Oh uh!").pipe(Effect.as(2)) + * + * // ┌─── Effect + * // ▼ + * const flipped = Effect.flip(program) + * Effect.runSync(flipped) // => "Oh uh!" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const flip = _internal_effect_js__rspack_import_1/* .flip */.UUz; +// ----------------------------------------------------------------------------- +// Zipping +// ----------------------------------------------------------------------------- +/** + * Combines two effects into a single effect, producing a tuple with the results of both effects. + * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * + * The `zip` function executes the first effect (left) and then the second effect (right). + * Once both effects succeed, their results are combined into a tuple. + * + * Concurrency: + * + * By default, `zip` processes the effects sequentially. To execute the effects concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two effects sequentially) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Combine the two effects together + * // + * // ┌─── Effect<[number, string], never, never> + * // ▼ + * const program = Effect.zip(task1, task2) + * + * Effect.runSync(program) // => [1, 'hello'] + * ``` + * + * **Example** (Combining two effects concurrently) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * // Run both effects concurrently using the concurrent option + * const program = Effect.zip(task1, task2, { concurrent: true }) + * + * await Effect.runPromise(program) // => [1, 'hello'] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. + * + * @category zipping + * @since 2.0.0 + */ +const zip = _internal_effect_js__rspack_import_1/* .zip */.yU6; +/** + * Combines two effects sequentially and applies a function to their results to + * produce a single value. + * + * **When to use** + * + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. + * + * **Details** + * + * Concurrency: + * + * By default, the effects are run sequentially. To execute them concurrently, + * use the `{ concurrent: true }` option. + * + * **Example** (Combining two success values with a function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task1 = Effect.succeed(1) + * const task2 = Effect.succeed("hello") + * + * const task3 = Effect.zipWith( + * task1, + * task2, + * // Combines results into a single value + * (number, string) => number + string.length + * ) + * + * Effect.runSync(task3) // => 6 + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = _internal_effect_js__rspack_import_1/* .zipWith */.OYO; +// ----------------------------------------------------------------------------- +// Error handling +// ----------------------------------------------------------------------------- +const catch_ = _internal_effect_js__rspack_import_1/* .catch_ */.h_t; + +/** + * Catches and handles specific errors by their `_tag` field, which is used as a + * discriminator. + * + * **When to use** + * + * Use when you need to recover from one specific tagged error in an effect + * error channel. + * + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class NetworkError { + * readonly _tag = "NetworkError" + * constructor(readonly message: string) {} + * } + * + * class ValidationError { + * readonly _tag = "ValidationError" + * constructor(readonly message: string) {} + * } + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError("offline")) + * + * const program = Effect.catchTag( + * task, + * "NetworkError", + * (error) => Effect.succeed(`Recovered from network error: ${error.message}`) + * ) + * + * Effect.runSync(program) // => "Recovered from network error: offline" + * ``` + * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling + * @since 2.0.0 + */ +const catchTag = _internal_effect_js__rspack_import_1/* .catchTag */.KuX; +/** + * Handles multiple errors in a single block of code using their `_tag` field. + * + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** + * + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. + * + * The error type must have a readonly `_tag` field to use `catchTags`. This + * field is used to identify and match errors. + * + * **Example** (Handling multiple tagged errors) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * // Define tagged error types + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * message: string + * }> {} + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * // An effect that might fail with multiple error types + * const program: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 503 })) + * + * // Handle multiple error types at once + * const handled = Effect.catchTags(program, { + * ValidationError: (error) => + * Effect.succeed(`Validation failed: ${error.message}`), + * NetworkError: (error) => Effect.succeed(`Network error: ${error.statusCode}`) + * }) + * + * Effect.runSync(handled) // => "Network error: 503" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchTags = _internal_effect_js__rspack_import_1/* .catchTags */.loE; +/** + * Catches a specific reason within a tagged error. + * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * + * Use this to handle nested error causes without removing the parent error + * from the error channel. The handler receives the unwrapped reason. + * + * **Example** (Handling an error reason) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Handle rate limits specifically + * const handled = program.pipe( + * Effect.catchReason("AiError", "RateLimitError", (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`) + * ) + * ) + * + * Effect.runSync(handled) // => "Retry after 30s" + * ``` + * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling + * @since 4.0.0 + */ +const catchReason = _internal_effect_js__rspack_import_1/* .catchReason */.AXC; +/** + * Catches multiple reasons within a tagged error using an object of handlers. + * + * **Example** (Handling multiple error reasons) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new QuotaExceededError({ limit: 100 }) }) + * ) + * + * const handled = program.pipe( + * Effect.catchReasons("AiError", { + * RateLimitError: (reason) => + * Effect.succeed(`Retry after ${reason.retryAfter}s`), + * QuotaExceededError: (reason) => + * Effect.succeed(`Quota exceeded: ${reason.limit}`) + * }) + * ) + * + * Effect.runSync(handled) // => "Quota exceeded: 100" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchReasons = _internal_effect_js__rspack_import_1/* .catchReasons */.zt4; +/** + * Promotes nested reason errors into the Effect error channel, replacing + * the parent error. + * + * **Example** (Extracting the reason from a tagged error) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class RateLimitError extends Data.TaggedError("RateLimitError")<{ + * retryAfter: number + * }> {} + * + * class QuotaExceededError extends Data.TaggedError("QuotaExceededError")<{ + * limit: number + * }> {} + * + * class AiError extends Data.TaggedError("AiError")<{ + * reason: RateLimitError | QuotaExceededError + * }> {} + * + * const program: Effect.Effect = Effect.fail( + * new AiError({ reason: new RateLimitError({ retryAfter: 30 }) }) + * ) + * + * // Before: Effect + * // After: Effect + * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) + * Effect.runSync(Effect.flip(unwrapped))._tag // => "RateLimitError" + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const unwrapReason = _internal_effect_js__rspack_import_1/* .unwrapReason */.scW; +/** + * Handles both recoverable and unrecoverable errors by providing a recovery + * effect. + * + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. + * + * **Details** + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically shouldn't be recovered from, as + * they often indicate serious issues. However, in some cases, such as + * dynamically loaded plugins, controlled recovery might be needed. + * + * **Example** (Recovering from full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * // An effect that might fail in different ways + * const program = Effect.die("Something went wrong") + * + * // Recover from any cause (including defects) + * const recovered = Effect.catchCause(program, (cause) => { + * if (Cause.hasDies(cause)) { + * return Effect.sync(() => { output.push("Caught defect") }).pipe( + * Effect.as("Recovered from defect") + * ) + * } + * return Effect.succeed("Unknown error") + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = _internal_effect_js__rspack_import_1/* .catchCause */.Tyx; +/** + * Recovers from defects using a provided recovery function. + * + * **When to use** + * + * Use when you need to report or translate defects at integration boundaries. + * + * **Details** + * + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. + * + * When to Recover from Defects: + * + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. + * + * **Example** (Recovering from defects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // An effect that might throw an unexpected error (defect) + * const program = Effect.sync(() => { + * throw new Error("Unexpected error") + * }) + * + * // Recover from defects only + * const recovered = Effect.catchDefect(program, (defect) => { + * return Effect.sync(() => { output.push(`Caught defect: ${(defect as Error).message}`) }).pipe( + * Effect.as("Recovered from defect") + * ) + * }) + * + * void output.push(Effect.runSync(recovered)) + * output // => ["Caught defect: Unexpected error", "Recovered from defect"] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchDefect = _internal_effect_js__rspack_import_1/* .catchDefect */.Fig; +/** + * Recovers from specific errors using a `Predicate` or `Refinement`. + * + * **When to use** + * + * Use when you need to recover from errors that match a condition. + * + * **Details** + * + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. + * + * **Example** (Recovering when a predicate matches) + * + * ```ts import.meta.vitest + * import { Data, Effect, Filter } from "effect" + * + * class NotFound extends Data.TaggedError("NotFound")<{ id: string }> {} + * + * const program = Effect.fail(new NotFound({ id: "user-1" })) + * + * // With a refinement + * const recovered = program.pipe( + * Effect.catchIf( + * (error): error is NotFound => error._tag === "NotFound", + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * // With a Filter + * const recovered2 = program.pipe( + * Effect.catchFilter( + * Filter.tagged("NotFound"), + * (error) => Effect.succeed(`missing:${error.id}`) + * ) + * ) + * + * Effect.runSync(Effect.all([recovered, recovered2])) // => ['missing:user-1', 'missing:user-1'] + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const catchIf = _internal_effect_js__rspack_import_1/* .catchIf */.XWm; +/** + * Recovers from specific errors using a `Filter`. + * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchFilter = _internal_effect_js__rspack_import_1/* .catchFilter */.osR; +/** + * Catches `NoSuchElementError` failures and converts them to `Option.none`. + * + * **When to use** + * + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. + * + * **Details** + * + * Success values become `Option.some`, `NoSuchElementError` becomes + * `Option.none`, and all other errors are preserved. + * + * **Example** (Recovering from missing Option values) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const some = Effect.fromNullishOr(1).pipe(Effect.catchNoSuchElement) + * const none = Effect.fromNullishOr(null).pipe(Effect.catchNoSuchElement) + * + * void output.push(Effect.runSync(some)) + * void output.push(Effect.runSync(none)) + * output // => [Option.some(1), Option.none()] + * ``` + * + * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError` + * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError` + * @see {@link option} for converting any failure into `Option.none` + * + * @category error handling + * @since 4.0.0 + */ +const catchNoSuchElement = _internal_effect_js__rspack_import_1/* .catchNoSuchElement */.U9Y; +/** + * Recovers from specific failures based on a predicate. + * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * + * This function allows you to conditionally catch and recover from failures + * that match a specific predicate. This is useful when you want to handle + * only certain types of errors while letting others propagate. + * + * **Example** (Recovering from selected causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * const output: Array = [] + * + * const httpRequest = Effect.fail("Network Error") + * + * // Only catch network-related failures + * const program = Effect.catchCauseIf( + * httpRequest, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Caught network error: ${Cause.squash(cause)}`) }) + * return "Fallback response" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Caught network error: Network Error", "Fallback response"] + * ``` + * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseIf = _internal_effect_js__rspack_import_1/* .catchCauseIf */.sJf; +/** + * Recovers from specific failures based on a `Filter`. + * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling + * @since 4.0.0 + */ +const catchCauseFilter = _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk; +/** + * Transforms the failure value of an effect without changing its success value. + * + * **When to use** + * + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const mapped = Effect.mapError( + * simulatedTask, + * (message) => new TaskError({ message }) + * ) + * Effect.runSync(Effect.flip(mapped)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .mapError */.xm_; +/** + * Applies transformations to both the success and error channels of an effect. + * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * + * **Details** + * + * This function takes two map functions as arguments: one for the error channel + * and one for the success channel. You can use it when you want to modify both + * the error and the success values without altering the overall success or + * failure status of the effect. + * + * **Example** (Transforming success and failure channels) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * // ┌─── Effect + * // ▼ + * const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1)) + * + * // ┌─── Effect + * // ▼ + * const modified = Effect.mapBoth(simulatedTask, { + * onFailure: (message) => new TaskError({ message }), + * onSuccess: (n) => n > 0 + * }) + * Effect.runSync(Effect.flip(modified)).message // => "Oh no!" + * ``` + * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapError} for a version that operates on the error channel. + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .mapBoth */.UcN; +/** + * Converts typed failures from the error channel into defects, removing the + * error type from the returned effect. + * + * **When to use** + * + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. + * + * **Example** (Converting typed failures into defects) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * + * class DivideByZeroError extends Data.TaggedError("DivideByZeroError")<{}> {} + * + * const divide = (a: number, b: number) => + * b === 0 + * ? Effect.fail(new DivideByZeroError()) + * : Effect.succeed(a / b) + * + * // ┌─── Effect + * // ▼ + * const program = Effect.orDie(divide(1, 0)) + * + * Effect.runSyncExit(program) // => Exit.die(new DivideByZeroError()) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = _internal_effect_js__rspack_import_1/* .orDie */.QgK; +/** + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. + * + * **Example** (Running effects on failure) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a task that fails with an error + * const task: Effect.Effect = Effect.fail("NetworkError") + * + * // Use tapError to log the error message when the task fails + * const tapping = Effect.tapError( + * task, + * (error) => Effect.sync(() => { output.push(`expected error: ${error}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping)) + * output // => ["expected error: NetworkError", Exit.fail("NetworkError")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = _internal_effect_js__rspack_import_1/* .tapError */.sFT; +/** + * Runs an effectful handler when a failure's `_tag` matches. + * + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) + * + * ```ts import.meta.vitest + * import { Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * statusCode: number + * }> {} + * + * class ValidationError extends Data.TaggedError("ValidationError")<{ + * field: string + * }> {} + * + * const task: Effect.Effect = + * Effect.fail(new NetworkError({ statusCode: 504 })) + * + * const program = Effect.tapErrorTag(task, "NetworkError", (error) => + * Effect.sync(() => { output.push(`expected error: ${error.statusCode}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["expected error: 504", Exit.fail(new NetworkError({ statusCode: 504 }))] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapErrorTag = _internal_effect_js__rspack_import_1/* .tapErrorTag */.k$L; +/** + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** + * + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. + * + * **Details** + * + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. + * + * **Example** (Observing full failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.tapCause( + * task, + * (cause) => Effect.sync(() => { output.push(`Logging cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging cause: Something went wrong", Exit.fail("Something went wrong")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = _internal_effect_js__rspack_import_1/* .tapCause */.dGm; +/** + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** + * + * This function allows you to tap into the cause of an effect's failure only when + * the cause matches a specific predicate. This is useful for conditional logging, + * monitoring, or other side effects based on the type of failure. + * + * **Example** (Observing selected failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("Network timeout") + * + * // Only log causes that contain failures (not interrupts or defects) + * const program = Effect.tapCauseIf( + * task, + * Cause.hasFails, + * (cause) => Effect.sync(() => { output.push(`Logging failure cause: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Logging failure cause: Network timeout", Exit.fail("Network timeout")] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseIf = _internal_effect_js__rspack_import_1/* .tapCauseIf */.cA6; +/** + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. + * + * **Details** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing + * @since 4.0.0 + */ +const tapCauseFilter = _internal_effect_js__rspack_import_1/* .tapCauseFilter */.bKC; +/** + * Runs an effectful operation when the source effect dies with a defect. + * + * **Details** + * + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. + * + * **Example** (Observing defects) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * // Simulate a severe failure in the system + * const task2: Effect.Effect = Effect.die( + * "Something went wrong" + * ) + * + * // Log the defect using tapDefect + * const tapping2 = Effect.tapDefect( + * task2, + * (defect) => Effect.sync(() => { output.push(`defect: ${defect}`) }) + * ) + * + * void output.push(Effect.runSyncExit(tapping2)) + * output // => ["defect: Something went wrong", Exit.die("Something went wrong")] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const tapDefect = _internal_effect_js__rspack_import_1/* .tapDefect */.nAi; +/** + * Retries an effect until it succeeds, discarding failures. + * + * **Details** + * + * Yields between attempts so other fibers can run. + * + * **Example** (Retrying until success) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * let attempts = 0 + * + * const flaky = Effect.gen(function*() { + * attempts++ + * yield* Effect.sync(() => { output.push(`Attempt ${attempts}`) }) + * if (attempts < 3) { + * return yield* Effect.fail("Not ready") + * } + * return "Ready" + * }) + * + * const program = Effect.eventually(flaky) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Attempt 1", "Attempt 2", "Attempt 3", "Ready"] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const eventually = _internal_effect_js__rspack_import_1/* .eventually */.u4Y; +/** + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. + * + * **Details** + * + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. + * + * **Gotchas** + * + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. + * + * Defects and interruptions are not retried. + * + * **Example** (Retrying with a schedule) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * + * class AttemptError extends Data.TaggedError("AttemptError")<{ readonly attempt: number }> {} + * + * let attempt = 0 + * const task = Effect.callback((resume) => { + * attempt++ + * if (attempt <= 2) { + * resume(Effect.fail(new AttemptError({ attempt }))) + * } else { + * resume(Effect.succeed("Success!")) + * } + * }) + * + * const policy = Schedule.recurs(5) + * const program = Effect.retry(task, policy) + * + * await Effect.runPromise(program) // => "Success!" + * ``` + * + * @see {@link retryOrElse} for a version that allows you to run a fallback. + * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. + * @category error handling + * @since 2.0.0 + */ +const retry = _internal_schedule_js__rspack_import_2/* .retry */.L5; +/** + * Retries a failing effect and runs a fallback effect if retries are exhausted. + * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * + * **Details** + * + * The `Effect.retryOrElse` function attempts to retry a failing effect multiple + * times according to a defined {@link Schedule} policy. + * + * If the retries are exhausted and the effect still fails, it runs a fallback + * effect instead. + * + * **Example** (Falling back after retries are exhausted) + * + * ```ts import.meta.vitest + * import { Data, Effect, Schedule } from "effect" + * const output: Array = [] + * + * class NetworkTimeoutError extends Data.TaggedError("NetworkTimeoutError")<{}> {} + * + * let attempt = 0 + * const networkRequest = Effect.gen(function*() { + * attempt++ + * yield* Effect.sync(() => { output.push(`Network attempt ${attempt}`) }) + * if (attempt < 3) { + * return yield* Effect.fail(new NetworkTimeoutError()) + * } + * return "Network data" + * }) + * + * // Retry up to 2 times, then fall back to cached data + * const program = Effect.retryOrElse( + * networkRequest, + * Schedule.recurs(2), + * (error, retryCount) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`All ${retryCount} retries failed, using cache`) }) + * return "Cached data" + * }) + * ) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Network attempt 1", "Network attempt 2", "Network attempt 3", "Network data"] + * ``` + * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling + * @since 2.0.0 + */ +const retryOrElse = _internal_schedule_js__rspack_import_2/* .retryOrElse */.$L; +/** + * Exposes an effect's full failure cause in the error channel as `Cause`. + * + * **Details** + * + * Use `sandbox` when downstream error handling needs to distinguish typed + * failures, defects, and interruptions. Use `unsandbox` to restore the original + * typed error channel after cause-level handling. + * + * **Example** (Exposing failures as causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * // Sandbox exposes the full cause as the error type + * const program = Effect.gen(function*() { + * const result = yield* Effect.flip(Effect.sandbox(task)) + * return `Caught cause: ${Cause.squash(result)}` + * }) + * + * Effect.runSync(program) // => "Caught cause: Something went wrong" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const sandbox = _internal_effect_js__rspack_import_1/* .sandbox */._Sg; +/** + * Discards both the success and failure values of an effect. + * + * **When to use** + * + * Use when an effect should run for its side effects while both success and + * failure values are discarded. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Discarding success and failure values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // ┌─── Effect + * // ▼ + * const task = Effect.fail("Uh oh!").pipe(Effect.as(5)) + * + * // ┌─── Effect + * // ▼ + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * **Example** (Logging failures while ignoring results) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("Uh oh!") + * + * const program = task.pipe(Effect.ignore) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const ignore = _internal_effect_js__rspack_import_1/* .ignore */.XeO; +/** + * Ignores the effect's failure cause, including defects and interruptions. + * + * **When to use** + * + * Use when a best-effort effect should never fail, even from defects or + * interruption, and optional cause logging is enough. + * + * **Details** + * + * Use the `log` option to emit the full {@link Cause} when the effect fails, + * and `message` to prepend a custom log message. + * + * **Example** (Ignoring failures and logging causes) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.fail("boom") + * + * const program = task.pipe(Effect.ignoreCause) + * Effect.runSync(program) // => undefined + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const ignoreCause = _internal_effect_js__rspack_import_1/* .ignoreCause */.GrF; +/** + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources + * until it succeeds or the plan is exhausted. + * + * **Details** + * + * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), + * and retry timing is derived per step (the first attempt uses the remaining + * attempts schedule; later retries apply the step schedule at least once). + * + * Attempts can be observed from outside the effect by passing + * `options.onEvent`, which receives an `ExecutionPlan.Event` before each + * attempt and after it settles. The handler is awaited inline before and after + * every attempt, so events are strictly ordered; keep it cheap. It cannot + * fail, which keeps observation from changing the plan's outcome, and its + * requirements are added to the resulting effect. Terminal events run like + * finalizers, so they are emitted even when the attempt is interrupted. + * + * **Example** (Retrying with an execution plan) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }), attempts: 2 }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const program = Effect.withExecutionPlan(fetchUrl, plan) + * Effect.runSync(program) // => "good" + * ``` + * + * **Example** (Observing execution-plan attempts) + * + * ```ts import.meta.vitest + * import { Context, Effect, ExecutionPlan, Layer } from "effect" + * + * const Endpoint = Context.Service<{ url: string }>("Endpoint") + * + * const fetchUrl = Effect.gen(function*() { + * const endpoint = yield* Effect.service(Endpoint) + * if (endpoint.url === "bad") { + * return yield* Effect.fail("Unavailable") + * } + * return endpoint.url + * }) + * + * const plan = ExecutionPlan.make( + * { provide: Layer.succeed(Endpoint, { url: "bad" }) }, + * { provide: Layer.succeed(Endpoint, { url: "good" }) } + * ) + * + * const events: Array = [] + * const program = Effect.withExecutionPlan(fetchUrl, plan, { + * onEvent: (event) => Effect.sync(() => events.push(`${event._tag}:${event.stepIndex}`)) + * }) + * + * await Effect.runPromise(program) // => "good" + * + * events // => ["AttemptStart:0", "AttemptFailure:0", "AttemptStart:1", "AttemptSuccess:1"] + * ``` + * + * @category error handling + * @since 3.16.0 + */ +const withExecutionPlan = _internal_executionPlan_js__rspack_import_3/* .withExecutionPlan */.OR; +/** + * Runs an effect and reports any errors to the configured `ErrorReporter`s. + * + * **Details** + * + * If the `defectsOnly` option is set to `true`, only defects (unrecoverable + * errors) will be reported, while regular failures will be ignored. + * + * @category error handling + * @since 4.0.0 + */ +const withErrorReporting = _internal_effect_js__rspack_import_1/* .withErrorReporting */.$$g; +// ----------------------------------------------------------------------------- +// Fallback +// ----------------------------------------------------------------------------- +/** + * Recovers from a typed failure by producing a fallback success value. + * + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. + * + * Defects and interruptions are not recovered by this operator. + * + * **Example** (Replacing failures with a value) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * const validate = (age: number): Effect.Effect => { + * if (age < 0) { + * return Effect.fail("NegativeAgeError") + * } else if (age < 18) { + * return Effect.fail("IllegalAgeError") + * } else { + * return Effect.succeed(age) + * } + * } + * + * const program = Effect.orElseSucceed(validate(-1), () => 18) + * + * Effect.runSyncExit(program) // => Exit.succeed(18) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSucceed = _internal_effect_js__rspack_import_1/* .orElseSucceed */.DM4; +/** + * Runs a sequence of effects and returns the result of the first successful + * one. + * + * **When to use** + * + * Use when you have prioritized fallback `Effect`s, such as attempting + * multiple APIs, reading configuration from several sources, or trying + * alternative resource locations in order. + * + * **Details** + * + * This function executes the provided effects in sequence, stopping at the + * first success. If an effect succeeds, its result is returned immediately and + * no further effects in the sequence are executed. + * + * If all effects fail, the returned effect fails with the error from the last + * effect. If the collection is empty, the returned effect defects with an + * `Error` whose message is `"Received an empty collection of effects"`. + * + * **Example** (Trying alternatives until one succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const primary = Effect.fail("primary unavailable") + * const secondary = Effect.succeed("secondary result") + * const tertiary = Effect.sync(() => { + * throw new Error("not evaluated") + * }) + * + * const program = Effect.firstSuccessOf([ + * primary, + * secondary, + * tertiary + * ]) + * + * Effect.runSync(program) // => "secondary result" + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const firstSuccessOf = _internal_effect_js__rspack_import_1/* .firstSuccessOf */.Dd; +// ----------------------------------------------------------------------------- +// Delays & timeouts +// ----------------------------------------------------------------------------- +/** + * Adds a time limit to an effect, triggering a timeout if the effect exceeds + * the duration. + * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * + * The `timeout` function allows you to specify a time limit for an + * effect's execution. If the effect does not complete within the given time, a + * `TimeoutError` is raised. This can be useful for controlling how long your + * program waits for a task to finish, ensuring that it doesn't hang + * indefinitely if the task takes too long. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const timedEffect = Effect.never.pipe(Effect.timeout(0)) + * const error = await Effect.runPromise(Effect.flip(timedEffect)) + * error._tag // => "TimeoutError" + * ``` + * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timeout = _internal_effect_js__rspack_import_1/* .timeout */.wRz; +/** + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. + * + * **When to use** + * + * Use when a timeout of an `Effect` should be handled as `Option.none`. + * + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const timedOutEffect = Effect.never.pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(timedOutEffect) // => Option.none() + * ``` + * + * @see {@link timeout} for a version that raises a `TimeoutError`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts + * @since 3.1.0 + */ +const timeoutOption = _internal_effect_js__rspack_import_1/* .timeoutOption */.D52; +/** + * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. + * + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.timeoutOrElse(Effect.never, { + * duration: 0, + * orElse: () => Effect.sync(() => { output.push("Query timed out, using cached data") }).pipe( + * Effect.as("Cached result") + * ) + * }) + * + * void output.push(await Effect.runPromise(program)) + * output // => ["Query timed out, using cached data", "Cached result"] + * ``` + * + * @see {@link timeout} for failing with a `TimeoutError`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 + */ +const timeoutOrElse = _internal_effect_js__rspack_import_1/* .timeoutOrElse */.mgX; +/** + * Returns an effect that is delayed from this effect by the specified + * `Duration`. + * + * **Example** (Delaying an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.delay(Effect.sync(() => { output.push("Delayed message") }), 0) + * + * await Effect.runPromise(program) + * output // => ["Delayed message"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const delay = _internal_effect_js__rspack_import_1/* .delay */.cbG; +/** + * Returns an effect that suspends the current fiber for the specified duration + * without blocking a JavaScript thread. + * + * **Example** (Pausing without blocking) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Start") }) + * yield* Effect.sleep(0) + * yield* Effect.sync(() => { output.push("End") }) + * }) + * + * await Effect.runPromise(program) + * output // => ["Start", "End"] + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const sleep = _internal_effect_js__rspack_import_1/* .sleep */.yy4; +/** + * Returns the runtime duration of an effect together with its result. + * + * **Details** + * + * The original success, failure, or interruption is preserved; only the success + * value is paired with the duration. + * + * **Example** (Measuring execution time) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const [, value] = yield* Effect.timed(Effect.succeed("ok")) + * return value + * }) + * + * Effect.runSync(program) // => "ok" + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const timed = _internal_effect_js__rspack_import_1/* .timed */.ayu; +// ----------------------------------------------------------------------------- +// Racing +// ----------------------------------------------------------------------------- +/** + * Runs multiple effects concurrently and returns the first successful result. + * + * **When to use** + * + * Use when early failures should be ignored until a success occurs + * or all effects fail. + * + * **Details** + * + * Early failures do not finish the race; `raceAll` keeps waiting until one + * effect succeeds or every effect has failed. When one effect succeeds, the + * remaining effects are interrupted. If every effect fails, the returned effect + * fails with a cause containing the collected failure reasons. + * + * **Example** (Racing many effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAll([ + * Effect.succeed("Fast"), + * Effect.never + * ]) + * await Effect.runPromise(raced) // => "Fast" + * ``` + * + * @see {@link race} for a version that handles only two effects. + * @category racing + * @since 2.0.0 + */ +const raceAll = _internal_effect_js__rspack_import_1/* .raceAll */.Vdx; +/** + * Runs multiple effects concurrently and completes with the first effect to + * finish, whether it succeeds or fails. + * + * **Details** + * + * After the first effect completes, all remaining effects are interrupted. Use + * `raceAll` when early failures should be ignored until a success occurs or + * all effects fail. + * + * **Example** (Taking the first settled result) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const raced = Effect.raceAllFirst([ + * Effect.fail("First failed"), + * Effect.never + * ]) + * await Effect.runPromise(Effect.flip(raced)) // => "First failed" + * ``` + * + * @category racing + * @since 4.0.0 + */ +const raceAllFirst = _internal_effect_js__rspack_import_1/* .raceAllFirst */.FfP; +/** + * Races two effects and returns the first successful result. + * + * **Details** + * + * If one effect succeeds, the other is interrupted and `onWinner` can observe the + * winning fiber. If both fail, the race fails. + * + * **Example** (Racing two effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.succeed("slow-success") + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.race(fastFail, slowSuccess) + * yield* Effect.sync(() => { output.push(`winner: ${result}`) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["winner: slow-success"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const race = _internal_effect_js__rspack_import_1/* .race */.O4F; +/** + * Races two effects and returns the result of the first one to complete, whether + * it succeeds or fails. + * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * + * The losing effect is interrupted, and `onWinner` can observe the winning fiber. + * + * **Example** (Observing the winning fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const fastFail = Effect.fail("fast-fail") + * const slowSuccess = Effect.never + * + * const program = Effect.gen(function*() { + * const message = yield* Effect.match(Effect.raceFirst(fastFail, slowSuccess), { + * onFailure: (error) => `failed: ${error}`, + * onSuccess: (value) => `succeeded: ${value}` + * }) + * yield* Effect.sync(() => { output.push(message) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["failed: fast-fail"] + * ``` + * + * @category racing + * @since 2.0.0 + */ +const raceFirst = _internal_effect_js__rspack_import_1/* .raceFirst */.KT6; +// ----------------------------------------------------------------------------- +// Filtering +// ----------------------------------------------------------------------------- +/** + * Filters elements of an iterable using a predicate, refinement, or effectful + * predicate. + * + * **Example** (Filtering success values) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // Sync predicate + * const evens = Effect.filter([1, 2, 3, 4], (n) => n % 2 === 0) + * + * // Effectful predicate + * const checked = Effect.filter([1, 2, 3], (n) => Effect.succeed(n > 1)) + * + * void output.push(Effect.runSync(evens)) + * void output.push(Effect.runSync(checked)) + * output // => [[2, 4], [2, 3]] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = _internal_effect_js__rspack_import_1/* .filter */.pbD; +/** + * Filters and maps elements of an iterable with a `Filter`. + * + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = _internal_effect_js__rspack_import_1/* .filterMap */.x1Q; +/** + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering + * @since 4.0.0 + */ +const filterMapEffect = _internal_effect_js__rspack_import_1/* .filterMapEffect */.E8K; +/** + * Filters an effect, providing an alternative effect if the predicate fails. + * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, it executes the `orElse` effect instead. The + * `orElse` effect can produce an alternative value or perform additional + * computations. + * + * **Example** (Filtering with a fallback effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, provide alternative for odd numbers + * const filtered = Effect.filterOrElse( + * program, + * (n) => n % 2 === 0, + * (n) => Effect.succeed(`Number ${n} is odd`) + * ) + * + * Effect.runSync(filtered) // => "Number 5 is odd" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrElse = _internal_effect_js__rspack_import_1/* .filterOrElse */.Pm0; +/** + * Filters an effect with a `Filter`, providing an alternative effect on failure. + * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrElse = _internal_effect_js__rspack_import_1/* .filterMapOrElse */.VtY; +/** + * Filters an effect, failing with a custom error if the predicate fails. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, the effect fails with either a custom + * error (if `orFailWith` is provided) or a `NoSuchElementError`. + * + * **Example** (Filtering with a custom failure) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // An effect that produces a number + * const program = Effect.succeed(5) + * + * // Filter for even numbers, fail for odd numbers + * const filtered = Effect.filterOrFail( + * program, + * (n) => n % 2 === 0, + * (n) => `Expected even number, got ${n}` + * ) + * + * Effect.runSync(Effect.flip(filtered)) // => "Expected even number, got 5" + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterOrFail = _internal_effect_js__rspack_import_1/* .filterOrFail */.W$I; +/** + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering + * @since 4.0.0 + */ +const filterMapOrFail = _internal_effect_js__rspack_import_1/* .filterMapOrFail */.ahH; +// ----------------------------------------------------------------------------- +// Conditional Operators +// ----------------------------------------------------------------------------- +/** + * Runs an effect conditionally based on the result of an effectful boolean + * condition. + * + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. + * + * **Details** + * + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. + * + * **Example** (Conditionally running an effect) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * const output: Array = [] + * + * const shouldLog = true + * + * const program = Effect.when( + * Effect.sync(() => { output.push("Condition is true!") }), + * Effect.succeed(shouldLog) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Condition is true!", Option.some(undefined)] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const when = _internal_effect_js__rspack_import_1/* .when */.z7s; +// ----------------------------------------------------------------------------- +// Pattern matching +// ----------------------------------------------------------------------------- +/** + * Handles both success and failure cases of an effect without performing side + * effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * + * **Details** + * + * `match` lets you define custom handlers for both success and failure + * scenarios. You provide separate functions to handle each case, allowing you + * to process the result if the effect succeeds, or handle the error if the + * effect fails. + * + * **Example** (Matching success and failure values) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * + * const program1 = Effect.match(success, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the successful effect + * Effect.runSync(program1) // => "success: 42" + * + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program2 = Effect.match(failure, { + * onFailure: (error) => `failure: ${error.message}`, + * onSuccess: (value) => `success: ${value}` + * }) + * + * // Run and log the result of the failed effect + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .match */.YWq; +/** + * Handles both success and failure cases of an effect without performing side + * effects, with eager evaluation for resolved effects. + * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * + * **Details** + * + * `matchEager` works like `match` but provides better performance for resolved + * effects (Success or Failure). When the effect is already resolved, it applies + * the handlers immediately without fiber scheduling. For unresolved effects, + * it falls back to the regular `match` behavior. + * + * **Example** (Pattern matching eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = yield* Effect.matchEager(Effect.succeed(42), { + * onFailure: (error) => `Failed: ${error}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * void output.push(result) + * }) + * + * Effect.runSync(program) + * output // => ["Success: 42"] + * ``` + * + * @see {@link match} for the non-eager version. + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching + * @since 4.0.0 + */ +const matchEager = _internal_effect_js__rspack_import_1/* .matchEager */.G$Q; +/** + * Handles failures by matching the cause of failure. + * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * + * **Details** + * + * The `matchCause` function allows you to handle failures with access to the + * full cause of the failure within a fiber. + * + * **Example** (Matching on success or failure causes) + * + * ```ts import.meta.vitest + * import { Cause, Effect } from "effect" + * + * const task = Effect.fail("Something went wrong") + * + * const program = Effect.matchCause(task, { + * onFailure: (cause) => `Failed: ${Cause.squash(cause)}`, + * onSuccess: (value) => `Success: ${value}` + * }) + * + * Effect.runSync(program) // => "Failed: Something went wrong" + * ``` + * + * @see {@link matchCauseEffect} if you need to perform side effects in the + * handlers. + * @see {@link match} if you don't need to handle the cause of the failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchCause = _internal_effect_js__rspack_import_1/* .matchCause */.D$$; +/** + * Handles failures by matching the cause of failure with eager evaluation. + * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * + * **Details** + * + * `matchCauseEager` works like `matchCause` but provides better performance for resolved + * effects by immediately applying the matching function instead of deferring it + * through the effect pipeline. + * + * **Example** (Eagerly matching already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const handleResult = Effect.matchCauseEager(Effect.succeed(42), { + * onSuccess: (value) => `Success: ${value}`, + * onFailure: (cause) => `Failed: ${cause}` + * }) + * Effect.runSync(handleResult) // => "Success: 42" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEager = _internal_effect_js__rspack_import_1/* .matchCauseEager */.NZb; +/** + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** + * + * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like + * {@link matchCauseEffect}. + * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching + * @since 4.0.0 + */ +const matchCauseEffectEager = _internal_effect_js__rspack_import_1/* .matchCauseEffectEager */.wR5; +/** + * Handles failures with access to the cause and allows performing side effects. + * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * + * **Details** + * + * The `matchCauseEffect` function works similarly to {@link matchCause}, but it + * also allows you to perform additional side effects based on the failure + * cause. This function provides access to the complete cause of the failure, + * making it possible to differentiate between various failure types, and allows + * you to respond accordingly while performing side effects (like logging or + * other operations). + * + * **Example** (Effectfully matching on causes) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Result } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const task = Effect.fail(new TaskError({ message: "Task failed" })) + * + * const program = Effect.matchCauseEffect(task, { + * onFailure: (cause) => + * Effect.gen(function*() { + * if (Cause.hasFails(cause)) { + * const error = Cause.findError(cause) + * if (Result.isSuccess(error)) { + * yield* Effect.sync(() => { output.push(`Handling error: ${error.success.message}`) }) + * } + * return "recovered from error" + * } else { + * yield* Effect.sync(() => { output.push("Handling interruption or defect") }) + * return "recovered from interruption/defect" + * } + * }), + * onSuccess: (value) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Success: ${value}`) }) + * return `processed ${value}` + * }) + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Handling error: Task failed", "recovered from error"] + * ``` + * + * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. + * @see {@link matchEffect} if you don't need to handle the cause of the failure. + * + * @category pattern matching + * @since 2.0.0 + */ +const matchCauseEffect = _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu; +/** + * Handles both success and failure by running effectful handlers. + * + * **When to use** + * + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. + * + * **Details** + * + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. + * + * **Example** (Matching success and failure with effectful handlers) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} + * + * const success: Effect.Effect = Effect.succeed(42) + * const failure: Effect.Effect = Effect.fail( + * new ExampleError({ message: "Uh oh!" }) + * ) + * + * const program1 = Effect.matchEffect(success, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program1) // => "success: 42" + * + * const program2 = Effect.matchEffect(failure, { + * onFailure: (error) => + * Effect.succeed(`failure: ${error.message}`), + * onSuccess: (value) => + * Effect.succeed(`success: ${value}`) + * }) + * + * Effect.runSync(program2) // => "failure: Uh oh!" + * ``` + * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching + * @since 2.0.0 + */ +const matchEffect = _internal_effect_js__rspack_import_1/* .matchEffect */.tvg; +// ----------------------------------------------------------------------------- +// Condition checking +// ----------------------------------------------------------------------------- +/** + * Determines whether an effect fails. + * + * **Details** + * + * Defects are not converted; if the effect dies, the resulting effect dies too. + * + * **Example** (Checking whether an effect fails) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const failed = yield* Effect.isFailure(Effect.fail("Uh oh!")) + * yield* Effect.sync(() => { output.push(failed) }) + * }) + * + * Effect.runSync(program) + * output // => [true] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .isFailure */.N6O; +/** + * Returns whether an effect completes successfully. + * + * **Details** + * + * Returns `false` for failures in the error channel, but defects still fail the + * effect. + * + * **Example** (Checking whether an effect succeeds) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ok = yield* Effect.isSuccess(Effect.succeed("done")) + * const failed = yield* Effect.isSuccess(Effect.fail("Uh oh")) + * yield* Effect.sync(() => { output.push(`ok: ${ok}`) }) + * yield* Effect.sync(() => { output.push(`failed: ${failed}`) }) + * }) + * + * Effect.runSync(program) + * output // => ["ok: true", "failed: false"] + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .isSuccess */.oJd; +// ----------------------------------------------------------------------------- +// Environment +// ----------------------------------------------------------------------------- +/** + * 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 + * + * @category accessors + * @since 2.0.0 + */ +const context = _internal_effect_js__rspack_import_1/* .context */._OA; +/** + * Transforms the current context using the provided function. + * + * **When to use** + * + * Use to derive an effect from the complete `Context`. + * + * **Details** + * + * This function allows you to access the complete context and perform + * computations based on all available services. This is useful when you need + * to conditionally execute logic based on what services are available. + * + * **Example** (Deriving values from the context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Cache = Context.Service<{ + * get: (key: string) => string | null + * }>("Cache") + * + * const program = Effect.contextWith((services: Context.Context>) => { + * const cacheOption = Context.getOption(services, Cache) + * const hasCache = Option.isSome(cacheOption) + * + * if (hasCache) { + * return Effect.gen(function*() { + * const cache = yield* Effect.service(Cache) + * yield* Effect.sync(() => { output.push("Using cached data") }) + * return cache.get("user:123") || "default" + * }) + * } else { + * return Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("No cache available, using fallback") }) + * return "fallback data" + * }) + * } + * }) + * + * const withCache = Effect.provideService(program, Cache, { + * get: () => "cached_value" + * }) + * void output.push(Effect.runSync(withCache)) + * output // => ["Using cached data", "cached_value"] + * ``` + * + * @see {@link context} for reading the complete context as a value + * @see {@link service} for reading one service from the context + * + * @category accessors + * @since 2.0.0 + */ +const contextWith = _internal_effect_js__rspack_import_1/* .contextWith */.sxi; +/** + * Provides dependencies to an effect using layers or a context. Use `options.local` + * to build the layer every time; by default, layers are shared between provide + * calls. + * + * **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" + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provide = _internal_layer_js__rspack_import_4/* .provide */.G; +/** + * Provides a context to an effect, fulfilling its service requirements. + * + * **Details** + * + * This function provides multiple services at once by supplying a context + * that contains all the required services. It removes the provided services + * from the effect's requirements, making them available to the effect. + * + * **Example** (Providing a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define service keys + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Database = Context.Service<{ + * query: (sql: string) => string + * }>("Database") + * + * // Create a context with multiple services + * const context = Context.make(Logger, { log: (message) => { output.push(message) } }) + * .pipe(Context.add(Database, { query: () => "result" })) + * + * // An effect that requires both services + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * const db = yield* Effect.service(Database) + * logger.log("Querying database") + * return db.query("SELECT * FROM users") + * }) + * + * const provided = Effect.provideContext(program, context) + * void output.push(Effect.runSync(provided)) + * output // => ["Querying database", "result"] + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const provideContext = _internal_effect_js__rspack_import_1/* .provideContext */.PpN; +/** + * Runs an effect with the provided context as its complete environment. + * + * **When to use** + * + * Use when you already have a `Context` containing every service required by + * the effect and want the wrapped effect to run with exactly that context. + * + * **Gotchas** + * + * `setContext` replaces the current context for the wrapped effect. Services + * from an outer context are not inherited unless they are also present in the + * context passed to `setContext`. + * + * **Example** (Running with a complete context) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const program = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * return `${config.greeting}, World!` + * }) + * + * const context = Context.make(Config, { greeting: "Hello" }) + * + * const runnable = Effect.setContext(program, context) + * + * Effect.runSync(runnable) // => "Hello, World!" + * ``` + * + * @see {@link provideContext} for partially satisfying an effect's context requirements. + * @see {@link updateContext} for deriving the required context from the current one. + * + * @category providing services + * @since 4.0.0 + */ +const setContext = _internal_effect_js__rspack_import_1/* .setContext */.oao; +/** + * Accesses a service from the context. + * + * **Example** (Accessing a required service) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Database { + * readonly query: (sql: string) => Effect.Effect + * } + * + * const Database = Context.Service("Database") + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * const runnable = Effect.provideService(program, Database, { + * query: (sql) => Effect.succeed(`Result for: ${sql}`) + * }) + * Effect.runSync(runnable) // => "Result for: SELECT * FROM users" + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const service = _internal_effect_js__rspack_import_1/* .service */.euC; +/** + * Optionally accesses a service from the environment. + * + * **When to use** + * + * Use to read an optional dependency from the current context without making + * that dependency part of the effect's required environment. + * + * **Details** + * + * This function attempts to access a service from the environment. If the + * service is available, it returns `Some(service)`. If the service is not + * available, it returns `None`. Unlike `service`, this function does not + * require the service to be present in the environment. + * + * **Example** (Accessing an optional service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Option } from "effect" + * const output: Array = [] + * + * // Define a service key + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * // Use serviceOption to optionally access the logger + * const program = Effect.gen(function*() { + * const maybeLogger = yield* Effect.serviceOption(Logger) + * + * if (Option.isSome(maybeLogger)) { + * maybeLogger.value.log("Service is available") + * } else { + * void output.push("Service not available") + * } + * }) + * + * Effect.runSync(program) + * output // => ["Service not available"] + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const serviceOption = _internal_effect_js__rspack_import_1/* .serviceOption */.Nav; +/** + * Provides part of the required context while leaving the rest unchanged. + * + * **Details** + * + * This function allows you to transform the context required by an effect, + * providing part of the context and leaving the rest to be fulfilled later. + * + * **Example** (Updating the context before running) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * // Define services + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * const Config = Context.Service<{ + * name: string + * }>("Config") + * + * const program = Effect.service(Config).pipe( + * Effect.map((config) => `Hello ${config.name}!`) + * ) + * + * // Transform services by providing Config while keeping Logger requirement + * const configured = program.pipe( + * Effect.updateContext((context: Context.Context>) => + * Context.add(context, Config, { name: "World" }) + * ) + * ) + * + * // The effect now requires only Logger service + * const result = Effect.provideService(configured, Logger, { + * log: () => {} + * }) + * Effect.runSync(result) // => "Hello World!" + * ``` + * + * @category providing services + * @since 4.0.0 + */ +const updateContext = _internal_effect_js__rspack_import_1/* .updateContext */.r_d; +/** + * 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] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const updateService = _internal_effect_js__rspack_import_1/* .updateService */.bUZ; +/** + * 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 + * + * @category providing services + * @since 4.0.0 + */ +const updateServiceScoped = _internal_effect_js__rspack_import_1/* .updateServiceScoped */.L_I; +/** + * Provides one concrete service implementation to an effect. + * + * **When to use** + * + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a service for configuration + * const Config = Context.Service<{ + * apiUrl: string + * timeout: number + * }>("Config") + * + * const fetchData = Effect.gen(function*() { + * const config = yield* Effect.service(Config) + * yield* Effect.sync(() => { output.push(`Fetching from: ${config.apiUrl}`) }) + * yield* Effect.sync(() => { output.push(`Timeout: ${config.timeout}ms`) }) + * return "data" + * }) + * + * // Provide the service implementation + * const program = Effect.provideService(fetchData, Config, { + * apiUrl: "https://api.example.com", + * timeout: 5000 + * }) + * + * void output.push(Effect.runSync(program)) + * output // => ["Fetching from: https://api.example.com", "Timeout: 5000ms", "data"] + * ``` + * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category providing services + * @since 2.0.0 + */ +const provideService = _internal_effect_js__rspack_import_1/* .provideService */.PfK; +/** + * Provides one service to an effect using an effectful acquisition. + * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * // Define a database connection service + * interface DatabaseConnection { + * readonly query: (sql: string) => Effect.Effect + * } + * const Database = Context.Service("Database") + * + * // Effect that creates a database connection + * const createConnection = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Establishing database connection...") }) + * yield* Effect.sync(() => { output.push("Database connected!") }) + * return { + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Effect.service(Database) + * return yield* db.query("SELECT * FROM users") + * }) + * + * // Provide the service through an effect + * const withDatabase = Effect.provideServiceEffect( + * program, + * Database, + * createConnection + * ) + * + * void output.push(await Effect.runPromise(withDatabase)) + * output // => ["Establishing database connection...", "Database connected!", "Result for: SELECT * FROM users"] + * ``` + * + * @category providing services + * @since 2.0.0 + */ +const provideServiceEffect = _internal_effect_js__rspack_import_1/* .provideServiceEffect */.c7E; +// ----------------------------------------------------------------------------- +// Resource management & finalization +// ----------------------------------------------------------------------------- +/** + * Returns the current scope for resource management. + * + * **Example** (Accessing the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const currentScope = yield* Effect.scope + * yield* Effect.sync(() => { output.push("Got scope for resource management") }) + * + * // Use the scope to manually manage resources if needed + * const resource = yield* Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * + * return resource + * }) + * + * void output.push(Effect.runSync(Effect.scoped(program))) + * output // => ["Got scope for resource management", "Acquiring resource", "Releasing resource", "resource"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scope = _internal_effect_js__rspack_import_1/* .scope */.z8E; +/** + * 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"] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const scoped = _internal_effect_js__rspack_import_1/* .scoped */.P1j; +/** + * Creates a scoped effect by providing access to the scope. + * + * **When to use** + * + * Use when resource acquisition needs direct access to the scope being created, + * for example to register finalizers manually. + * + * **Example** (Working with an explicit scope) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * const output: Array = [] + * + * const program = Effect.scopedWith((scope) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Inside scoped context") }) + * + * // Manually add a finalizer to the scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => { output.push("Manual finalizer") })) + * + * // Create a scoped resource + * const resource = yield* Effect.scoped( + * Effect.acquireRelease( + * Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), + * () => Effect.sync(() => { output.push("Releasing resource") }) + * ) + * ) + * + * return resource + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Inside scoped context", "Acquiring resource", "Releasing resource", "Manual finalizer", "resource"] + * ``` + * + * @category resource management + * @since 3.11.0 + */ +const scopedWith = _internal_effect_js__rspack_import_1/* .scopedWith */.Pxi; +/** + * 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 + * + * @category resource management + * @since 2.0.0 + */ +const acquireRelease = _internal_effect_js__rspack_import_1/* .acquireRelease */.Q56; +/** + * Acquires a scoped resource that implements JavaScript disposal protocols. + * + * **When to use** + * + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. + * + * **Details** + * + * The resource is automatically disposed when the surrounding + * {@link Scope} is closed, using {@link Symbol.dispose} for + * synchronous disposables or {@link Symbol.asyncDispose} for asynchronous + * disposables. + * + * This is similar to {@link acquireRelease}, but uses the standard + * JavaScript disposal protocol instead of requiring an explicit release + * function. It works with JavaScript `Disposable` and `AsyncDisposable` + * resources. + * + * **Example** (Acquiring a disposable resource) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * class Resource implements Disposable { + * [Symbol.dispose]() { + * void output.push("disposed") + * } + * } + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.acquireDisposable(Effect.succeed(new Resource())) + * void output.push("acquired") + * }) + * ) + * + * Effect.runSync(program) + * output // => ["acquired", "disposed"] + * ``` + * + * @see {@link acquireRelease} for resources that need an explicit finalizer + * + * @category resource management + * @since 4.0.0 + */ +const acquireDisposable = _internal_effect_js__rspack_import_1/* .acquireDisposable */.N24; +/** + * Runs resource acquisition, usage, and release as one bracketed effect. + * + * **When to use** + * + * Use to bracket acquire, use, and release logic in one effect. + * + * **Details** + * + * `acquireUseRelease` does the following: + * + * 1. Ensures that the `Effect` value that acquires the resource will not be + * interrupted. Note that acquisition may still fail due to internal + * reasons (such as an uncaught exception). + * 2. Ensures that the `release` `Effect` value will not be interrupted, + * and will be executed as long as the acquisition `Effect` value + * successfully acquires the resource. + * + * During the time period between the acquisition and release of the resource, + * the `use` `Effect` value will be executed. + * + * If the `release` `Effect` value fails, then the entire `Effect` value will + * fail, even if the `use` `Effect` value succeeds. If this fail-fast behavior + * is not desired, errors produced by the `release` `Effect` value can be caught + * and ignored. + * + * **Example** (Acquiring resources with cleanup) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * readonly connection: string + * readonly query: (sql: string) => Effect.Effect + * } + * + * const program = Effect.acquireUseRelease( + * // Acquire - connect to database + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Connecting to database...") }) + * return { + * connection: "db://localhost:5432", + * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) + * } + * }), + * // Use - perform database operations + * (db) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Connected to ${db.connection}`) }) + * const result = yield* db.query("SELECT * FROM users") + * yield* Effect.sync(() => { output.push(`Query result: ${result}`) }) + * return result + * }), + * // Release - close database connection + * (db, exit) => + * Effect.gen(function*() { + * if (Exit.isSuccess(exit)) { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (success)`) }) + * } else { + * yield* Effect.sync(() => { output.push(`Closing connection to ${db.connection} (failure)`) }) + * } + * }) + * ) + * + * await Effect.runPromise(program) + * output // => ["Connecting to database...", "Connected to db://localhost:5432", "Query result: Result for: SELECT * FROM users", "Closing connection to db://localhost:5432 (success)"] + * ``` + * + * @see {@link acquireRelease} for scoped resources whose use happens later + * + * @category resource management + * @since 2.0.0 + */ +const acquireUseRelease = _internal_effect_js__rspack_import_1/* .acquireUseRelease */.jGc; +/** + * Adds a finalizer to the current scope. + * + * **When to use** + * + * Use to register low-level cleanup in the current scope. + * + * **Details** + * + * The finalizer runs when the surrounding scope is closed and receives the + * `Exit` value used to close the scope. + * + * **Example** (Registering scope finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * // Add a finalizer that runs when the scope closes + * yield* Effect.addFinalizer((exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? "Cleanup: Operation completed successfully" + * : "Cleanup: Operation failed, cleaning up resources" + * ) }) + * ) + * + * yield* Effect.sync(() => { output.push("Performing main operation...") }) + * + * // This could succeed or fail + * return "operation result" + * }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Performing main operation...", "Cleanup: Operation completed successfully", "operation result"] + * ``` + * + * @see {@link acquireRelease} for resource acquisition with a release finalizer + * @see {@link ensuring} for attaching a finalizer to one effect + * + * @category resource management + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_1/* .addFinalizer */.U9h; +/** + * Returns an effect that, if this effect _starts_ execution, then the + * specified `finalizer` is guaranteed to be executed, whether this effect + * succeeds, fails, or is interrupted. + * + * **Details** + * + * For use cases that need access to the effect's result, see `onExit`. + * + * Finalizers offer very powerful guarantees, but they are low-level, and + * should generally not be used for releasing resources. For higher-level + * logic built on `ensuring`, see the `acquireRelease` family of methods. + * + * **Example** (Always running cleanup) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task started") }) + * yield* Effect.sync(() => { output.push("Task completed") }) + * return 42 + * }) + * + * // Ensure cleanup always runs, regardless of success or failure + * const program = Effect.ensuring( + * task, + * Effect.sync(() => { output.push("Cleanup: This always runs!") }) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task started", "Task completed", "Cleanup: This always runs!", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const ensuring = _internal_effect_js__rspack_import_1/* .ensuring */.yeE; +/** + * Runs the specified effect if this effect fails, providing the error to the + * effect if it exists. The provided effect will not be interrupted. + * + * **Example** (Running cleanup on failure) + * + * ```ts import.meta.vitest + * import { Cause, Data, Effect, Exit } from "effect" + * const output: Array = [] + * + * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} + * + * const error = new TaskError({ message: "Something went wrong" }) + * const task = Effect.fail(error) + * + * const program = Effect.onError( + * task, + * (cause) => Effect.sync(() => { output.push(`Cleanup on error: ${Cause.squash(cause)}`) }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cleanup on error: TaskError: Something went wrong", Exit.fail(error)] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onError = _internal_effect_js__rspack_import_1/* .onError */.S5A; +/** + * Runs the finalizer only when this effect fails and the `Cause` matches the + * provided predicate. + * + * **Example** (Running cleanup for selected failures) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.fail("boom") + * + * const program = Effect.onErrorIf( + * task, + * Cause.hasFails, + * (cause) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Cause: ${Cause.squash(cause)}`) }) + * }) + * ) + * + * void output.push(Effect.runSyncExit(program)) + * output // => ["Cause: boom", Exit.fail("boom")] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onErrorIf = _internal_effect_js__rspack_import_1/* .onErrorIf */.BeE; +/** + * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management + * @since 4.0.0 + */ +const onErrorFilter = _internal_effect_js__rspack_import_1/* .onErrorFilter */.iKM; +/** + * Runs an optional finalizer with the effect's `Exit` value when the effect + * completes. + * + * **When to use** + * + * Use when you are building a low-level `Effect` operator that must inspect the + * source effect's `Exit`, may skip finalization by returning `undefined`, or + * must choose whether finalization is forced into an uninterruptible region. + * + * **Details** + * + * This low-level operator preserves the source effect's result unless the + * finalizer fails. If both the source effect and the finalizer fail, the two + * causes are merged. Prefer `onExit` for normal cleanup logic. + * + * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect + * + * @category resource management + * @since 4.0.0 + */ +const onExitPrimitive = _internal_effect_js__rspack_import_1/* .onExitPrimitive */.r7h; +/** + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * If both the effect and the cleanup function fail, the two causes are merged. + * + * **Example** (Observing every exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const task = Effect.succeed(42) + * + * const program = Effect.onExit(task, (exit) => + * Effect.sync(() => { output.push( + * Exit.isSuccess(exit) + * ? `Task succeeded with: ${exit.value}` + * : `Task failed: ${Exit.isFailure(exit) ? exit.cause : "interrupted"}` + * ) })) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 2.0.0 + */ +const onExit = _internal_effect_js__rspack_import_1/* .onExit */.cfM; +/** + * Runs the cleanup effect only when the `Exit` satisfies the provided + * predicate. + * + * **Example** (Observing selected exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.onExitIf( + * Effect.succeed(42), + * Exit.isSuccess, + * (exit) => + * Exit.isSuccess(exit) + * ? Effect.sync(() => { output.push(`Succeeded with: ${exit.value}`) }) + * : Effect.void + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Succeeded with: 42", 42] + * ``` + * + * @category resource management + * @since 4.0.0 + */ +const onExitIf = _internal_effect_js__rspack_import_1/* .onExitIf */.fGe; +/** + * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. + * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management + * @since 4.0.0 + */ +const onExitFilter = _internal_effect_js__rspack_import_1/* .onExitFilter */.uRq; +// ----------------------------------------------------------------------------- +// Caching +// ----------------------------------------------------------------------------- +/** + * Returns an effect that lazily computes a result and caches it for subsequent + * evaluations. + * + * **When to use** + * + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. + * + * **Details** + * + * This function wraps an effect and ensures that its result is computed only + * once. Once the result is computed, it is cached, meaning that subsequent + * evaluations of the same effect will return the cached result without + * re-executing the logic. + * + * **Example** (Memoizing an effect until invalidated) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * void output.push("non-cached version:") + * yield* expensiveTask.pipe(Effect.andThen(record)) + * yield* expensiveTask.pipe(Effect.andThen(record)) + * void output.push("cached version:") + * const cached = yield* Effect.cached(expensiveTask) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * await Effect.runPromise(program) + * output // => ["non-cached version:", "expensive task...", "result 1", "expensive task...", "result 2", "cached version:", "expensive task...", "result 3", "result 3"] + * ``` + * + * @see {@link cachedWithTTL} for a similar function that includes a + * time-to-live duration for the cached value. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cached = _internal_effect_js__rspack_import_1/* .cached */.PO3; +/** + * Returns an effect that caches its result for a specified `Duration`, + * known as "timeToLive" (TTL). + * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * + * **Details** + * + * This function is used to cache the result of an effect for a specified amount + * of time. This means that the first time the effect is evaluated, its result + * is computed and stored. + * + * If the effect is evaluated again within the specified `timeToLive`, the + * cached result will be used, avoiding recomputation. + * + * After the specified duration has passed, the cache expires, and the effect + * will be recomputed upon the next evaluation. + * + * **Example** (Memoizing an effect with TTL) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const cached = yield* Effect.cachedWithTTL(expensiveTask, "1 hour") + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "result 1"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching + * @since 2.0.0 + */ +const cachedWithTTL = _internal_effect_js__rspack_import_1/* .cachedWithTTL */.Rgn; +/** + * Creates a cached effect result for a specified duration and allows manual + * invalidation before expiration. + * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * + * **Details** + * + * This function behaves similarly to {@link cachedWithTTL} by caching the + * result of an effect for a specified period of time. However, it introduces an + * additional feature: it provides an effect that allows you to manually + * invalidate the cached result before it naturally expires. + * + * This gives you more control over the cache, allowing you to refresh the + * result when needed, even if the original cache has not yet expired. + * + * Once the cache is invalidated, the next time the effect is evaluated, the + * result will be recomputed, and the cache will be refreshed. + * + * **Example** (Memoizing with TTL and invalidation) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * const record = (value: unknown) => Effect.sync(() => { output.push(value) }) + * + * let i = 1 + * const expensiveTask = Effect.sync(() => { + * void output.push("expensive task...") + * return `result ${i++}` + * }) + * + * const program = Effect.gen(function*() { + * const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL( + * expensiveTask, + * "1 hour" + * ) + * yield* cached.pipe(Effect.andThen(record)) + * yield* cached.pipe(Effect.andThen(record)) + * yield* invalidate + * yield* cached.pipe(Effect.andThen(record)) + * }) + * + * Effect.runSync(program) + * output // => ["expensive task...", "result 1", "result 1", "expensive task...", "result 2"] + * ``` + * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching + * @since 2.0.0 + */ +const cachedInvalidateWithTTL = _internal_effect_js__rspack_import_1/* .cachedInvalidateWithTTL */.CJw; +// ----------------------------------------------------------------------------- +// Interruption +// ----------------------------------------------------------------------------- +/** + * Returns an effect that is immediately interrupted. + * + * **Example** (Creating an interrupted effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * return yield* Effect.interrupt + * yield* Effect.succeed("This won't execute and is unreachable") + * }) + * + * Effect.runSyncExit(program)._tag // => "Failure" + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .interrupt */.GaK; +/** + * Returns a new effect that allows the effect to be interruptible. + * + * **Example** (Allowing interruption) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.interruptible(Effect.never).pipe( + * Effect.timeoutOption(0) + * ) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptible = _internal_effect_js__rspack_import_1/* .interruptible */.Inz; +/** + * Runs the specified finalizer effect if this effect is interrupted. + * + * **Example** (Running cleanup on interruption) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * const task = Effect.forever(Effect.succeed("working...")) + * + * const program = Effect.onInterrupt( + * task, + * () => Effect.sync(() => { output.push("Task was interrupted, cleaning up...") }) + * ) + * + * const fiber = Effect.runFork(program) + * await Effect.runPromise(Fiber.interrupt(fiber)) + * output // => ["Task was interrupted, cleaning up..."] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const onInterrupt = _internal_effect_js__rspack_import_1/* .onInterrupt */.nAr; +/** + * Returns a new effect that disables interruption for the given effect. + * + * **Example** (Preventing interruption) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const criticalTask = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Starting critical section...") }) + * yield* Effect.sync(() => { output.push("Critical section completed") }) + * }) + * + * const program = Effect.uninterruptible(criticalTask) + * + * Effect.runSync(program) + * output // => ["Starting critical section...", "Critical section completed"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptible = _internal_effect_js__rspack_import_1/* .uninterruptible */.rfi; +/** + * Disables interruption and provides a restore function to restore the + * interruptible state within the effect. + * + * **Example** (Restoring interruption in protected regions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.uninterruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * // Restore interruptibility for this part + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to uninterruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Uninterruptible phase...", "Interruptible phase...", "Back to uninterruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const uninterruptibleMask = _internal_effect_js__rspack_import_1/* .uninterruptibleMask */.FcF; +/** + * Runs an effect in an interruptible region while providing `restore` for + * locally restoring the previous interruptibility. + * + * **Example** (Controlling interruptibility locally) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.interruptibleMask((restore) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Interruptible phase...") }) + * // Make this part uninterruptible + * yield* restore( + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Uninterruptible phase...") }) + * }) + * ) + * + * yield* Effect.sync(() => { output.push("Back to interruptible") }) + * }) + * ) + * + * Effect.runSync(program) + * output // => ["Interruptible phase...", "Uninterruptible phase...", "Back to interruptible"] + * ``` + * + * @category interruption + * @since 2.0.0 + */ +const interruptibleMask = _internal_effect_js__rspack_import_1/* .interruptibleMask */.eMl; +/** + * Creates an AbortSignal that is managed by the provided scope. + * + * **When to use** + * + * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation + * through a signal. + * + * **Details** + * + * Each acquisition creates a fresh `AbortController`. Closing the owning scope + * runs a finalizer that aborts the controller and the effect succeeds with the + * controller's signal. + * + * **Gotchas** + * + * The signal is aborted when its owning scope closes, so avoid keeping it for + * work that outlives that scope. + * + * @see {@link scoped} for binding resource lifetime to a scope + * + * @category interruption + * @since 4.0.0 + */ +const abortSignal = _internal_effect_js__rspack_import_1/* .abortSignal */.dsN; +/** + * Repeats this effect forever (until the first error). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Option } from "effect" + * + * const program = Effect.forever(Effect.never).pipe(Effect.timeoutOption(0)) + * await Effect.runPromise(program) // => Option.none() + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const forever = _internal_effect_js__rspack_import_1/* .forever */.i4r; +/** + * Repeats an effect based on a specified schedule or until the first failure. + * + * **When to use** + * + * Use to rerun an effect after successful executions. + * + * **Details** + * + * This function executes an effect repeatedly according to the given schedule. + * Each repetition occurs after the initial execution of the effect, meaning + * that the schedule determines the number of additional repetitions. For + * example, using `Schedule.once` will result in the effect being executed twice + * (once initially and once as part of the repetition). + * + * If the effect succeeds, it is repeated according to the schedule. If it + * fails, the repetition stops immediately, and the failure is returned. + * + * The schedule can also specify delays between repetitions, making it useful + * for tasks like retrying operations with backoff, periodic execution, or + * performing a series of dependent actions. + * + * You can combine schedules for more advanced repetition logic, such as adding + * delays, limiting recursions, or dynamically adjusting based on the outcome of + * each execution. + * + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * + * ```ts import.meta.vitest + * // Success Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const action = Effect.sync(() => { output.push("success") }) + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push(Effect.runSync(program)) + * output // => ["success", "success", "success", 2] + * ``` + * + * **Example** (Stopping repetition on failure) + * + * ```ts import.meta.vitest + * // Failure Example + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * let count = 0 + * + * // Define a callback effect that simulates an action with possible failures + * const action = Effect.callback((resume) => { + * if (count > 1) { + * void output.push("failure") + * resume(Effect.fail("Uh oh!")) + * } else { + * count++ + * void output.push("success") + * resume(Effect.succeed("yay!")) + * } + * }) + * + * const policy = Schedule.recurs(2) + * const program = Effect.repeat(action, policy) + * + * void output.push((await Effect.runPromiseExit(program))._tag) + * output // => ["success", "success", "failure", "Failure"] + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails + * + * @category repetition + * @since 2.0.0 + */ +const repeat = _internal_schedule_js__rspack_import_2/* .repeat */.ux; +/** + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. + * + * **Details** + * + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. + * + * **Example** (Recovering after repetition stops) + * + * ```ts import.meta.vitest + * import { Effect, Option, Schedule } from "effect" + * const output: Array = [] + * + * let attempt = 0 + * const task = Effect.gen(function*() { + * attempt++ + * if (attempt <= 2) { + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} failed`) }) + * return yield* Effect.fail(`Error ${attempt}`) + * } + * yield* Effect.sync(() => { output.push(`Attempt ${attempt} succeeded`) }) + * return "success" + * }) + * + * const program = Effect.repeatOrElse( + * task, + * Schedule.recurs(3), + * (error, attempts) => + * Effect.sync(() => { output.push( + * `Final failure: ${error}, after ${ + * Option.getOrElse(attempts, () => 0) + * } attempts` + * ) }).pipe(Effect.map(() => 0)) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Attempt 1 failed", "Final failure: Error 1, after 0 attempts", 0] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const repeatOrElse = _internal_schedule_js__rspack_import_2/* .repeatOrElse */.i3; +/** + * Returns an array of `n` identical effects. + * + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category repetition + * @since 2.0.0 + */ +const replicate = _internal_effect_js__rspack_import_1/* .replicate */.aAq; +/** + * Performs this effect `n` times and collects results with `Effect.all` semantics. + * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * + * Use `concurrency` to control parallelism and `discard: true` to ignore results. + * + * **Example** (Replicating an effect) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const results = yield* Effect.replicateEffect(3)(Effect.succeed(1)) + * yield* Effect.sync(() => { output.push(results) }) + * }) + * + * Effect.runSync(program) + * output // => [[1, 1, 1]] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const replicateEffect = _internal_effect_js__rspack_import_1/* .replicateEffect */.Xrv; +/** + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. + * + * **Details** + * + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. + * + * **Example** (Scheduling repeated execution) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("Task executing...") }) + * return 1 + * }) + * + * const program = Effect.schedule(task, Schedule.recurs(2)) + * + * void output.push(Effect.runSync(program)) + * output // => ["Task executing...", "Task executing...", 2] + * ``` + * + * @see {@link scheduleFrom} for a variant that allows the schedule's decision + * to depend on the result of this effect. + * + * @category repetition + * @since 2.0.0 + */ +const schedule = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, schedule) => scheduleFrom(self, undefined, schedule)))); +/** + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. + * + * **Details** + * + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. + * + * **Example** (Scheduling from an initial value) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * const output: Array = [] + * + * const task = (input: number) => + * Effect.gen(function*() { + * yield* Effect.sync(() => { output.push(`Processing: ${input}`) }) + * return input + 1 + * }) + * + * // Start with 0, repeat 3 times + * const program = Effect.scheduleFrom( + * task(0), + * 0, + * Schedule.recurs(2) + * ) + * + * void output.push(Effect.runSync(program)) + * output // => ["Processing: 0", "Processing: 0", 2] + * ``` + * + * @category repetition + * @since 2.0.0 + */ +const scheduleFrom = _internal_schedule_js__rspack_import_2/* .scheduleFrom */.mG; +// ----------------------------------------------------------------------------- +// Tracing +// ----------------------------------------------------------------------------- +/** + * Returns the current tracer from the context. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const currentTracer = yield* Effect.tracer + * return typeof currentTracer.span + * }) + * + * Effect.runSync(program) // => "function" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const tracer = _internal_effect_js__rspack_import_1/* .tracer */.kJM; +/** + * Provides a tracer to an effect. + * + * **Example** (Providing a tracer) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.tracer + * return yield* Effect.withTracer(Effect.succeed("completed"), tracer) + * }) + * + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracer = _internal_effect_js__rspack_import_1/* .withTracer */._o1; +/** + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not be registered with the tracer + * Effect.withTracerEnabled(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerEnabled = _internal_effect_js__rspack_import_1/* .withTracerEnabled */.nDN; +/** + * Enables or disables tracer timing for the given Effect. + * + * **Example** (Enabling or disabling tracing timing) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed(42).pipe( + * Effect.withSpan("my-span"), + * // the span will not have timing information + * Effect.withTracerTiming(false) + * ) + * Effect.runSync(program) // => 42 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withTracerTiming = _internal_effect_js__rspack_import_1/* .withTracerTiming */.MaT; +/** + * Adds an annotation to each span in this effect. + * + * **Example** (Annotating all spans) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.succeed("result") + * + * // Add single annotation + * const annotated1 = Effect.annotateSpans(program, "user", "john") + * + * // Add multiple annotations + * const annotated2 = Effect.annotateSpans(program, { + * operation: "data-processing", + * version: "1.0.0", + * environment: "production" + * }) + * + * Effect.runSync(Effect.all([annotated1, annotated2])) // => ['result', 'result'] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateSpans = _internal_effect_js__rspack_import_1/* .annotateSpans */.Muk; +/** + * Adds an annotation to the current span if available. + * + * **Example** (Annotating the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * yield* Effect.annotateCurrentSpan("userId", "123") + * yield* Effect.annotateCurrentSpan({ + * operation: "user-lookup" + * }) + * return "success" + * }) + * + * const traced = Effect.withSpan(program, "user-operation") + * Effect.runSync(traced) // => "success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const annotateCurrentSpan = _internal_effect_js__rspack_import_1/* .annotateCurrentSpan */.ww9; +/** + * Returns the currently active local tracing span. + * + * **Details** + * + * The effect fails with `NoSuchElementError` when there is no active local + * `Span`. + * + * **Example** (Reading the current span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.currentSpan + * return span.name + * }) + * + * const traced = Effect.withSpan(program, "my-span") + * Effect.runSync(traced) // => "my-span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentSpan = _internal_effect_js__rspack_import_1/* .currentSpan */._32; +/** + * Returns the current parent span from the effect context. + * + * **Details** + * + * The effect succeeds with either a local span or external span when one is + * present, and fails with `NoSuchElementError` when no parent span is + * available. + * + * **Example** (Reading the parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const childOperation = Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * return parentSpan._tag + * }) + * + * const program = Effect.withSpan(childOperation, "child-span") + * + * const traced = Effect.withSpan(program, "parent-span") + * Effect.runSync(traced) // => "Span" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const currentParentSpan = _internal_effect_js__rspack_import_1/* .currentParentSpan */.Wj8; +/** + * Returns the tracing span annotations currently carried in the effect context. + * + * **Details** + * + * These annotations are applied to spans created inside the context, such as + * spans created by `withSpan`, `useSpan`, or `makeSpan`. + * + * **Example** (Providing span annotations) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const annotations = yield* Effect.spanAnnotations + * return annotations + * }).pipe(Effect.annotateSpans({ userId: "123", operation: "data-processing" })) + * + * Effect.runSync(program) // => { userId: '123', operation: 'data-processing' } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanAnnotations = _internal_effect_js__rspack_import_1/* .spanAnnotations */.Fu6; +/** + * Returns the tracing span links currently carried in the effect context. + * + * **Details** + * + * These links are attached to spans created inside the context. Span links + * connect related spans without making one span the parent of another. + * + * **Example** (Providing span links) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * // Get the current span links + * const links = yield* Effect.spanLinks + * return links + * }) + * + * Effect.runSync(program).length // => 0 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const spanLinks = _internal_effect_js__rspack_import_1/* .spanLinks */.WbR; +/** + * Adds a link with the provided span to all spans in this effect. + * + * **Details** + * + * This is useful for connecting spans that are related but not in a direct + * parent-child relationship. For example, you might want to link spans from + * parallel operations or connect spans across different traces. + * + * **Example** (Linking one span to another span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.withSpan(Effect.gen(function*() { + * const parentSpan = yield* Effect.currentSpan + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans(parentSpan, { relationship: "follows" }) + * ) + * }), "parent-operation") + * + * Effect.runSync(program).length // => 1 + * ``` + * + * **Example** (Linking multiple spans at once) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span1 = yield* Effect.makeSpan("span-1") + * const span2 = yield* Effect.makeSpan("span-2") + * + * return yield* Effect.spanLinks.pipe( + * Effect.linkSpans([span1, span2], { + * type: "dependency", + * source: "multiple-operations" + * }) + * ) + * }) + * + * Effect.runSync(program).length // => 2 + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const linkSpans = _internal_effect_js__rspack_import_1/* .linkSpans */.A_r; +/** + * Creates a new tracing span and returns it without managing its lifetime. + * + * **Details** + * + * The span is not added to the current span stack and is not ended + * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span + * should be installed as context or closed automatically. + * + * **Example** (Creating a span manually) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("my-operation") + * return span.name + * }) + * + * Effect.runSync(program) // => "my-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpan = _internal_effect_js__rspack_import_1/* .makeSpan */.Z98; +/** + * Create a new span for tracing, and automatically close it when the Scope + * finalizes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Creating a scoped standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const span = yield* Effect.makeSpanScoped("scoped-operation") + * return span.name + * // Span automatically closes when scope ends + * }) + * ) + * + * Effect.runSync(program) // => "scoped-operation" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const makeSpanScoped = _internal_effect_js__rspack_import_1/* .makeSpanScoped */.Rd$; +/** + * Create a new span for tracing, and automatically close it when the effect + * completes. + * + * **Details** + * + * The span is not added to the current span stack, so no child spans will be + * created for it. + * + * **Example** (Running an effect with a standalone span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.useSpan( + * "user-operation", + * (span) => Effect.succeed(`${span.name}: success`) + * ) + * Effect.runSync(program) // => "user-operation: success" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const useSpan = _internal_effect_js__rspack_import_1/* .useSpan */.gvr; +/** + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.succeed("result") + * + * const traced = Effect.withSpan(task, "my-task", { + * attributes: { version: "1.0" } + * }) + * Effect.runSync(traced) // => "result" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = _internal_effect_js__rspack_import_1/* .withSpan */.fRP; +/** + * Wraps the effect with a scoped child span for tracing. + * + * **Details** + * + * The span is ended when the Scope is finalized. + * + * **Example** (Creating a scoped child span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const task = Effect.succeed("working") + * yield* Effect.withSpanScoped(task, "scoped-task") + * return "completed" + * }) + * ) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpanScoped = _internal_effect_js__rspack_import_1/* .withSpanScoped */.zr8; +/** + * Adds the provided span to the current span stack. + * + * **Example** (Setting a parent span) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.gen(function*() { + * const span = yield* Effect.makeSpan("parent-span") + * const childTask = Effect.succeed("child operation") + * yield* Effect.withParentSpan(childTask, span) + * return "completed" + * }) + * Effect.runSync(program) // => "completed" + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = _internal_effect_js__rspack_import_1/* .withParentSpan */.hq; +// ----------------------------------------------------------------------------- +// Batching +// ----------------------------------------------------------------------------- +/** + * Executes a request using the provided resolver. + * + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Request, RequestResolver } from "effect" + * const output: Array = [] + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: number + * } + * const GetUser = Request.tagged("GetUser") + * + * const resolver = RequestResolver.make( + * Effect.fnUntraced(function*(entries) { + * for (const entry of entries) { + * yield* Request.complete(entry, Exit.succeed(`user-${entry.request.id}`)) + * } + * }) + * ) + * + * const program = Effect.gen(function*() { + * const name = yield* Effect.request(GetUser({ id: 1 }), resolver) + * yield* Effect.sync(() => { output.push(name) }) + * }) + * + * await Effect.runPromise(program) + * output // => ["user-1"] + * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category running + * @since 2.0.0 + */ +const request = _internal_request_js__rspack_import_5/* .request */.E; +/** + * Registers a request with a resolver and delivers the exit value via `onExit`. + * + * **When to use** + * + * Use when you already have a `Context` and need to enqueue a request outside + * an `Effect` while receiving completion through `onExit`. + * + * **Details** + * + * It returns a canceler that removes the pending request entry. + * + * @see {@link request} for the `Effect`-returning API used for normal request execution + * + * @category unsafe + * @since 4.0.0 + */ +const requestUnsafe = _internal_request_js__rspack_import_5/* .requestUnsafe */.m; +// ----------------------------------------------------------------------------- +// Supervision & Fiber's +// ----------------------------------------------------------------------------- +/** + * 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 other higher-level methods, such as `raceWith`, + * `zipPar`, and so forth. + * + * 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" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkChild = _internal_effect_js__rspack_import_1/* .forkChild */.zhn; +/** + * Forks the effect in the specified scope. The fiber will be interrupted + * when the scope is closed. + * + * **Example** (Forking into a supplied scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const task = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const scope = yield* Effect.scope + * const fiber = yield* Effect.forkIn(task, scope) + * // Fiber will be interrupted when scope closes + * return "done" + * }) + * ) + * + * await Effect.runPromise(program) // => "done" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkIn = _internal_effect_js__rspack_import_1/* .forkIn */.ar0; +/** + * Forks the fiber in a `Scope`, interrupting it when the scope is closed. + * + * **Example** (Forking into the current scope) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const backgroundTask = Effect.never + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* backgroundTask.pipe(Effect.forkScoped) + * + * // Fiber will be interrupted when scope closes + * return "scope completed" + * }) + * ) + * + * await Effect.runPromise(program) // => "scope completed" + * ``` + * + * @category forking + * @since 2.0.0 + */ +const forkScoped = _internal_effect_js__rspack_import_1/* .forkScoped */.x6Z; +/** + * Forks the effect into a new fiber attached to the global scope. Because the + * new fiber is attached to the global scope, when the fiber executing the + * returned effect terminates, the forked fiber will continue running. + * + * **Example** (Forking a detached fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const daemonTask = Effect.succeed("daemon result") + * + * const program = Effect.gen(function*() { + * const fiber = yield* daemonTask.pipe(Effect.forkDetach) + * return yield* Fiber.join(fiber) + * }) + * + * await Effect.runPromise(program) // => "daemon result" + * ``` + * + * @category forking + * @since 4.0.0 + */ +const forkDetach = _internal_effect_js__rspack_import_1/* .forkDetach */.yxg; +/** + * Waits for all child fibers forked by this effect to complete before this + * effect completes. + * + * **When to use** + * + * Use to let an effect start child work concurrently while still delaying its + * own completion until that child work is done. + * + * **Gotchas** + * + * Child fibers that already exist before the wrapped effect starts are not + * awaited. + * + * @see {@link forkChild} for forking child fibers that are awaited by this operator + * @see {@link forkDetach} for forking fibers outside the child scope + * @see {@link forkIn} for forking into an explicit scope + * @see {@link forkScoped} for forking fibers tied to the current scope + * + * @category sequencing + * @since 2.0.0 + */ +const awaitAllChildren = _internal_effect_js__rspack_import_1/* .awaitAllChildren */.PCg; +/** + * Accesses the fiber currently executing the effect. + * + * **Example** (Accessing the current fiber) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.fiber + * yield* Effect.sync(() => { output.push(typeof fiber.id) }) + * }) + * + * Effect.runSync(program) + * output // => ["number"] + * ``` + * + * @category accessors + * @since 4.0.0 + */ +const fiber = _internal_effect_js__rspack_import_1/* .fiber */.pEE; +/** + * Accesses the current fiber id executing the effect. + * + * **Example** (Accessing the current fiber id) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.fiberId.pipe(Effect.map((id) => typeof id)) + * Effect.runSync(program) // => "number" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const fiberId = _internal_effect_js__rspack_import_1/* .fiberId */.ABT; +/** + * Runs an effect in the background, returning a fiber that can + * be observed or interrupted. + * + * **When to use** + * + * Use when you need to start an effect in the background and receive a fiber. + * + * **Example** (Running an effect in the background) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * const output: Array = [] + * + * // ┌─── Effect + * // ▼ + * const program = Effect.sync(() => { output.push("running...") }).pipe(Effect.as("done")) + * + * // ┌─── RuntimeFiber + * // ▼ + * const fiber = Effect.runFork(program) + * + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["running...", "done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runFork = _internal_effect_js__rspack_import_1/* .runFork */.MY7; +/** + * Runs an effect in the background with the provided services. + * + * **When to use** + * + * Use when an effect still requires services, you already have a `Context`, and + * you want a background fiber. + * + * **Example** (Running with services in the background) + * + * ```ts import.meta.vitest + * import { Context, Effect, Fiber } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => void + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => void output.push(message) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * logger.log("Hello from service!") + * return "done" + * }) + * + * const fiber = Effect.runForkWith(services)(program) + * void output.push(await Effect.runPromise(Fiber.join(fiber))) + * output // => ["Hello from service!", "done"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runForkWith = _internal_effect_js__rspack_import_1/* .runForkWith */.eJC; +/** + * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor. + * + * **When to use** + * + * Use when embedding an effect into callback-style code with explicit services + * and a synchronous interruptor. + * + * **Details** + * + * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id. + * + * **Example** (Running with services and a callback) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * const output: Array = [] + * + * interface Logger { + * log: (message: string) => Effect.Effect + * } + * + * const Logger = Context.Service("Logger") + * + * const services = Context.make(Logger, { + * log: (message) => Effect.sync(() => { output.push(message) }) + * }) + * + * const program = Effect.gen(function*() { + * const logger = yield* Logger + * yield* logger.log("Started") + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallbackWith(services)(program, { + * onExit: (exit) => { + * void output.push(exit._tag) + * resolve() + * } + * }) + * }) + * output // => ["Started", "Success"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runCallbackWith = _internal_effect_js__rspack_import_1/* .runCallbackWith */.lSz; +/** + * Runs an effect asynchronously, registering `onExit` as a fiber observer and + * returning an interruptor. + * + * **Details** + * + * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor + * id. + * + * **Example** (Running with a callback) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.sync(() => { output.push("working") }) + * return "done" + * }) + * + * await new Promise((resolve) => { + * Effect.runCallback(program, { + * onExit: (exit) => { + * Effect.runSync( + * Exit.match(exit, { + * onFailure: () => Effect.sync(() => { output.push("failed") }), + * onSuccess: (value) => Effect.sync(() => { output.push(`success: ${value}`) }) + * }) + * ) + * resolve() + * } + * }) + * }) + * + * output // => ["working", "success: done"] + * ``` + * + * @category running + * @since 2.0.0 + */ +const runCallback = _internal_effect_js__rspack_import_1/* .runCallback */.bPG; +/** + * 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. + * @category running + * @since 2.0.0 + */ +const runPromise = _internal_effect_js__rspack_import_1/* .runPromise */.pR5; +/** + * Executes an effect as a Promise with the provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that rejects on + * effect failure. + * + * **Example** (Running with services as a promise) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface Config { + * apiUrl: string + * } + * + * const Config = Context.Service("Config") + * + * const context = Context.make(Config, { + * apiUrl: "https://api.example.com" + * }) + * + * const program = Effect.gen(function*() { + * const config = yield* Config + * return `Connecting to ${config.apiUrl}` + * }) + * + * await Effect.runPromiseWith(context)(program) // => "Connecting to https://api.example.com" + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseWith = _internal_effect_js__rspack_import_1/* .runPromiseWith */.v2Q; +/** + * Runs an effect and returns a `Promise` that resolves to an `Exit`, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use when you need to determine if an effect succeeded + * or failed, including any defects, and you want to work with a `Promise`. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * **Example** (Observing promise results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * // Execute a successful effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * // Execute a failing effect and get the Exit result as a Promise + * await Effect.runPromiseExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * @see {@link runPromise} for a version that rejects on failure. + * + * @category running + * @since 2.0.0 + */ +const runPromiseExit = _internal_effect_js__rspack_import_1/* .runPromiseExit */.NpQ; +/** + * Runs an effect and returns a Promise of Exit with provided services. + * + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that preserves + * success and failure as an `Exit`. + * + * **Example** (Running with services as an Exit promise) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * interface Database { + * query: (sql: string) => string + * } + * + * const Database = Context.Service("Database") + * + * const services = Context.make(Database, { + * query: (sql) => `Result for: ${sql}` + * }) + * + * const program = Effect.gen(function*() { + * const db = yield* Database + * return db.query("SELECT * FROM users") + * }) + * + * const exit = await Effect.runPromiseExitWith(services)(program) + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } + * output // => ["Success: Result for: SELECT * FROM users"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runPromiseExitWith = _internal_effect_js__rspack_import_1/* .runPromiseExitWith */.jqV; +/** + * 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, is interrupted, or performs asynchronous work, + * `runSync` throws a `FiberFailure` instead of returning a value. 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. + * @category running + * @since 2.0.0 + */ +const runSync = _internal_effect_js__rspack_import_1/* .runSync */.HZF; +/** + * Executes an effect synchronously with provided services. + * + * **When to use** + * + * Use when you already have a `Context`, the effect is known to complete + * synchronously, and failures should throw. + * + * **Example** (Running synchronously with services) + * + * ```ts import.meta.vitest + * import { Context, Effect } from "effect" + * + * interface MathService { + * add: (a: number, b: number) => number + * } + * + * const MathService = Context.Service("MathService") + * + * const context = Context.make(MathService, { + * add: (a, b) => a + b + * }) + * + * const program = Effect.gen(function*() { + * const math = yield* MathService + * return math.add(2, 3) + * }) + * + * const result = Effect.runSyncWith(context)(program) + * result // => 5 + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncWith = _internal_effect_js__rspack_import_1/* .runSyncWith */.lE; +/** + * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which + * represents the outcome (success or failure) of the effect. + * + * **When to use** + * + * Use to find out whether an effect succeeded or failed, + * including any defects, without dealing with asynchronous operations. + * + * **Details** + * + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * If the effect contains asynchronous operations, `runSyncExit` will + * return an `Failure` with a `Die` cause, indicating that the effect cannot be + * resolved synchronously. + * + * **Example** (Observing synchronous results as Exit) + * + * ```ts import.meta.vitest + * import { Effect, Exit } from "effect" + * + * Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1) + * + * Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error") + * ``` + * + * **Example** (Capturing async work as a Die cause) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Exit } from "effect" + * + * const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))) + * const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some( + * (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect) + * ) + * + * isAsyncDie // => true + * ``` + * + * @see {@link runSync} for a version that throws on failure. + * + * @category running + * @since 2.0.0 + */ +const runSyncExit = _internal_effect_js__rspack_import_1/* .runSyncExit */.lKS; +/** + * Runs an effect synchronously with provided services, returning an Exit result safely. + * + * **When to use** + * + * Use when you already have a `Context` and need a synchronous `Exit` instead of + * throwing on failure. + * + * **Example** (Running synchronously with services as Exit) + * + * ```ts import.meta.vitest + * import { Context, Effect, Exit } from "effect" + * const output: Array = [] + * + * // Define a logger service + * const Logger = Context.Service<{ + * log: (msg: string) => void + * }>("Logger") + * + * const program = Effect.gen(function*() { + * const logger = yield* Effect.service(Logger) + * logger.log("Computing result...") + * return 42 + * }) + * + * // Prepare context + * const context = Context.make(Logger, { + * log: (msg) => void output.push(`[LOG] ${msg}`) + * }) + * + * const exit = Effect.runSyncExitWith(context)(program) + * + * if (Exit.isSuccess(exit)) { + * void output.push(`Success: ${exit.value}`) + * } else { + * void output.push(`Failure: ${exit.cause}`) + * } + * output // => ["[LOG] Computing result...", "Success: 42"] + * ``` + * + * @category running + * @since 4.0.0 + */ +const runSyncExitWith = _internal_effect_js__rspack_import_1/* .runSyncExitWith */.rfH; +/** + * 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. 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" + * ``` + * + * @category constructors + * @since 3.12.0 + */ +const fnUntraced = _internal_effect_js__rspack_import_1/* .fnUntraced */.D9k; +/** + * Creates a reusable traced function from an Effect body. + * + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, and you want + * tracing spans or stack-frame capture. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the + * generator body instead of allocating a fresh generator closure around the + * arguments on every call. Call `Effect.fn(body, ...)` for a generic + * stack-frame boundary without creating a span. Call + * `Effect.fn("operationName", options?)(body, ...)` when that boundary should + * have a readable operation name and the returned `Effect` should create a + * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata + * such as attributes, links, parent or root selection, kind, sampling, and log + * level. Additional arguments after the generator body act like `pipe` + * transforms: each transform receives the previous result and the original + * function arguments. When those transforms return an `Effect`, the returned + * effect includes stack-frame metadata and, for the named form, a tracing span. + * Generator bodies may declare a `this` parameter; pass `{ self }` before the + * body to bind `this` when the function is created. + * + * **Example** (Defining traced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(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.fn("formatLength")( + * 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** (Binding this) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * class Counter { + * count = 0 + * + * increment = Effect.fn("Counter.increment")( + * { self: this }, + * function*(this: Counter, by: number) { + * this.count += by + * return yield* Effect.succeed(this.count) + * } + * ) + * } + * + * const counter = new Counter() + * + * // ┌─── Effect.Effect + * // ▼ + * const program = counter.increment(1) + * Effect.runSync(program) // => 1 + * ``` + * + * **Example** (Annotating a traced non-parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => 5 + * ``` + * + * **Example** (Annotating a traced parametric function) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const f = Effect.fn("succeed")(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * Effect.runSync(program) // => "hello" + * ``` + * + * @category constructors + * @since 3.11.0 + */ +const fn = _internal_effect_js__rspack_import_1.fn; +// ======================================================================== +// Clock +// ======================================================================== +/** + * Retrieves the `Clock` service from the context and provides it to the + * specified effectful function. + * + * **Example** (Accessing the Clock service) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const program = Effect.clockWith((clock) => + * clock.currentTimeMillis.pipe( + * Effect.map(() => "Clock is available") + * ) + * ) + * + * Effect.runSync(program) // => "Clock is available" + * ``` + * + * @category accessors + * @since 2.0.0 + */ +const clockWith = _internal_effect_js__rspack_import_1/* .clockWith */.RKA; +// ======================================================================== +// Logging +// ======================================================================== +/** + * Creates a logger function that logs at the specified level. + * + * **Details** + * + * If no level is provided, the logger uses the fiber's current log level and + * extracts any `Cause` values from the message list. + * + * **Example** (Logging at a dynamic level) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const logWarn = Effect.logWithLevel("Warn") + * + * const program = Effect.gen(function*() { + * yield* logWarn("Cache miss") + * }) + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Warn: Cache miss"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWithLevel = _internal_effect_js__rspack_import_1/* .logWithLevel */.lIX; +/** + * Logs one or more messages using the default log level. + * + * **Example** (Logging at the default level) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const result = 2 + 2 + * yield* Effect.log("Result:", result) + * return result + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * void output.push(Effect.runSync(runnable)) + * output // => ["Info: Result: 4", 4] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const log = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel())); +/** + * Logs one or more messages at the FATAL level. + * + * **Example** (Logging fatal messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logFatal("Critical system failure") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = Effect.provide(program, Logger.layer([logger])) + * Effect.runSync(runnable) + * output // => ["Fatal: Critical system failure"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logFatal = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Fatal"))); +/** + * Logs one or more messages at the WARNING level. + * + * **Example** (Logging warnings) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logWarning("API rate limit approaching") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Warn: API rate limit approaching"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logWarning = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Warn"))); +/** + * Logs one or more messages at the ERROR level. + * + * **Example** (Logging errors) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logError("Database connection failed") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Error: Database connection failed"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logError = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Error"))); +/** + * Logs one or more messages at the INFO level. + * + * **Example** (Logging information) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logInfo("Application starting up") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["Info: Application starting up"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logInfo = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Info"))); +/** + * Logs one or more messages at the DEBUG level. + * + * **Example** (Logging debug messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logDebug("Debug mode enabled") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Debug"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Debug: Debug mode enabled"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logDebug = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Debug"))); +/** + * Logs one or more messages at the TRACE level. + * + * **Example** (Logging trace messages) + * + * ```ts import.meta.vitest + * import { Effect, Logger, References } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.logTrace("Entering function processData") + * }) + * + * const logger = Logger.make(({ logLevel, message }) => { + * void output.push(`${logLevel}: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * }) + * const runnable = program.pipe( + * Effect.provideService(References.MinimumLogLevel, "Trace"), + * Effect.provide(Logger.layer([logger])) + * ) + * Effect.runSync(runnable) + * output // => ["Trace: Entering function processData"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const logTrace = /*#__PURE__*/(/* unused pure expression or super */ null && (internal.logWithLevel("Trace"))); +/** + * Adds a logger to the set of loggers which will output logs for this effect. + * + * **Example** (Adding a logger to an effect) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * // Create a custom logger that logs to the console + * const customLogger = Logger.make(({ message }) => + * void output.push(`[CUSTOM]: ${Array.isArray(message) ? message.map(String).join(" ") : String(message)}`) + * ) + * + * const program = Effect.gen(function*() { + * yield* Effect.log("This will go to both default and custom logger") + * return "completed" + * }) + * + * // Add the custom logger to the effect + * const programWithLogger = Effect.withLogger(program, customLogger) + * + * Effect.runSync(Effect.provide(programWithLogger, Logger.layer([]))) + * output // => ["[CUSTOM]: This will go to both default and custom logger"] + * ``` + * + * @category logging + * @since 4.0.0 + */ +const withLogger = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, logger) => internal.updateService(effect, internal.CurrentLoggers, loggers => new Set([...loggers, logger]))))); +/** + * Adds an annotation to each log line in this effect. + * + * **Example** (Adding log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * yield* Effect.log("Starting operation") + * }) + * + * // Add annotations to all log messages + * const annotatedProgram = Effect.annotateLogs(program, { + * userId: "user123", + * operation: "data-processing" + * }) + * + * // Also supports single key-value annotations + * const singleAnnotated = Effect.annotateLogs(program, "requestId", "req-456") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * const run = (effect: Effect.Effect) => + * Effect.runSync(Effect.provide(effect, Logger.layer([logger]))) + * run(annotatedProgram) + * run(singleAnnotated) + * output // => ["Starting operation", "Starting operation"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const annotateLogs = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (effect, ...args) => internal.updateService(effect, CurrentLogAnnotations, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + InternalRecord.assignProperty(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})))); +/** + * Adds log annotations to the current scope. + * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * + * This differs from `annotateLogs`, which only annotates a specific effect. + * `annotateLogsScoped` updates annotations for the entire current `Scope` and + * restores the previous annotations when the scope closes. + * + * **Example** (Adding scoped log annotations) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * yield* Effect.log("before") + * yield* Effect.annotateLogsScoped({ requestId: "req-123" }) + * yield* Effect.log("inside scope") + * }) + * ) + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * Effect.runSync(Effect.provide(program, Logger.layer([logger]))) + * output // => ["before", "inside scope"] + * ``` + * + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 + */ +const annotateLogsScoped = _internal_effect_js__rspack_import_1/* .annotateLogsScoped */.gsV; +/** + * Adds a span to each log line in this effect. + * + * **Example** (Adding a log span) + * + * ```ts import.meta.vitest + * import { Effect, Logger } from "effect" + * const output: Array = [] + * + * const databaseOperation = Effect.gen(function*() { + * yield* Effect.log("Connecting to database") + * yield* Effect.log("Executing query") + * yield* Effect.log("Processing results") + * return "data" + * }) + * + * const httpRequest = Effect.gen(function*() { + * yield* Effect.log("Making HTTP request") + * const data = yield* Effect.withLogSpan(databaseOperation, "db-operation") + * yield* Effect.log("Sending response") + * return data + * }) + * + * const program = Effect.withLogSpan(httpRequest, "http-handler") + * + * const logger = Logger.make(({ message }) => + * void output.push(Array.isArray(message) ? message.join(" ") : String(message)) + * ) + * void output.push(Effect.runSync(Effect.provide(program, Logger.layer([logger])))) + * output // => ["Making HTTP request", "Connecting to database", "Executing query", "Processing results", "Sending response", "data"] + * ``` + * + * @category logging + * @since 2.0.0 + */ +const withLogSpan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (effect, label) => internal.flatMap(internal.currentTimeMillis, now => internal.updateService(effect, CurrentLogSpans, spans => { + const span = [label, now]; + return [span, ...spans]; +}))))); +// ----------------------------------------------------------------------------- +// Metrics +// ----------------------------------------------------------------------------- +/** + * Updates the `Metric` every time the `Effect` is executed. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Exit` value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Incrementing a metric for each execution) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const counter = Metric.counter("effect_executions", { + * description: "Counts effect executions" + * }).pipe(Metric.withConstantInput(1)) + * + * const program = Effect.succeed("Hello").pipe( + * Effect.track(counter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(counter)).count // => 1 + * ``` + * + * **Example** (Mapping exits before updating a metric) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Metric } from "effect" + * + * // Track different exit types with custom mapping + * const exitTracker = Metric.frequency("exit_types", { + * description: "Tracks success/failure/defect counts" + * }) + * + * const mapExitToString = (exit: Exit.Exit) => { + * if (Exit.isSuccess(exit)) return "success" + * if (Exit.isFailure(exit)) return "failure" + * return "defect" + * } + * + * const effect = Effect.succeed("result").pipe( + * Effect.track(exitTracker, mapExitToString) + * ) + * Effect.runSync(effect) + * Effect.runSync(Metric.value(exitTracker)).occurrences.get("success") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const track = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => onExit(self, exit => { + const input = f === undefined ? exit : internalCall(() => f(exit)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` succeeds with + * a value. + * + * **Details** + * + * Also accepts an optional function which can be used to map the success value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting successful results) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const successCounter = Metric.counter("successes").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.succeed(42).pipe( + * Effect.trackSuccesses(successCounter) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(successCounter)).count // => 1 + * ``` + * + * **Example** (Mapping successes before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track successful request sizes + * const requestSizeGauge = Metric.gauge("request_size_bytes") + * + * const program = Effect.succeed("Hello World!").pipe( + * Effect.trackSuccesses(requestSizeGauge, (value: string) => value.length) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(requestSizeGauge)).value // => 12 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackSuccesses = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tap(self, value => { + const input = f === undefined ? value : f(value); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **expected** error. + * + * **Details** + * + * Also accepts an optional function which can be used to map the error value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting expected failures) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const errorCounter = Metric.counter("errors").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.fail("Network timeout").pipe( + * Effect.trackErrors(errorCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorCounter)).count // => 1 + * ``` + * + * **Example** (Mapping errors before tracking) + * + * ```ts import.meta.vitest + * import { Data, Effect, Metric } from "effect" + * + * class ConnectionFailedError extends Data.TaggedError("ConnectionFailedError")<{}> {} + * + * // Track error types using frequency metric + * const errorTypeFrequency = Metric.frequency("error_types") + * + * const program = Effect.fail(new ConnectionFailedError()).pipe( + * Effect.trackErrors(errorTypeFrequency, (error: ConnectionFailedError) => error._tag) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(errorTypeFrequency)).occurrences.get("ConnectionFailedError") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackErrors = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapError(self, error => { + const input = f === undefined ? error : internalCall(() => f(error)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` every time the wrapped `Effect` fails with an + * **unexpected** error (i.e. a defect). + * + * **Details** + * + * Also accepts an optional function which can be used to map the defect value + * of the `Effect` into a valid `Input` for the `Metric`. + * + * **Example** (Counting defects) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const defectCounter = Metric.counter("defects").pipe( + * Metric.withConstantInput(1) + * ) + * + * const program = Effect.die("Critical system failure").pipe( + * Effect.trackDefects(defectCounter) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectCounter)).count // => 1 + * ``` + * + * **Example** (Mapping defects before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track defect types using frequency metric + * const defectTypeFrequency = Metric.frequency("defect_types") + * + * const program = Effect.die(new Error("Null pointer exception")).pipe( + * Effect.trackDefects(defectTypeFrequency, (defect: unknown) => { + * if (defect instanceof Error) return defect.constructor.name + * return typeof defect + * }) + * ) + * + * Effect.runSyncExit(program) + * Effect.runSync(Metric.value(defectTypeFrequency)).occurrences.get("Error") // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDefects = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => tapDefect(self, defect => { + const input = f === undefined ? defect : internalCall(() => f(defect)); + return Metric.update(metric, input); +})))); +/** + * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) + * that the wrapped `Effect` took to complete. + * + * **Details** + * + * Also accepts an optional function which can be used to map the `Duration` + * that the wrapped `Effect` took to complete into a valid `Input` for the + * `Metric`. + * + * **Example** (Recording execution duration) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * const executionTimer = Metric.timer("execution_time") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(executionTimer) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(executionTimer)).count // => 1 + * ``` + * + * **Example** (Mapping duration before tracking) + * + * ```ts import.meta.vitest + * import { Effect, Metric } from "effect" + * + * // Track execution time in milliseconds using custom mapping + * const durationGauge = Metric.gauge("execution_millis") + * + * const program = Effect.succeed("done").pipe( + * Effect.trackDuration(durationGauge, () => 1) + * ) + * + * Effect.runSync(program) + * Effect.runSync(Metric.value(durationGauge)).value // => 1 + * ``` + * + * @category metrics + * @since 4.0.0 + */ +const trackDuration = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(args => isEffect(args[0]), (self, metric, f) => clockWith(clock => { + const startTime = clock.monotonicTimeNanosUnsafe(); + return onExit(self, () => { + const endTime = clock.monotonicTimeNanosUnsafe(); + const duration = Duration.subtract(Duration.fromInputUnsafe(endTime), Duration.fromInputUnsafe(startTime)); + const input = f === undefined ? duration : internalCall(() => f(duration)); + return Metric.update(metric, input); + }); +})))); +// ----------------------------------------------------------------------------- +// Transactions +// ----------------------------------------------------------------------------- +/** + * Service that holds the current transaction state. + * + * **Details** + * + * It includes a journal that stores non-committed changes to `TxRef` values and + * a retry flag that records whether the transaction should be retried. + * + * **Example** (Building transactions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Transaction class for software transactional memory operations + * const txEffect = Effect.gen(function*() { + * const tx = yield* Effect.Transaction + * // Use transaction for coordinated state changes + * return "Transaction complete" + * }) + * + * const runnable = Effect.provideService(txEffect, Effect.Transaction, { + * retry: false, + * journal: new Map() + * }) + * Effect.runSync(runnable) // => "Transaction complete" + * ``` + * + * @category services + * @since 4.0.0 + */ +class Transaction extends /*#__PURE__*/(/* unused pure expression or super */ null && (Context.Service()("effect/Effect/Transaction"))) {} +/** + * Defines a transaction boundary. Transactions are "all or nothing" with respect to changes + * made to transactional values (i.e. TxRef) that occur within the transaction body. + * + * **Details** + * + * If called inside an active transaction, `tx` composes with the current transaction and reuses + * its journal and retry state instead of creating a nested boundary. + * + * Effect transactions are optimistic with retry. A transaction is retried when + * its body explicitly calls `Effect.txRetry` and any accessed transactional + * value changes, or when any accessed transactional value changes because a + * different transaction commits before the current one. + * + * The outermost `tx` call creates the transaction boundary and commits or rolls back the full + * composed transaction. + * + * **Example** (Running a transaction) + * + * ```ts import.meta.vitest + * import { Effect, TxRef } from "effect" + * const output: Array = [] + * + * const program = Effect.gen(function*() { + * const ref1 = yield* TxRef.make(0) + * const ref2 = yield* TxRef.make(0) + * + * // Nested tx calls compose into the same transaction + * yield* Effect.tx(Effect.gen(function*() { + * yield* TxRef.set(ref1, 10) + * yield* Effect.tx(TxRef.set(ref2, 20)) + * const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2)) + * void output.push(`Transaction sum: ${sum}`) + * })) + * + * void output.push(`Final ref1: ${yield* TxRef.get(ref1)}`) + * void output.push(`Final ref2: ${yield* TxRef.get(ref2)}`) + * }) + * + * Effect.runSync(program) + * output // => ["Transaction sum: 30", "Final ref1: 10", "Final ref2: 20"] + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const tx = effect => withFiber(fiber => { + let state = Context.getOrUndefined(fiber.context, Transaction); + if (state) { + return effect; + } + // Create transaction state only at the outermost boundary + state = { + journal: new Map(), + retry: false + }; + let result; + return uninterruptibleMask(restore => flatMap(whileLoop({ + while: () => !result, + body: constant(restore(effect).pipe(provideService(Transaction, state), tapCause(() => { + if (!state.retry) return void_; + return restore(awaitPendingTransaction(state)); + }), exit)), + step(exit) { + if (state.retry || !isTransactionConsistent(state)) { + return clearTransaction(state); + } + if (Exit.isSuccess(exit)) { + commitTransaction(fiber, state); + } else { + clearTransaction(state); + } + result = exit; + } + }), () => result)); +}); +const isTransactionConsistent = state => { + for (const [ref, { + version + }] of state.journal) { + if (ref.version !== version) { + return false; + } + } + return true; +}; +const awaitPendingTransaction = state => suspend(() => { + const key = {}; + const refs = Array.from(state.journal.keys()); + const clearPending = () => { + for (const clear of refs) { + clear.pending.delete(key); + } + }; + return callback(resume => { + const onCall = () => { + clearPending(); + resume(void_); + }; + for (const ref of refs) { + ref.pending.set(key, onCall); + } + return sync(clearPending); + }); +}); +function commitTransaction(fiber, state) { + for (const [ref, { + value + }] of state.journal) { + if (value !== ref.value) { + ref.version = ref.version + 1; + ref.value = value; + } + for (const pending of ref.pending.values()) { + fiber.currentDispatcher.scheduleTask(pending, 0); + } + ref.pending.clear(); + } +} +function clearTransaction(state) { + state.retry = false; + state.journal.clear(); +} +/** + * Retries the current transaction by signaling that it must be retried. + * + * **Details** + * + * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. + * + * **Example** (Retrying transactions) + * + * ```ts import.meta.vitest + * import { Deferred, Effect, TxRef } from "effect" + * + * const program = Effect.gen(function*() { + * const ref = yield* TxRef.make(0) + * const update = yield* Deferred.make() + * + * yield* Effect.forkChild( + * Deferred.await(update).pipe(Effect.andThen(Effect.tx(TxRef.set(ref, 1)))) + * ) + * + * return yield* Effect.tx(Effect.gen(function*() { + * const value = yield* TxRef.get(ref) + * if (value === 0) { + * yield* Deferred.succeed(update, undefined) + * return yield* Effect.txRetry + * } + * return value + * })) + * }) + * + * await Effect.runPromise(program) // => 1 + * ``` + * + * @category transactions + * @since 4.0.0 + */ +const txRetry = /*#__PURE__*/(/* unused pure expression or super */ null && (flatMap(Transaction, state => { + state.retry = true; + return interrupt; +}))); +/** + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const uppercase = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(null, input.toUpperCase())) + * + * const effectfulUppercase = Effect.effectify(uppercase) + * const program = effectfulUppercase("hello") + * + * await Effect.runPromise(program) // => "HELLO" + * ``` + * + * **Example** (Mapping callback errors to typed failures) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const fail = ( + * input: string, + * callback: (error: Error | null, value?: string) => void + * ) => queueMicrotask(() => callback(new Error("unavailable"))) + * + * const effectfulFail = Effect.effectify( + * fail, + * (error, args) => new Error(`Failed to process ${args[0]}: ${error.message}`) + * ) + * + * const program = Effect.flip(effectfulFail("hello")) + * + * const error = await Effect.runPromise(program) + * error.message // => "Failed to process hello: unavailable" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const effectify = (fn, onError, onSyncError) => (...args) => callback(resume => { + try { + fn(...args, (err, result) => { + if (err) { + resume(fail(onError ? onError(err, args) : err)); + } else { + resume(succeed(result)); + } + }); + } catch (err) { + resume(onSyncError ? fail(onSyncError(err, args)) : die(err)); + } +}); +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that an effect's success type extends a given type `A`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the success type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Effect.satisfiesSuccessType() + * + * // This works - Effect<42, never, never> extends Effect + * const validEffect = satisfiesNumber(Effect.succeed(42)) + * Effect.runSync(validEffect) // => 42 + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesNumber(Effect.succeed("string")) + * // ^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'number' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => effect => effect; +/** + * Ensures that an effect's error type extends a given type `E`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the error type) + * + * ```ts import.meta.vitest + * import { Data, Effect } from "effect" + * + * class ValidationError extends Data.TaggedError("ValidationError")<{}> {} + * + * // Define a constraint that the error type must be a ValidationError + * const satisfiesError = Effect.satisfiesErrorType() + * + * // This works - Effect extends the constrained type + * const validEffect = satisfiesError(Effect.fail(new ValidationError())) + * Effect.runSync(Effect.flip(validEffect))._tag // => "ValidationError" + * + * // This would cause a TypeScript compilation error: + * // const invalidEffect = satisfiesError(Effect.fail("string error")) + * // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * // Type 'string' is not assignable to type 'ValidationError' + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => effect => effect; +/** + * Ensures that an effect's requirements type extends a given type `R`. + * + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the services type) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // Define a constraint that requires a string as the requirements type + * const satisfiesStringServices = Effect.satisfiesServicesType() + * + * // This works - effect requires string + * const validEffect: Effect.Effect = Effect.succeed(42) + * const constrainedEffect = satisfiesStringServices(validEffect) + * + * // This would cause a TypeScript compilation error if uncommented: + * // const invalidEffect: Effect.Effect = Effect.succeed(42) + * // const constrainedInvalid = satisfiesStringServices(invalidEffect) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => effect => effect; +/** + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. + * + * **Details** + * + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. + * + * **Example** (Mapping already completed effects) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the mapping is applied immediately + * const resolved = Effect.succeed(5) + * const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly + * + * // For pending effects, behaves like regular map + * const pending = Effect.delay(Effect.succeed(5), 0) + * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map + * + * await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapEager = _internal_effect_js__rspack_import_1/* .mapEager */.jkJ; +/** + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. + * + * **Example** (Mapping errors eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the error mapping is applied immediately + * const failed = Effect.fail("original error") + * const mapped = Effect.mapErrorEager(failed, (err: string) => `mapped: ${err}`) // Applied eagerly + * + * // For pending effects, behaves like regular mapError + * const pending = Effect.delay(Effect.fail("error"), 0) + * const mappedPending = Effect.mapErrorEager( + * pending, + * (err: string) => `mapped: ${err}` + * ) // Uses regular mapError + * + * void output.push(await Effect.runPromise(Effect.all([ + * Effect.flip(mapped), + * Effect.flip(mappedPending) + * ]))) + * output // => [['mapped: original error', 'mapped: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const mapErrorEager = _internal_effect_js__rspack_import_1/* .mapErrorEager */.Z9x; +/** + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. + * + * **Details** + * + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. + * + * **Example** (Mapping both channels eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved effects, the appropriate mapping is applied immediately + * const success = Effect.succeed(5) + * const mapped = Effect.mapBothEager(success, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onSuccess applied eagerly + * + * const failure = Effect.fail("error") + * const mappedError = Effect.mapBothEager(failure, { + * onFailure: (err: string) => `Failed: ${err}`, + * onSuccess: (n: number) => n * 2 + * }) // onFailure applied eagerly + * + * void output.push(Effect.runSync(mapped)) + * void output.push(Effect.runSync(Effect.flip(mappedError))) + * output // => [10, "Failed: error"] + * ``` + * + * @category mapping + * @since 4.0.0 + */ +const mapBothEager = _internal_effect_js__rspack_import_1/* .mapBothEager */.q7Y; +/** + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. + * + * **Details** + * + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. + * + * **Example** (Flat mapping eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * // For resolved effects, the flatMap is applied immediately + * const resolved = Effect.succeed(5) + * const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly + * + * // For pending effects, behaves like regular flatMap + * const pending = Effect.delay(Effect.succeed(5), 0) + * const flatMappedPending = Effect.flatMapEager( + * pending, + * (n) => Effect.succeed(n * 2) + * ) // Uses regular flatMap + * + * await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapEager = _internal_effect_js__rspack_import_1/* .flatMapEager */.Ab9; +/** + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** + * + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. + * + * **Details** + * + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. + * + * **Example** (Catching failures eagerly when possible) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * const output: Array = [] + * + * // For resolved failure effects, the catch function is applied immediately + * const failed = Effect.fail("original error") + * const recovered = Effect.catchEager( + * failed, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Applied eagerly + * + * // For success effects, returns success as-is + * const success = Effect.succeed(42) + * const unchanged = Effect.catchEager( + * success, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Returns success as-is + * + * // For pending effects, behaves like regular catch + * const pending = Effect.delay(Effect.fail("error"), 0) + * const recoveredPending = Effect.catchEager( + * pending, + * (err: string) => Effect.succeed(`recovered from: ${err}`) + * ) // Uses regular catch + * + * void output.push(await Effect.runPromise(Effect.all([ + * recovered, + * unchanged, + * recoveredPending + * ]))) + * output // => [['recovered from: original error', 42, 'recovered from: error']] + * ``` + * + * @category error handling + * @since 4.0.0 + */ +const catchEager = _internal_effect_js__rspack_import_1/* .catchEager */.UVN; +/** + * Creates untraced function effects with eager evaluation optimization. + * + * **Details** + * + * Executes generator functions eagerly when all yielded effects are synchronous, + * stopping at the first async effect and deferring to normal execution. + * + * **Example** (Defining eager untraced effect functions) + * + * ```ts import.meta.vitest + * import { Effect } from "effect" + * + * const computation = Effect.fnUntracedEager(function*() { + * yield* Effect.succeed(1) + * yield* Effect.succeed(2) + * return "computed eagerly" + * }) + * + * const effect = computation() // Executed immediately if all effects are sync + * Effect.runSync(effect) // => "computed eagerly" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fnUntracedEager = _internal_effect_js__rspack_import_1/* .fnUntracedEager */.vCS; +//# sourceMappingURL=Effect.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Bqz: flatten, + DYE: suspend, + F_Q: die, + HZF: runSync, + JkU: gen, + L5P: retry, + MY7: runFork, + MfU: catch_, + Mim: tap, + NpQ: runPromiseExit, + OH5: sync, + PpN: provideContext, + Q56: acquireRelease, + QgK: orDie, + R6R: withFiber, + SvU: try_, + bPG: runCallback, + dsN: abortSignal, + eJC: runForkWith, + fJG: fail, + hgn: andThen, + jGc: acquireUseRelease, + jqV: runPromiseExitWith, + lE: runSyncWith, + lKS: runSyncExit, + lSz: runCallbackWith, + pR5: runPromise, + qIB: flatMap, + rIH: void_, + rfH: runSyncExitWith, + v2Q: runPromiseWith +}); + + +}, +"./node_modules/effect/dist/Effectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.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 + * + * @category prototypes + * @since 4.0.0 + */ +const Prototype = options => (0,_internal_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: options.label, + [_internal_core_js__rspack_import_0/* .evaluate */._3]: options.evaluate +}); +const Base = /*#__PURE__*/(/* unused pure expression or super */ null && ((() => { + const Base = function () {}; + Base.prototype = /*#__PURE__*/Prototype({ + label: "Effectable", + evaluate(_) { + return this; + } + }); + return Base; +})())); +/** + * Provides an abstract class that can be extended to create an `Effect`. + * + * **When to use** + * + * Use as an abstract base class to define custom classes whose instances behave + * as `Effect` values. + * + * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class + * @category constructors + * @since 2.0.0 + */ +class Class extends (/* unused pure expression or super */ null && (Base)) {} +//# sourceMappingURL=Effectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + b: Prototype +}); + + +}, +"./node_modules/effect/dist/Encoding.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text. + * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes. + * Encode functions return strings directly, while decode functions return + * `Result.Result` so invalid input is reported as an `EncodingError` instead of + * being thrown. + * + * @since 4.0.0 + */ + + + +// ------------------------------------------------------------------------------------- +// EncodingError +// ------------------------------------------------------------------------------------- +/** + * Type identifier stored on `EncodingError` values and used by + * `isEncodingError`. + * + * **When to use** + * + * Use when implementing low-level `EncodingError`-compatible values that need + * to carry the runtime marker. + * + * **Details** + * + * This marker is part of the runtime representation of `EncodingError`. Prefer + * `isEncodingError` when narrowing unknown values. + * + * @see {@link isEncodingError} for the public guard that checks this marker + * + * @category type IDs + * @since 4.0.0 + */ +const EncodingErrorTypeId = "~effect/encoding/EncodingError"; +/** + * Error returned when an encoding or decoding operation cannot process its + * input. + * + * **When to use** + * + * Use when you need to handle or inspect failures from encoding or decoding + * operations. + * + * **Details** + * + * The error records whether the failure happened during encoding or decoding, + * which encoding module reported it, the original input, and a human-readable + * message. + * + * @see {@link isEncodingError} for checking whether a value is an EncodingError + * @category errors + * @since 4.0.0 + */ +class EncodingError extends /*#__PURE__*/(/* unused pure expression or super */ null && (Data.TaggedError("EncodingError"))) { + /** + * Marks this value as an encoding or decoding error for runtime guards. + * + * **When to use** + * + * Use to identify `EncodingError` instances through `isEncodingError`. + * + * @since 4.0.0 + */ + [EncodingErrorTypeId] = EncodingErrorTypeId; +} +/** + * Checks whether a value is an `EncodingError`. + * + * **When to use** + * + * Use to narrow an unknown value before handling it as an `EncodingError` from + * encoding or decoding code. + * + * **Details** + * + * Returns `true` when the value carries the `EncodingErrorTypeId` marker and + * narrows the value to `EncodingError`. + * + * @see {@link EncodingError} for the structured error produced by failed + * encoding and decoding operations + * + * @category guards + * @since 4.0.0 + */ +const isEncodingError = u => hasProperty(u, EncodingErrorTypeId); +// ------------------------------------------------------------------------------------- +// Base64 +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (RFC4648) `string`. + * + * **When to use** + * + * Use to encode text or bytes as a standard padded Base64 string for storage or + * transport. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64 encoding. + * `Uint8Array` inputs are encoded directly. The output uses the standard + * RFC4648 alphabet with `=` padding. + * + * **Example** (Encoding Base64 strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string + * Encoding.encodeBase64("hello") // => "aGVsbG8=" + * + * // Encode binary data + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeBase64(bytes) // => "SGVsbG8=" + * ``` + * + * @see {@link decodeBase64} for decoding standard Base64 to bytes + * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text + * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64 = input => typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input); +/** + * Decodes a base64 (RFC4648) string into bytes safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into bytes without throwing on + * invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64("SGVsbG8=") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64 = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 !== 0) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Length must be a multiple of 4, but is ${length}` + })); + } + const index = stripped.indexOf("="); + if (index !== -1 && (index < length - 2 || index === length - 2 && stripped[length - 1] !== "=")) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: `Found a '=' character, but it is not at the end` + })); + } + try { + const missingOctets = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0; + const result = new Uint8Array(3 * (length / 4) - missingOctets); + for (let i = 0, j = 0; i < length; i += 4, j += 3) { + const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 | getBase64Code(stripped.charCodeAt(i + 1)) << 12 | getBase64Code(stripped.charCodeAt(i + 2)) << 6 | getBase64Code(stripped.charCodeAt(i + 3)); + result[j] = buffer >> 16; + result[j + 1] = buffer >> 8 & 0xff; + result[j + 2] = buffer & 0xff; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + kind: "Decode", + module: "Base64", + input: stripped, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a base64 (RFC4648) string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64String("aGVsbG8=") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64String = str => Result.map(decodeBase64(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Base64Url +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a base64 (URL) `string`. + * + * **When to use** + * + * Use to encode text or bytes as an unpadded Base64Url string for contexts that + * require the URL-safe alphabet. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64Url encoding. + * `Uint8Array` inputs are encoded directly. The output removes `=` padding and + * replaces `+` with `-` and `/` with `_`. + * + * **Example** (Encoding URL-safe Base64) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // URL-safe base64 encoding (uses - and _ instead of + and /) + * Encoding.encodeBase64Url("hello?") // => "aGVsbG8_" + * + * const bytes = new Uint8Array([72, 101, 108, 108, 111, 63]) + * Encoding.encodeBase64Url(bytes) // => "SGVsbG8_" + * ``` + * + * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes + * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text + * @see {@link encodeBase64} for standard padded Base64 output + * + * @category encoding + * @since 2.0.0 + */ +const encodeBase64Url = input => typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input); +/** + * Decodes a URL-safe base64 string into bytes safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into bytes without throwing + * on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. Both padded and unpadded URL-safe base64 forms are accepted when + * otherwise valid. + * + * **Example** (Decoding URL-safe Base64 bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64Url("SGVsbG8_") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111, 63])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64Url = str => { + const stripped = stripCrlf(str); + const length = stripped.length; + if (length % 4 === 1) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: `Length should be a multiple of 4, but is ${length}` + })); + } + if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) { + return Result.fail(new EncodingError({ + module: "Base64Url", + kind: "Decode", + input: stripped, + message: "Invalid input" + })); + } + // Some variants allow or require omitting the padding '=' signs + let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped; + sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/"); + return decodeBase64(sanitized); +}; +/** + * Decodes a URL-safe base64 string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into UTF-8 text without + * throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. + * + * **Example** (Decoding URL-safe Base64 strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeBase64UrlString("aGVsbG8_") // => Result.succeed("hello?") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeBase64UrlString = str => Result.map(decodeBase64Url(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// Hex +// ------------------------------------------------------------------------------------- +/** + * Encodes the given value into a hex `string`. + * + * **When to use** + * + * Use to encode text or bytes as lowercase hexadecimal text. + * + * **Example** (Encoding hex strings and bytes) + * + * ```ts import.meta.vitest + * import { Encoding } from "effect" + * + * // Encode a string to hex + * Encoding.encodeHex("hello") // => "68656c6c6f" + * + * // Encode binary data to hex + * const bytes = new Uint8Array([72, 101, 108, 108, 111]) + * Encoding.encodeHex(bytes) // => "48656c6c6f" + * ``` + * + * @category encoding + * @since 2.0.0 + */ +const encodeHex = input => typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input); +/** + * Generates a random lowercase hexadecimal string, optimized for lengths that + * are multiples of 8. + * + * `length` is not validated. The function generates `length >>> 3` random + * 8-character words, so non-negative lengths below `2 ** 32` are rounded down + * to a multiple of 8 and other values follow JavaScript's unsigned 32-bit + * coercion rules. + * + * This function uses `Math.random()` and is not cryptographically secure. For + * security-sensitive values, use the `Crypto.Crypto` service's `randomBytes` + * method and encode the result with {@link encodeHex}. + * + * @category encoding + * @since 4.0.0 + */ +const randomHex = length => { + let result = ""; + for (let i = length >>> 3; i > 0; i--) { + const word = Math.random() * 0x100000000 >>> 0; + result += byteToHex[word >>> 24] + byteToHex[word >>> 16 & 0xff] + byteToHex[word >>> 8 & 0xff] + byteToHex[word & 0xff]; + } + return result; +}; +/** + * Decodes a hexadecimal string into bytes safely. + * + * **When to use** + * + * Use to decode hexadecimal text into bytes without throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input has an odd length or + * contains invalid hex characters. + * + * **Example** (Decoding hex bytes) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHex("48656c6c6f") // => Result.succeed(new Uint8Array([72, 101, 108, 108, 111])) + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHex = str => { + const bytes = new TextEncoder().encode(str); + if (bytes.length % 2 !== 0) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: `Length must be a multiple of 2, but is ${bytes.length}` + })); + } + try { + const length = bytes.length / 2; + const result = new Uint8Array(length); + for (let i = 0; i < length; i++) { + const a = fromHexChar(bytes[i * 2]); + const b = fromHexChar(bytes[i * 2 + 1]); + result[i] = a << 4 | b; + } + return Result.succeed(result); + } catch (e) { + return Result.fail(new EncodingError({ + module: "Hex", + kind: "Decode", + input: str, + message: e instanceof Error ? e.message : "Invalid input" + })); + } +}; +/** + * Decodes a hexadecimal string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode hexadecimal text into UTF-8 text without throwing on invalid + * input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid hex. + * + * **Example** (Decoding hex strings) + * + * ```ts import.meta.vitest + * import { Encoding, Result } from "effect" + * + * Encoding.decodeHexString("68656c6c6f") // => Result.succeed("hello") + * ``` + * + * @category decoding + * @since 2.0.0 + */ +const decodeHexString = str => Result.map(decodeHex(str), _ => decoder.decode(_)); +// ------------------------------------------------------------------------------------- +// internals +// ------------------------------------------------------------------------------------- +const encoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextEncoder())); +const decoder = /*#__PURE__*/(/* unused pure expression or super */ null && (new TextDecoder())); +const stripCrlf = str => str.replace(/[\n\r]/g, ""); +// Base64 internals +const base64EncodeUint8Array = bytes => { + const length = bytes.length; + let result = ""; + let i; + for (i = 2; i < length; i += 3) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2 | bytes[i] >> 6]; + result += base64abc[bytes[i] & 0x3f]; + } + if (i === length + 1) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4]; + result += "=="; + } + if (i === length) { + result += base64abc[bytes[i - 2] >> 2]; + result += base64abc[(bytes[i - 2] & 0x03) << 4 | bytes[i - 1] >> 4]; + result += base64abc[(bytes[i - 1] & 0x0f) << 2]; + result += "="; + } + return result; +}; +function getBase64Code(charCode) { + if (charCode >= base64codes.length) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + const code = base64codes[charCode]; + if (code === 255) { + throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`); + } + return code; +} +const base64abc = (/* unused pure expression or super */ null && (["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "/"])); +const base64codes = (/* unused pure expression or super */ null && ([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51])); +// Base64Url internals +const base64UrlEncodeUint8Array = data => base64EncodeUint8Array(data).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +// Hex internals +const byteToHex = []; +for (let i = 0; i < 256; i++) { + byteToHex.push(i.toString(16).padStart(2, "0")); +} +const hexEncodeUint8Array = bytes => { + let result = ""; + for (let i = 0; i < bytes.length; i++) { + result += byteToHex[bytes[i]]; + } + return result; +}; +const fromHexChar = byte => { + if (48 <= byte && byte <= 57) { + return byte - 48; + } + if (97 <= byte && byte <= 102) { + return byte - 97 + 10; + } + if (65 <= byte && byte <= 70) { + return byte - 65 + 10; + } + throw new TypeError("Invalid input"); +}; +//# sourceMappingURL=Encoding.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + nw: randomHex +}); + + +}, +"./node_modules/effect/dist/Equal.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Hash_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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; + } + // Special case for NaN: NaN should be considered equal to NaN + if (selfType === "number" && self !== self && that !== that) { + return true; + } + if (selfType !== "object" && selfType !== "function") { + return false; + } + if (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self) || _internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(that)) { + return false; + } + // For objects and functions, use cached comparison + return withCache(self, that, compareObjects); +} +/** Helper to run comparison with proper visited tracking */ +function withVisitedTracking(self, that, fn) { + const hasLeft = visitedLeft.has(self); + const hasRight = visitedRight.has(that); + // Check for circular references before adding + if (hasLeft && hasRight) { + return true; // Both are circular at the same level + } + if (hasLeft || hasRight) { + return false; // Only one is circular + } + visitedLeft.add(self); + visitedRight.add(that); + const result = fn(); + visitedLeft.delete(self); + visitedRight.delete(that); + return result; +} +const visitedLeft = /*#__PURE__*/new WeakSet(); +const visitedRight = /*#__PURE__*/new WeakSet(); +/** Helper to perform cached object comparison */ +function compareObjects(self, that) { + if (_Hash_js__rspack_import_1/* .hash */.tW(self) !== _Hash_js__rspack_import_1/* .hash */.tW(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) { + if (!(that instanceof RegExp)) return false; + return self.toString() === that.toString(); + } + const selfIsEqual = isEqual(self); + const thatIsEqual = isEqual(that); + if (selfIsEqual !== thatIsEqual) return false; + const bothEquals = selfIsEqual && thatIsEqual; + if (typeof self === "function" && !bothEquals) { + return false; + } + return withVisitedTracking(self, that, () => { + 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 (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) { + return false; + } + if (selfIsDataView) { + const thatDataView = that; + return compareTypedArrays(new Uint8Array(self.buffer, self.byteOffset, self.byteLength), new Uint8Array(thatDataView.buffer, thatDataView.byteOffset, thatDataView.byteLength)); + } + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) { + return false; + } + return compareMaps(self, that); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) { + return false; + } + return compareSets(self, that); + } + return compareRecords(self, that); + }); +} +function withCache(self, that, f) { + // Check cache first + let selfMap = equalityCache.get(self); + if (!selfMap) { + selfMap = new WeakMap(); + equalityCache.set(self, selfMap); + } else if (selfMap.has(that)) { + return selfMap.get(that); + } + // Perform the comparison + const result = f(self, that); + // Cache the result bidirectionally + selfMap.set(that, result); + let thatMap = equalityCache.get(that); + if (!thatMap) { + thatMap = new WeakMap(); + equalityCache.set(that, thatMap); + } + thatMap.set(self, result); + return result; +} +const equalityCache = /*#__PURE__*/new WeakMap(); +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 = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(self); + const thatKeys = (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(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; +} +/** @internal */ +function makeCompareMap(keyEquivalence, valueEquivalence) { + return function compareMaps(self, that) { + const thatEntries = Array.from(that); + for (const [selfKey, selfValue] of self) { + let found = false; + for (let i = 0; i < thatEntries.length; i++) { + const [thatKey, thatValue] = thatEntries[i]; + if (keyEquivalence(selfKey, thatKey) && valueEquivalence(selfValue, thatValue)) { + thatEntries[i] = thatEntries[thatEntries.length - 1]; + thatEntries.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareMaps = /*#__PURE__*/makeCompareMap(compareBoth, compareBoth); +/** @internal */ +function makeCompareSet(equivalence) { + return function compareSets(self, that) { + const thatValues = Array.from(that); + for (const selfValue of self) { + let found = false; + for (let i = 0; i < thatValues.length; i++) { + const thatValue = thatValues[i]; + if (equivalence(selfValue, thatValue)) { + thatValues[i] = thatValues[thatValues.length - 1]; + thatValues.pop(); + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; + }; +} +const compareSets = /*#__PURE__*/makeCompareSet(compareBoth); +/** + * 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 property keyed by + * {@link symbol}. + * - 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 + * @category guards + * @since 2.0.0 + */ +const isEqual = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Wraps {@link equals} as an `Equivalence`. + * + * **When to use** + * + * Use when you want to pass `Equal.equals` to APIs that require an + * `Equivalence`. + * + * **Details** + * + * - Returns a function `(a: A, b: A) => boolean` that delegates to + * {@link equals}. + * - Pure; allocates a thin wrapper on each call. + * + * **Example** (Deduplicating with Equal semantics) + * + * ```ts import.meta.vitest + * import { Array, Equal } from "effect" + * + * Array.dedupeWith([1, 2, 2, 3, 1], Equal.asEquivalence()) // => [1, 2, 3] + * ``` + * + * @see {@link equals} — the underlying comparison function + * @category instances + * @since 4.0.0 + */ +const asEquivalence = () => equals; +/** + * Creates a proxy that uses reference equality instead of structural equality. + * + * **When to use** + * + * Use when you need to compare a plain object or array by identity without + * mutating the original value. + * + * **Details** + * + * - Returns a `Proxy` wrapping `obj`. The proxy reads through to the + * original, so property access is unchanged. + * - The proxy is registered in an internal WeakSet; {@link equals} returns + * `false` for any pair where at least one operand is in that set (unless + * they are the same reference). + * - Each call creates a **new** proxy, so `byReference(x) !== byReference(x)`. + * - Does **not** mutate the original object (unlike {@link byReferenceUnsafe}). + * + * **Example** (Opting out of structural equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const a = { x: 1 } + * const b = { x: 1 } + * + * Equal.equals(a, b) // => true + * + * const aRef = Equal.byReference(a) + * Equal.equals(aRef, b) // => false + * Equal.equals(aRef, aRef) // => true + * aRef.x // => 1 + * ``` + * + * @see {@link byReferenceUnsafe} — same effect without a proxy (mutates the + * original) + * @see {@link equals} — the comparison function affected by this opt-out + * @category equality + * @since 4.0.0 + */ +const byReference = obj => byReferenceUnsafe(new Proxy(obj, {})); +/** + * Marks an object permanently to use reference equality, without creating a proxy. + * + * **When to use** + * + * Use when you need reference equality without proxy allocation and accept + * permanently marking the original object for reference-only equality. + * + * **Details** + * + * - Adds `obj` to an internal WeakSet. From that point on, {@link equals} + * treats it as reference-only. + * - Returns the **same** object (not a copy or proxy), so + * `byReferenceUnsafe(x) === x`. + * - Does **not** affect the object's prototype, properties, or behavior + * beyond equality checks. + * + * **Gotchas** + * + * The marking is irreversible for the lifetime of the object. + * + * **Example** (Marking an object for reference equality) + * + * ```ts import.meta.vitest + * import { Equal } from "effect" + * + * const obj1 = { a: 1, b: 2 } + * const obj2 = { a: 1, b: 2 } + * + * const marked = Equal.byReferenceUnsafe(obj1) + * + * Equal.equals(obj1, obj2) // => false + * Equal.equals(obj1, obj1) // => true + * marked === obj1 // => true + * ``` + * + * @see {@link byReference} — safer alternative that creates a proxy + * @see {@link equals} — the comparison function affected by this opt-out + * @category unsafe + * @since 4.0.0 + */ +const byReferenceUnsafe = obj => { + _internal_equal_js__rspack_import_0/* .byReferenceInstances.add */.J.add(obj); + return obj; +}; +//# sourceMappingURL=Equal.js.map +__webpack_require__.d(__webpack_exports__, { + aI: () => (equals) +}, { + HR: symbol, + Xq: byReferenceUnsafe, + jI: asEquivalence +}); + + +}, +"./node_modules/effect/dist/Equivalence.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Defines reusable equality functions for values of the same type. + * + * An `Equivalence` returns `true` when two `A` values should be treated as + * the same for a particular purpose. This module includes strict equality + * instances for primitive types, constructors for custom comparisons, and + * helpers for tuples, arrays, structs, records, dates, and values compared + * through a derived field. + * + * @since 2.0.0 + */ + + +/** + * Creates a custom equivalence relation with an optimized reference equality check. + * + * **When to use** + * + * Use when you need an equality rule that the built-in instances and input + * mapping helpers cannot express, and you can provide a law-abiding comparison. + * + * **Details** + * + * The returned equivalence first checks reference equality (`===`) for + * performance. If the values are not the same reference, it falls back to the + * provided equivalence function, which must satisfy reflexive, symmetric, and + * transitive properties. + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.make((a, b) => + * a.toLowerCase() === b.toLowerCase() + * ) + * + * caseInsensitive("Hello", "HELLO") // => true + * caseInsensitive("foo", "bar") // => false + * + * // Same reference optimization + * const str = "test" + * caseInsensitive(str, str) // => true + * ``` + * + * **Example** (Comparing numbers with tolerance) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const tolerance = Equivalence.make((a, b) => Math.abs(a - b) < 0.0001) + * + * tolerance(1.0, 1.001) // => false + * tolerance(1.0, 1.00001) // => true + * ``` + * + * @see {@link strictEqual} + * @see {@link mapInput} + * @category constructors + * @since 2.0.0 + */ +const make = isEquivalent => (self, that) => self === that || isEquivalent(self, that); +const isStrictEquivalent = (x, y) => x === y; +/** + * Creates an equivalence relation that uses strict equality (`===`) to compare values. + * + * **When to use** + * + * Use when you need strict equality (`===`) as the comparison. + * + * **Details** + * + * Uses JavaScript's strict equality operator (`===`). Primitives compare by + * value. Objects compare by reference, so only the same object instance is + * equivalent. Use this as a building block for more complex equivalences via + * `mapInput` or `combine`. + * + * **Gotchas** + * + * `NaN !== NaN`, so `NaN` values are never considered equivalent. + * + * **Example** (Comparing primitive types) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const strictEq = Equivalence.strictEqual() + * + * strictEq(1, 1) // => true + * strictEq(1, 2) // => false + * strictEq(NaN, NaN) // => false + * ``` + * + * **Example** (Comparing objects by reference) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const obj = { value: 42 } + * const strictObjEq = Equivalence.strictEqual() + * + * strictObjEq(obj, obj) // => true + * strictObjEq(obj, { value: 42 }) // => false + * ``` + * + * @see {@link make} + * @see `Equal` for structural equality + * @category constructors + * @since 4.0.0 + */ +const strictEqual = () => isStrictEquivalent; +/** + * Equivalence instance for strings using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply case-sensitive string equality. + * + * **Example** (Comparing strings) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.String("hello", "hello") // => true + * Equivalence.String("hello", "world") // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const String = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for numbers. + * + * **When to use** + * + * Use when you need numeric equality that treats NaN as equal to itself. + * + * **Example** (Comparing numbers) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Number(1, 1) // => true + * Equivalence.Number(1, 2) // => false + * Equivalence.Number(NaN, NaN) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)))); +/** + * Equivalence instance for booleans using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply boolean equality. + * + * **Example** (Comparing booleans) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.Boolean(true, true) // => true + * Equivalence.Boolean(true, false) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const Boolean = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Equivalence instance for bigints using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply bigint equality. + * + * **Example** (Comparing bigints) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * Equivalence.BigInt(1n, 1n) // => true + * Equivalence.BigInt(1n, 2n) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const BigInt = (/* unused pure expression or super */ null && (isStrictEquivalent)); +/** + * Combines two equivalence relations using logical AND. + * + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** + * + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining name and age equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * } + * + * const nameEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.name + * ) + * + * const ageEquivalence = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Person) => p.age + * ) + * + * const personEquivalence = Equivalence.combine(nameEquivalence, ageEquivalence) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Alice", age: 30 } + * const person3 = { name: "Alice", age: 31 } + * + * personEquivalence(person1, person2) // => true + * personEquivalence(person1, person3) // => false + * ``` + * + * @see {@link combineAll} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((x, y) => self(x, y) && that(x, y))))); +/** + * Combines multiple equivalence relations into a single equivalence using logical AND. + * + * **When to use** + * + * Use when you need to combine many `Equivalence` instances from an iterable. + * + * **Details** + * + * Returns `true` only if all equivalences in the collection return `true`. The + * comparison stops at the first equivalence that returns `false`. Empty + * collections return an equivalence that always returns `true`. The result is + * also an equivalence that satisfies reflexive, symmetric, and transitive + * properties. + * + * **Example** (Combining multiple field equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Point3D { + * x: number + * y: number + * z: number + * } + * + * const xEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.x + * ) + * const yEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.y + * ) + * const zEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (p: Point3D) => p.z + * ) + * + * const point3DEq = Equivalence.combineAll([xEq, yEq, zEq]) + * + * const point1 = { x: 1, y: 2, z: 3 } + * const point2 = { x: 1, y: 2, z: 3 } + * const point3 = { x: 1, y: 2, z: 4 } + * + * point3DEq(point1, point2) // => true + * point3DEq(point1, point3) // => false + * ``` + * + * **Example** (Handling empty collections) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * // Empty collection always returns true + * const alwaysEq = Equivalence.combineAll([]) + * alwaysEq("anything", "else") // => true + * ``` + * + * @see {@link combine} + * @see {@link mapInput} + * @category combining + * @since 2.0.0 + */ +const combineAll = collection => make((x, y) => { + for (const equivalence of collection) { + if (!equivalence(x, y)) { + return false; + } + } + return true; +}); +/** + * Transforms an equivalence relation by mapping the input values before comparison. + * + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** + * + * - Applies the transformation function to both values before comparing + * - The transformation function should be pure and have no side effects + * - The resulting equivalence compares the transformed values using the provided equivalence + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings + * + * **Example** (Deriving equivalence from an object property) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface User { + * id: number + * name: string + * email: string + * } + * + * // Create equivalence based on user ID only + * const userByIdEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (user: User) => user.id + * ) + * + * const user1 = { id: 1, name: "Alice", email: "alice@example.com" } + * const user2 = { id: 1, name: "Alice Smith", email: "alice.smith@example.com" } + * const user3 = { id: 2, name: "Bob", email: "bob@example.com" } + * + * userByIdEq(user1, user2) // => true + * userByIdEq(user1, user3) // => false + * ``` + * + * **Example** (Case-insensitive string equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitiveEq = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * caseInsensitiveEq("Hello", "HELLO") // => true + * caseInsensitiveEq("Hello", "World") // => false + * ``` + * + * @see {@link combine} + * @see {@link Struct} + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => make((x, y) => self(f(x), f(y)))))); +/** + * Creates an equivalence for tuples with heterogeneous element types. + * + * **When to use** + * + * Use when you need an `Equivalence` for fixed-length tuples with per-position + * equivalences. + * + * **Details** + * + * Tuples must have the same length; different lengths are never equivalent. + * Each equivalence is applied to the corresponding element position. The result + * returns `true` only if all elements are equivalent according to their + * respective equivalences, and it also satisfies reflexive, symmetric, and + * transitive properties. + * + * **Example** (Comparing homogeneous tuples) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringTupleEq = Equivalence.Tuple([ + * Equivalence.strictEqual(), + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ]) + * + * const tuple1 = ["hello", "world", "test"] as const + * const tuple2 = ["hello", "world", "test"] as const + * const tuple3 = ["hello", "world", "different"] as const + * + * stringTupleEq(tuple1, tuple2) // => true + * stringTupleEq(tuple1, tuple3) // => false + * ``` + * + * **Example** (Comparing tuples with custom equivalences) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const customTupleEq = Equivalence.Tuple([ + * caseInsensitive, + * caseInsensitive, + * caseInsensitive + * ]) + * + * customTupleEq(["Hello", "World", "Test"], ["HELLO", "WORLD", "TEST"]) // => true + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + if (self.length !== that.length) { + return false; + } + for (let i = 0; i < self.length; i++) { + if (!elements[i](self[i], that[i])) { + return false; + } + } + return true; + }); +} +/** + * @since 4.0.0 + */ +function Array_(item) { + return make((self, that) => { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) { + if (!item(self[i], that[i])) return false; + } + return true; + }); +} + +/** + * Creates an equivalence for objects by comparing their properties using provided equivalences. + * + * **When to use** + * + * Use when you need an `Equivalence` for objects with known, fixed property + * names. + * + * **Details** + * + * Compares only the properties specified in the struct definition; other + * properties are ignored. String and symbol keys are supported via + * `Reflect.ownKeys`. The result returns `true` only if all specified properties + * are equivalent according to their equivalences, and it also satisfies + * reflexive, symmetric, and transitive properties. + * + * **Example** (Comparing structs with different equivalences per field) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * interface Person { + * name: string + * age: number + * email: string + * } + * + * const caseInsensitive = Equivalence.mapInput( + * Equivalence.strictEqual(), + * (s: string) => s.toLowerCase() + * ) + * + * const personEq = Equivalence.Struct({ + * name: caseInsensitive, + * age: Equivalence.strictEqual(), + * email: caseInsensitive + * }) + * + * const person1 = { name: "Alice", age: 30, email: "alice@example.com" } + * const person2 = { name: "ALICE", age: 30, email: "ALICE@EXAMPLE.COM" } + * const person3 = { name: "Alice", age: 31, email: "alice@example.com" } + * + * personEq(person1, person2) // => true + * personEq(person1, person3) // => false + * ``` + * + * **Example** (Comparing specific fields) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const nameAgeEq = Equivalence.Struct({ + * name: Equivalence.strictEqual(), + * age: Equivalence.strictEqual() + * }) + * + * // Only compares name and age, ignores other properties + * const obj1 = { name: "Alice", age: 30, extra: "ignored" } + * const obj2 = { name: "Alice", age: 30, extra: "different" } + * nameAgeEq(obj1, obj2) // => true + * ``` + * + * @see {@link Record} + * @see {@link mapInput} + * @see {@link combine} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Reflect.ownKeys(fields); + return make((self, that) => { + for (const key of keys) { + if (!fields[key](self[key], that[key])) return false; + } + return true; + }); +} +/** + * Creates an equivalence for objects by comparing all properties using the same equivalence. + * + * **When to use** + * + * Use when you need to compare records with the same equivalence for every + * property value. + * + * **Details** + * + * - Compares all properties present in both objects + * - Requires both objects to have the same set of keys; different keys result in `false` + * - All property values must be equivalent according to the provided equivalence + * - Supports both string and symbol keys via `Reflect.ownKeys` + * - Empty objects are considered equivalent + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * + * **Example** (Defining records with string values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const stringRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const record1 = { a: "hello", b: "world" } + * const record2 = { a: "hello", b: "world" } + * const record3 = { a: "hello", b: "different" } + * const record4 = { a: "hello" } // missing key 'b' + * + * stringRecordEq(record1, record2) // => true + * stringRecordEq(record1, record3) // => false + * stringRecordEq(record1, record4) // => false + * ``` + * + * **Example** (Defining records with number values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const numberRecordEq = Equivalence.Record(Equivalence.strictEqual()) + * + * const scores1 = { alice: 100, bob: 85 } + * const scores2 = { alice: 100, bob: 85 } + * const scores3 = { alice: 100, bob: 90 } + * + * numberRecordEq(scores1, scores2) // => true + * numberRecordEq(scores1, scores3) // => false + * ``` + * + * @category combinators + * @since 4.0.0 + */ +function Record(value) { + return make((self, that) => { + const selfKeys = Reflect.ownKeys(self); + const thatKeys = Reflect.ownKeys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (const key of selfKeys) { + if (!Object.hasOwn(that, key) || !value(self[key], that[key])) { + return false; + } + } + return true; + }); +} +/** + * Creates a `Reducer` for combining `Equivalence` instances, useful for aggregating equivalences in collections. + * + * **When to use** + * + * Use when you need a reducer that combines equivalences. + * + * **Details** + * + * Returns a reducer that combines equivalences using `combine`. The identity + * element for empty collections is an equivalence that always returns `true`. + * The reducer uses `combineAll` for collections of equivalences and can be used + * with fold operations. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const reducer = Equivalence.makeReducer() + * const equivalences = [ + * Equivalence.strictEqual(), + * Equivalence.make((a, b) => Math.abs(a - b) < 1) + * ] + * + * const combined = reducer.combineAll(equivalences) + * // Combined equivalence requires both conditions to be true + * combined(1, 1) // => true + * combined(1, 1.5) // => false + * ``` + * + * @see {@link combine} Combine two equivalences + * @see {@link combineAll} Combine multiple equivalences + * @see {@link Reducer} Reducer type for collection operations + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => true, combineAll); +} +/** + * Equivalence instance for `Date` objects that compares their `getTime()` values using `Equivalence.Number`. + * + * **When to use** + * + * Use when you need an `Equivalence` for JavaScript date objects by their + * millisecond timestamp. + * + * **Details** + * + * Different `Date` instances that represent the same millisecond timestamp are equivalent. Because `Equivalence.Number` + * treats `NaN` as equal to `NaN`, two invalid `Date` values are also considered equivalent. + * + * **Example** (Comparing Date values) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date("2020-01-01T00:00:00.000Z") + * const d2 = new Date("2020-01-01T00:00:00.000Z") + * const d3 = new Date("2021-01-01T00:00:00.000Z") + * const invalidDate1 = new Date("foo") + * const invalidDate2 = new Date("bar") + * + * Equivalence.Date(d1, d2) // => true + * Equivalence.Date(d1, d3) // => false + * Equivalence.Date(invalidDate1, invalidDate2) // => true + * Equivalence.Date(invalidDate1, d1) // => false + * ``` + * + * **Example** (Comparing reference and value equality) + * + * ```ts import.meta.vitest + * import { Equivalence } from "effect" + * + * const d1 = new Date(0) + * const d2 = new Date(0) + * + * d1 === d2 // => false + * Equivalence.Date(d1, d2) // => true + * ``` + * + * @see {@link Number} for the numeric equivalence applied to each `Date#getTime()` result + * @see {@link mapInput} for deriving an equivalence by mapping inputs before comparison + * @see {@link strictEqual} for reference equality when two values must be the same object + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, d => d.getTime()))); +//# sourceMappingURL=Equivalence.js.map +__webpack_require__.d(__webpack_exports__, { + O3: () => (Array_) +}, { + L8: make +}); + + +}, +"./node_modules/effect/dist/ExecutionPlan.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); + + + + + + +/** + * Runtime type identifier attached to `ExecutionPlan` values and used by + * `isExecutionPlan`. + * + * @category type IDs + * @since 3.16.0 + */ +const TypeId = "~effect/ExecutionPlan"; +/** + * Returns `true` if a value is an `ExecutionPlan` by checking for the + * `ExecutionPlan.TypeId` marker. + * + * **When to use** + * + * Use when accepting an unknown value and you need to narrow it to an + * `ExecutionPlan` before reading plan fields or passing it to plan-consuming + * APIs. + * + * **Gotchas** + * + * This is a structural marker check; it does not validate the marker value or + * the shape of the plan steps. + * + * @see {@link make} for constructing execution plans that satisfy this guard + * @see {@link TypeId} for the runtime marker checked by this guard + * + * @category guards + * @since 3.16.0 + */ +const isExecutionPlan = u => Predicate.hasProperty(u, TypeId); +/** + * Create an `ExecutionPlan`, which can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. + * + * **Example** (Creating an execution plan) + * + * ```ts import.meta.vitest + * import { Context, ExecutionPlan } from "effect" + * + * const ThePlan = ExecutionPlan.make( + * { + * provide: Context.empty(), + * attempts: 2 + * }, + * { + * provide: Context.empty() + * } + * ) + * + * ThePlan.steps.length // => 2 + * ``` + * + * @category constructors + * @since 3.16.0 + */ +const make = (...steps) => makeProto(steps.map((options, i) => { + if (options.attempts !== undefined && options.attempts < 1) { + throw new Error(`ExecutionPlan.make: step[${i}].attempts must be greater than 0`); + } + return { + schedule: options.schedule, + attempts: options.attempts, + while: options.while ? input => effect.suspend(() => { + const result = options.while(input); + return typeof result === "boolean" ? effect.succeed(result) : result; + }) : undefined, + provide: options.provide + }; +})); +const Proto = (/* unused pure expression or super */ null && ({ + [TypeId]: TypeId, + get captureRequirements() { + const self = this; + return effect.contextWith(context => effect.succeed(makeProto(self.steps.map(step => ({ + ...step, + provide: Layer.isLayer(step.provide) ? Layer.provide(step.provide, Layer.succeedContext(context)) : step.provide + }))))); + }, + pipe() { + return pipeArguments(this, arguments); + } +})); +const makeProto = steps => { + const self = Object.create(Proto); + self.steps = steps; + return self; +}; +/** + * Combines multiple execution plans by concatenating their steps in order. + * + * **When to use** + * + * Use to combine separately defined fallback plans into one ordered plan before + * applying it to an effect or stream. + * + * **Details** + * + * The resulting plan tries every step from the first plan, then every step from + * the next plan, and so on. + * + * @see {@link make} for building a plan from individual steps instead of combining existing plans + * + * @category combining + * @since 3.16.0 + */ +const merge = (...plans) => makeProto(plans.flatMap(plan => plan.steps)); +/** + * Context reference containing metadata for the currently running + * execution-plan attempt. + * + * **When to use** + * + * Use to read the active plan step and attempt while code is running under an + * execution plan. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/ExecutionPlan/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + attempt: 0, + stepIndex: 0 + }) +}); +//# sourceMappingURL=ExecutionPlan.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + d3: CurrentMetadata +}); + + +}, +"./node_modules/effect/dist/Exit.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = _internal_core_js__rspack_import_0/* .ExitTypeId */.IH; +/** + * Checks whether an unknown value is an Exit. + * + * **When to use** + * + * Use to validate unknown values at system boundaries and narrow them to + * `Exit`. + * + * **Details** + * + * Does not inspect the contents of the Exit. Returns `true` for both Success + * and Failure exits. + * + * **Example** (Checking if a value is an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.isExit(Exit.succeed(42)) // => true + * Exit.isExit(Exit.fail("err")) // => true + * Exit.isExit("not an exit") // => false + * ``` + * + * @see {@link isSuccess} to check for a successful Exit + * @see {@link isFailure} to check for a failed Exit + * + * @category guards + * @since 2.0.0 + */ +const isExit = _internal_core_js__rspack_import_0/* .isExit */.b9; +/** + * Creates a successful Exit containing the given value. + * + * **When to use** + * + * Use when you need an Exit that contains a known success value. + * + * **Details** + * + * Returns a `Success` with the provided value. Does not perform any + * computation. + * + * **Example** (Creating a successful Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.succeed(42) // => Exit.succeed(42) + * ``` + * + * @see {@link fail} to create a failed Exit + * @see {@link void_ void} for a pre-allocated success with no value + * + * @category constructors + * @since 2.0.0 + */ +const succeed = _internal_core_js__rspack_import_0/* .exitSucceed */.xt; +/** + * Creates a failed Exit from a Cause. + * + * **When to use** + * + * Use when you already have a `Cause` and want to wrap it in an Exit + * for advanced error handling where you need full control over the Cause + * structure. + * + * **Details** + * + * Returns a `Failure`. If you only have an error value, use + * {@link fail} instead. + * + * **Example** (Creating a failed Exit from a Cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link fail} to create a Failure from a plain error value + * @see {@link die} to create a Failure from a defect + * + * @category constructors + * @since 2.0.0 + */ +const failCause = _internal_core_js__rspack_import_0/* .exitFailCause */.cb; +/** + * Creates a failed Exit from a typed error value. + * + * **When to use** + * + * Use when you need to represent an expected typed failure as an `Exit`. + * + * **Details** + * + * The error is wrapped in a `Cause.Fail` internally. + * + * Returns a `Failure`. + * + * **Example** (Creating a failed Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.fail("Something went wrong") // => Exit.fail("Something went wrong") + * ``` + * + * @see {@link succeed} to create a successful Exit + * @see {@link die} to create a Failure from an unexpected defect + * @see {@link failCause} to create a Failure from a full Cause + * + * @category constructors + * @since 2.0.0 + */ +const fail = _internal_core_js__rspack_import_0/* .exitFail */.Rk; +/** + * Creates a failed Exit from a defect (unexpected error). + * + * **When to use** + * + * Use when you need unexpected, unrecoverable errors that should not appear in + * the typed error channel. + * + * **Details** + * + * The defect is wrapped in a `Cause.Die` internally. + * + * Returns a `Failure` with `E = never`, since defects do not appear in + * the typed error channel. + * + * **Example** (Creating a defect Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.die("Unexpected error") // => Exit.die("Unexpected error") + * ``` + * + * @see {@link fail} to create a Failure from a typed error + * @see {@link hasDies} to check whether an Exit contains defects + * + * @category constructors + * @since 2.0.0 + */ +const die = _internal_core_js__rspack_import_0/* .exitDie */.V2; +/** + * Creates a failed Exit representing fiber interruption. + * + * **When to use** + * + * Use to signal that a fiber was interrupted. + * + * **Details** + * + * Optionally pass a fiber ID to identify which fiber was interrupted. Returns + * a `Failure` with an `Interrupt` cause. + * + * **Example** (Creating an interruption Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.interrupt(123) // => Exit.interrupt(123) + * ``` + * + * @see {@link hasInterrupts} to check whether an Exit contains interruptions + * + * @category constructors + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_1/* .exitInterrupt */._sz; +const void_ = _internal_effect_js__rspack_import_1/* .exitVoid */.x5l; + +/** + * Checks whether an Exit is a Success. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Success` and access the + * `value` property. + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * const exit = Exit.succeed(42) + * + * if (Exit.isSuccess(exit)) { + * exit.value // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isSuccess = _internal_effect_js__rspack_import_1/* .exitIsSuccess */.CoE; +/** + * Checks whether an Exit is a Failure. + * + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Failure` and access the + * `cause` property. + * + * **Example** (Narrowing to failure) + * + * ```ts import.meta.vitest + * import { Cause, Exit } from "effect" + * + * const exit = Exit.fail("error") + * + * if (Exit.isFailure(exit)) { + * exit.cause // => Cause.fail("error") + * } + * ``` + * + * @see {@link isSuccess} for the opposite check + * @see {@link match} for exhaustive pattern matching + * + * @category guards + * @since 2.0.0 + */ +const isFailure = _internal_effect_js__rspack_import_1/* .exitIsFailure */.VE1; +/** + * Checks whether a failed Exit contains typed errors (Fail reasons). + * + * **When to use** + * + * Use to distinguish typed failures from defects or interruptions. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Fail` reasons in the + * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for typed errors) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasFails(Exit.fail("err")) // => true + * Exit.hasFails(Exit.die("bug")) // => false + * Exit.hasFails(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasDies} to check for defects + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasFails = _internal_effect_js__rspack_import_1/* .exitHasFails */._mh; +/** + * Checks whether a failed Exit contains defects (Die reasons). + * + * **When to use** + * + * Use to check whether an `Exit` failure cause contains unexpected errors. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Die` reasons in the + * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`. + * + * **Example** (Checking for defects) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasDies(Exit.die("bug")) // => true + * Exit.hasDies(Exit.fail("err")) // => false + * Exit.hasDies(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasInterrupts} to check for interruptions + * + * @category guards + * @since 4.0.0 + */ +const hasDies = _internal_effect_js__rspack_import_1/* .exitHasDies */.YDM; +/** + * Checks whether a failed Exit contains interruptions (Interrupt reasons). + * + * **When to use** + * + * Use to check whether an `Exit` contains fiber interruption. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Interrupt` reasons in + * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`. + * + * **Example** (Checking for interruptions) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.hasInterrupts(Exit.interrupt(1)) // => true + * Exit.hasInterrupts(Exit.fail("err")) // => false + * Exit.hasInterrupts(Exit.succeed(42)) // => false + * ``` + * + * @see {@link hasFails} to check for typed errors + * @see {@link hasDies} to check for defects + * + * @category guards + * @since 4.0.0 + */ +const hasInterrupts = _internal_effect_js__rspack_import_1/* .exitHasInterrupts */.lNM; +/** + * Extracts the Success variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Success wrapper. + * + * **Details** + * + * Returns `Result.succeed(success)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for success) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterSuccess(Exit.succeed(42)) // => Result.succeed(Exit.succeed(42)) + * ``` + * + * @see {@link filterFailure} for the inverse + * @see {@link filterValue} to extract the raw value instead of the Success object + * + * @category filtering + * @since 4.0.0 + */ +const filterSuccess = _internal_effect_js__rspack_import_1/* .exitFilterSuccess */.K$2; +/** + * Extracts the success value from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw success value rather than the Success + * wrapper. + * + * **Details** + * + * Returns `Result.succeed(value)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the value) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterValue(Exit.succeed(42)) // => Result.succeed(42) + * ``` + * + * @see {@link filterSuccess} to get the full Success object + * @see {@link getSuccess} to get the value as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterValue = _internal_effect_js__rspack_import_1/* .exitFilterValue */.GUt; +/** + * Extracts the Failure variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(failure)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for failure) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.filterFailure(Exit.fail("err")) // => Result.succeed(Exit.fail("err")) + * ``` + * + * @see {@link filterSuccess} for the inverse + * @see {@link filterCause} to extract the Cause directly + * + * @category filtering + * @since 4.0.0 + */ +const filterFailure = _internal_effect_js__rspack_import_1/* .exitFilterFailure */.HIt; +/** + * Extracts the Cause from a failed Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw Cause rather than the Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(cause)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. + * + * **Example** (Filtering for the cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Result } from "effect" + * + * Exit.filterCause(Exit.fail("err")) // => Result.succeed(Cause.fail("err")) + * ``` + * + * @see {@link filterFailure} to get the full Failure object + * @see {@link getCause} to get the Cause as an Option instead + * + * @category filtering + * @since 4.0.0 + */ +const filterCause = _internal_effect_js__rspack_import_1/* .exitFilterCause */.yJo; +/** + * Extracts the first typed error value from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(error)` when the Cause contains a Fail reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple errors, the rest + * are ignored. + * + * **Example** (Finding the first typed error) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findError(Exit.fail("not found")) // => Result.succeed("not found") + * Exit.findError(Exit.die("bug")) // => Result.fail(Exit.die("bug")) + * ``` + * + * @see {@link findErrorOption} to get the error as an Option instead + * @see {@link findDefect} to find defects instead + * + * @category filtering + * @since 4.0.0 + */ +const findError = _internal_effect_js__rspack_import_1/* .exitFindError */._OD; +/** + * Extracts the first defect from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first defect from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(defect)` when the Cause contains a Die reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** + * + * Only finds the first Die reason. If the Cause has multiple defects, the rest + * are ignored. + * + * **Example** (Finding the first defect) + * + * ```ts import.meta.vitest + * import { Exit, Result } from "effect" + * + * Exit.findDefect(Exit.die("boom")) // => Result.succeed("boom") + * Exit.findDefect(Exit.fail("err")) // => Result.fail(Exit.fail("err")) + * ``` + * + * @see {@link findError} to find typed errors instead + * @see {@link hasDies} to check for defects without extracting them + * + * @category filtering + * @since 4.0.0 + */ +const findDefect = _internal_effect_js__rspack_import_1/* .exitFindDefect */.jCT; +/** + * Pattern matches on an Exit, handling both success and failure cases. + * + * **When to use** + * + * Use when you need exhaustive handling of both `Exit` success and failure + * outcomes. + * + * **Details** + * + * Calls `onSuccess` with the value if the Exit is a Success, and calls + * `onFailure` with the Cause if the Exit is a Failure. + * + * **Example** (Matching on an Exit) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.match(Exit.succeed(42), { + * onSuccess: (value) => `Got: ${value}`, + * onFailure: () => "Failed" + * }) // => "Got: 42" + * ``` + * + * @see {@link isSuccess} and {@link isFailure} for simple boolean checks + * + * @category pattern matching + * @since 2.0.0 + */ +const match = _internal_effect_js__rspack_import_1/* .exitMatch */.Wtn; +/** + * Transforms the success value of an Exit using the given function. + * + * **When to use** + * + * Use to apply a transformation to the value inside a successful Exit + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Mapping over a success) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.map(Exit.succeed(21), (x) => x * 2) // => Exit.succeed(42) + * ``` + * + * @see {@link mapError} to transform the error + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const map = _internal_effect_js__rspack_import_1/* .exitMap */.v9O; +/** + * Transforms the typed error of a failed Exit using the given function. + * + * **When to use** + * + * Use to remap typed errors while preserving the Exit structure + * + * **Details** + * + * Successes pass through unchanged. + * + * Allocates a new Exit if the error is transformed. + * + * **Gotchas** + * + * Only transforms typed errors (Fail reasons). If the Cause contains only + * defects or interruptions, the failure passes through unchanged. + * + * **Example** (Mapping over an error) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapError(Exit.fail("bad input"), (error) => error.toUpperCase()) // => Exit.fail("BAD INPUT") + * ``` + * + * @see {@link map} to transform the success value + * @see {@link mapBoth} to transform both success and error + * + * @category combinators + * @since 2.0.0 + */ +const mapError = _internal_effect_js__rspack_import_1/* .exitMapError */.zPu; +/** + * Transforms both the success value and typed error of an Exit. + * + * **When to use** + * + * Use when you need to remap both channels in one step. + * + * **Details** + * + * `onSuccess` transforms the value if the Exit is a Success. `onFailure` + * transforms the typed error if the Exit is a Failure with a Fail reason. + * Allocates a new Exit. + * + * **Gotchas** + * + * If the Cause contains only defects or interruptions, the failure passes + * through unchanged. + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.mapBoth(Exit.succeed(42), { + * onSuccess: (x) => String(x), + * onFailure: (error: string) => error.toUpperCase() + * }) // => Exit.succeed("42") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error + * + * @category combinators + * @since 2.0.0 + */ +const mapBoth = _internal_effect_js__rspack_import_1/* .exitMapBoth */.EkE; +/** + * Discards the success value of an Exit, replacing it with `void`. + * + * **When to use** + * + * Use when you need to discard a successful `Exit` value while preserving + * whether the `Exit` succeeded or failed. + * + * **Details** + * + * Failures pass through unchanged. + * + * Allocates a new Exit if successful. + * + * **Example** (Discarding the success value) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoid(Exit.succeed(42)) // => Exit.succeed(undefined) + * ``` + * + * @see {@link void_ void} for a pre-allocated void success + * @see {@link asVoidAll} to combine multiple exits into a single void Exit + * + * @category combinators + * @since 2.0.0 + */ +const asVoid = _internal_effect_js__rspack_import_1/* .exitAsVoid */.Hox; +/** + * Combines multiple Exit values into a single `Exit`. + * + * **When to use** + * + * Use to validate that all exits in a collection succeeded + * + * **Details** + * + * If all exits are successful, this returns a void success. If any exit is a + * failure, this returns a single failure with all error causes combined. + * + * Iterates over the entire collection. Collects all failure causes, not just + * the first. + * + * **Example** (Combining exits) + * + * ```ts import.meta.vitest + * import { Exit } from "effect" + * + * Exit.asVoidAll([Exit.succeed(1), Exit.succeed(2), Exit.succeed(3)]) // => Exit.succeed(undefined) + * Exit.asVoidAll([Exit.succeed(1), Exit.fail("err"), Exit.succeed(3)]) // => Exit.fail("err") + * ``` + * + * @see {@link asVoid} to discard the value of a single Exit + * + * @category combinators + * @since 4.0.0 + */ +const asVoidAll = _internal_effect_js__rspack_import_1/* .exitAsVoidAll */.ely; +/** + * Returns the success value of an Exit as an Option. + * + * **When to use** + * + * Use when you need the success value from an `Exit` as an `Option` instead of + * pattern matching. + * + * **Details** + * + * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure. + * + * **Example** (Getting the success value) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.getSuccess(Exit.succeed(42)) // => Option.some(42) + * Exit.getSuccess(Exit.fail("err")) // => Option.none() + * ``` + * + * @see {@link getCause} to extract the Cause of a failure + * @see {@link filterValue} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_effect_js__rspack_import_1/* .exitGetSuccess */.kMI; +/** + * Returns the Cause of a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the failure `Cause` from an `Exit` as an `Option` instead + * of pattern matching. + * + * **Details** + * + * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success. + * + * **Example** (Getting the failure cause) + * + * ```ts import.meta.vitest + * import { Cause, Exit, Option } from "effect" + * + * Exit.getCause(Exit.fail("err")) // => Option.some(Cause.fail("err")) + * Exit.getCause(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link getSuccess} to extract the success value + * @see {@link filterCause} for filter-pipeline usage + * + * @category getters + * @since 4.0.0 + */ +const getCause = _internal_effect_js__rspack_import_1/* .exitGetCause */.Sv3; +/** + * Returns the first typed error from a failed Exit as an Option. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as an `Option`, + * ignoring successes and non-typed failures. + * + * **Details** + * + * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes, + * defect-only failures, and interrupt-only failures return `Option.none()`. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple typed errors, + * the rest are ignored. + * + * **Example** (Getting the first error) + * + * ```ts import.meta.vitest + * import { Exit, Option } from "effect" + * + * Exit.findErrorOption(Exit.fail("err")) // => Option.some("err") + * Exit.findErrorOption(Exit.die("bug")) // => Option.none() + * Exit.findErrorOption(Exit.succeed(42)) // => Option.none() + * ``` + * + * @see {@link findError} for filter-pipeline usage + * @see {@link getCause} to get the full Cause as an Option + * + * @category getters + * @since 4.0.0 + */ +const findErrorOption = _internal_effect_js__rspack_import_1/* .exitFindErrorOption */.lgw; +//# sourceMappingURL=Exit.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + N6: isFailure, + oJ: isSuccess, + rI: void_ +}); + + +}, +"./node_modules/effect/dist/Fiber.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); + + +const TypeId = "~effect/Fiber"; +const await_ = _internal_effect_js__rspack_import_0/* .fiberAwait */.zFM; + +/** + * Waits for all fibers in the provided iterable to complete and returns + * an array of their exit values. + * + * **When to use** + * + * Use when you need every fiber outcome as data, including failures and + * interruptions. + * + * **Details** + * + * The returned array is ordered like the input iterable. + * + * **Gotchas** + * + * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you + * want the first failed fiber to fail the returned Effect. + * + * **Example** (Awaiting multiple fiber exits) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.succeed(1)) + * const fiber2 = yield* Effect.forkChild(Effect.succeed(2)) + * return yield* Fiber.awaitAll([fiber1, fiber2]) + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [Exit.succeed(1), Exit.succeed(2)] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const awaitAll = _internal_effect_js__rspack_import_0/* .fiberAwaitAll */.C6p; +/** + * 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 + * + * @category combinators + * @since 2.0.0 + */ +const join = _internal_effect_js__rspack_import_0/* .fiberJoin */.D7p; +/** + * Waits for all fibers to succeed and returns their values in input order. + * + * **When to use** + * + * Use when you need every fiber to succeed and want the successful values + * rather than the `Exit` values. + * + * **Details** + * + * If any fiber fails, the returned `Effect` fails with that fiber's cause and + * stops waiting for additional results. This does not interrupt the remaining + * fibers. + * + * **Gotchas** + * + * A failure stops waiting, but it does not interrupt any other fibers. Use + * {@link interruptAll} separately when remaining fibers should be stopped. + * + * @see {@link awaitAll} for collecting every fiber outcome as an Exit + * + * @category combinators + * @since 2.0.0 + */ +const joinAll = _internal_effect_js__rspack_import_0/* .fiberJoinAll */.INJ; +/** + * Interrupts a fiber, causing it to stop executing and clean up any + * acquired resources. + * + * **When to use** + * + * Use when you need to cancel a forked fiber and wait for its cleanup to + * complete. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * Interruption is cooperative. A fiber can continue running while it is inside + * uninterruptible work or finalizers. + * + * **Example** (Interrupting a fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild( + * Effect.delay("1 second")(Effect.succeed(42)) + * ) + * yield* Fiber.interrupt(fiber) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAs} for specifying the interrupting fiber ID + * @see {@link await_ await} for observing the interrupted fiber's Exit + * + * @category interruption + * @since 2.0.0 + */ +const interrupt = _internal_effect_js__rspack_import_0/* .fiberInterrupt */.mKq; +/** + * Interrupts a fiber with a specific fiber ID as the interruptor. This allows + * tracking which fiber initiated the interruption. + * + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const targetFiber = yield* Effect.forkChild( + * Effect.delay("5 seconds")(Effect.succeed("task completed")) + * ) + * + * // Interrupt the fiber, specifying fiber ID 123 as the interruptor + * yield* Fiber.interruptAs(targetFiber, 123) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interrupt} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAs */.eGS; +/** + * Interrupts all fibers in the provided iterable, causing them to stop executing + * and clean up any acquired resources. + * + * **When to use** + * + * Use when you need to cancel several forked fibers and wait for their cleanup + * to complete. + * + * **Details** + * + * The current fiber is recorded as the interruptor. The returned Effect + * completes only after all interrupted fibers have completed. + * + * **Gotchas** + * + * Interruption is cooperative for each fiber. The returned Effect can wait for + * uninterruptible work and finalizers in any interrupted fiber. + * + * **Example** (Interrupting multiple fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const fiber1 = yield* Effect.forkChild(Effect.never) + * const fiber2 = yield* Effect.forkChild(Effect.never) + * const fiber3 = yield* Effect.forkChild(Effect.never) + * yield* Fiber.interruptAll([fiber1, fiber2, fiber3]) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAllAs} for specifying the interrupting fiber ID + * + * @category interruption + * @since 2.0.0 + */ +const interruptAll = _internal_effect_js__rspack_import_0/* .fiberInterruptAll */.DKo; +/** + * Interrupts all fibers in the provided iterable using the specified fiber ID as the + * interrupting fiber. This allows you to control which fiber is considered the source + * of the interruption, which can be useful for debugging and tracing. + * + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a controlling fiber + * const controllerFiber = yield* Effect.forkChild(Effect.succeed("controller")) + * + * const worker1 = yield* Effect.forkChild(Effect.never) + * const worker2 = yield* Effect.forkChild(Effect.never) + * + * yield* Fiber.interruptAllAs([worker1, worker2], controllerFiber.id) + * }) + * + * await Effect.runPromise(program) + * ``` + * + * @see {@link interruptAll} for using the current fiber as the interruptor + * + * @category interruption + * @since 2.0.0 + */ +const interruptAllAs = _internal_effect_js__rspack_import_0/* .fiberInterruptAllAs */.$MQ; +/** + * Checks whether a value is a Fiber. This is a type guard that can be used to + * determine if an unknown value is a Fiber instance. + * + * **When to use** + * + * Use when checking values at boundaries where an unknown value may be a + * runtime fiber. + * + * **Details** + * + * The check looks for the internal Fiber type ID marker and does not inspect + * the fiber's current state. + * + * **Example** (Checking for fibers) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * // Create a fiber + * const fiber = yield* Effect.forkChild(Effect.succeed(42)) + * + * // Test if values are fibers + * return [Fiber.isFiber(fiber), Fiber.isFiber("hello"), Fiber.isFiber(42), Fiber.isFiber(null)] + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => [true, false, false, false] + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isFiber = u => hasProperty(u, effect.FiberTypeId); +/** + * Returns the current fiber if called from within a fiber context, + * otherwise returns `undefined`. + * + * **When to use** + * + * Use when you need low-level runtime integrations that need access to the currently + * executing fiber. + * + * **Gotchas** + * + * This is a synchronous accessor, not an Effect. It returns `undefined` outside + * an active fiber runtime context. + * + * **Example** (Getting the current fiber) + * + * ```ts import.meta.vitest + * import { Effect, Fiber } from "effect" + * + * const program = Effect.gen(function*() { + * const current = Fiber.getCurrent() + * return current !== undefined + * }) + * + * const actual = await Effect.runPromise(program) + * actual // => true + * ``` + * + * @category getters + * @since 4.0.0 + */ +const getCurrent = _internal_effect_js__rspack_import_0/* .getCurrentFiber */.Iku; +/** + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. + * + * **Details** + * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion + * + * @category resource management + * @since 4.0.0 + */ +const runIn = _internal_effect_js__rspack_import_0/* .fiberRunIn */.vTQ; +//# sourceMappingURL=Fiber.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Tx: await_, + VO: runIn +}); + + +}, +"./node_modules/effect/dist/Filter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Result.js"); + + + + + +// ------------------------------------------------------------------------------------- +// Constructors +// ------------------------------------------------------------------------------------- +/** + * Creates a Filter from a function that returns either a `pass` or `fail` value. + * + * **Details** + * + * This is the primary constructor for creating custom filters. The function + * should return either `Result.succeed(value)` or `Result.fail(value)`. + * + * **Example** (Creating custom filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create a filter for positive numbers + * const positiveFilter = Filter.make((n: number) => n > 0 ? Result.succeed(n) : Result.fail(n)) + * + * // Create a filter that transforms strings to uppercase + * const uppercaseFilter = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * positiveFilter(1) // => Result.succeed(1) + * uppercaseFilter("ok") // => Result.succeed("OK") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const make = f => f; +/** + * Creates an effectful Filter from a function that returns an Effect. + * + * **Details** + * + * This constructor is used when the filtering operation needs to perform + * effectful computations, such as async operations, error handling, or accessing + * services from the environment. + * + * **Example** (Creating effectful filters) + * + * ```ts import.meta.vitest + * import { Effect, Filter, Result } from "effect" + * + * // Create an effectful filter that validates async + * const asyncValidate = Filter.makeEffect((id: string) => + * Effect.gen(function*() { + * const isValid = yield* Effect.succeed(id.length > 0) + * return isValid ? Result.succeed(id) : Result.fail(id) + * }) + * ) + * + * await Effect.runPromise(asyncValidate("id")) // => Result.succeed("id") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeEffect = f => f; +/** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping + * @since 4.0.0 + */ +const mapFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => input => Result.mapError(self(input), f)))); +const try_ = f => input => { + try { + return Result.succeed(f(input)); + } catch { + return Result.fail(input); + } +}; + +/** + * Creates a Filter from a predicate or refinement function. + * + * **Details** + * + * This is a convenient way to create filters from boolean-returning functions. + * When the predicate returns true, the input value is passed through unchanged. + * When it returns false, the `fail` type is returned. + * + * **Example** (Creating filters from predicates) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * // Create filter from predicate + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const nonEmptyStrings = Filter.fromPredicate((s: string) => s.length > 0) + * + * // Type refinement + * const isString = Filter.fromPredicate((x: unknown): x is string => + * typeof x === "string" + * ) + * positiveNumbers(1) // => Result.succeed(1) + * nonEmptyStrings("") // => Result.fail("") + * isString("ok") // => Result.succeed("ok") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicate = predicate => input => predicate(input) ? _Result_js__rspack_import_0/* .succeed */.Py(input) : _Result_js__rspack_import_0/* .fail */.fJ(input); +/** + * Creates a `Filter` from a function that returns an `Option`; `Some(value)` + * passes with `value`, and `None` fails with the original input. + * + * @category constructors + * @since 4.0.0 + */ +const fromPredicateOption = predicate => input => { + const o = predicate(input); + return o._tag === "None" ? Result.fail(input) : Result.succeed(o.value); +}; +/** + * Converts a Filter into a predicate function. + * + * **When to use** + * + * Use to reuse a `Filter` with APIs that accept only boolean predicates when + * the pass and fail payloads are not needed. + * + * @see {@link toOption} for keeping passed values and discarding failure values + * @see {@link toResult} for preserving both pass and failure values + * + * @category converting + * @since 4.0.0 + */ +const toPredicate = self => input => !Result.isFailure(self(input)); +/** + * A predefined filter that only passes through string values. + * + * **Example** (Filtering strings) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.string("hello") // => Result.succeed("hello") + * Filter.string(42) // => Result.fail(42) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const string = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isString */.Kg); +/** + * Creates a `Filter` that passes only values strictly equal to the specified + * value using JavaScript `===` comparison. + * + * **When to use** + * + * Use when you need a `Filter` that accepts only the exact primitive value or + * object reference using JavaScript strict equality in a `Filter` / `Result` + * pipeline. + * + * **Gotchas** + * + * `NaN` never passes, even when the expected value is `NaN`, and objects pass + * only when they are the same reference. + * + * @see {@link equals} for structural equality when distinct values with equal + * contents should pass + * + * @category constructors + * @since 4.0.0 + */ +const equalsStrict = value => u => u === value ? Result.succeed(value) : Result.fail(u); +/** + * Creates a `Filter` that passes inputs whose `has(key)` method returns + * `true` for the specified key. + * + * **When to use** + * + * Use to keep inputs that expose a `has` method, such as `Set` or `Map`, when + * they contain a required key. + * + * @see {@link fromPredicate} for custom predicate filters or inputs without a + * `has` method + * @see {@link Predicate.hasProperty} for guarding property presence instead of + * calling an input's `has` method + * + * @category constructors + * @since 4.0.0 + */ +const has = key => input => input.has(key) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that only passes instances of the given constructor. + * + * **When to use** + * + * Use to narrow unknown input to values created by a specific JavaScript + * constructor while keeping the result in the `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when the input satisfies `instanceof constructor`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This uses JavaScript `instanceof` semantics, including prototype-chain and + * realm behavior. + * + * @see {@link fromPredicate} for custom predicate-based narrowing + * + * @category constructors + * @since 4.0.0 + */ +const instanceOf = constructor => u => u instanceof constructor ? Result.succeed(u) : Result.fail(u); +/** + * A predefined filter that only passes through number values. + * + * **Example** (Filtering numbers) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * Filter.number(42) // => Result.succeed(42) + * Filter.number("42") // => Result.fail("42") + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const number = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isNumber */.Et); +/** + * A predefined filter that only passes through boolean values. + * + * **When to use** + * + * Use when accepting an unknown input only if it is already a boolean and you + * want a `Filter` result rather than a plain predicate result. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBoolean)`, so `true` and `false` + * succeed and non-booleans fail with the original input. + * + * @see {@link Predicate.isBoolean} for the underlying guard + * @see {@link fromPredicate} for custom predicate-based filters + * + * @category constructors + * @since 4.0.0 + */ +const boolean = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBoolean */.Lm); +/** + * A predefined filter that only passes through `bigint` primitive values. + * + * **When to use** + * + * Use to keep primitive big integer values from unknown input while staying in + * the composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBigInt)`, so values where + * `typeof input === "bigint"` succeed and all other inputs fail with the + * original input. + * + * **Gotchas** + * + * This filter does not coerce numbers or strings; `1n` passes while `1` fails. + * + * @see {@link number} for JavaScript `number` values + * @see {@link Predicate.isBigInt} for the underlying guard + * + * @category constructors + * @since 4.0.0 + */ +const bigint = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isBigInt */.sI); +/** + * A predefined filter that only passes through Symbol values. + * + * @category constructors + * @since 4.0.0 + */ +const symbol = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isSymbol */.Bm); +/** + * A predefined filter that only passes through Date objects. + * + * **When to use** + * + * Use when you need to narrow unknown input to JavaScript `Date` instances with + * a reusable `Filter`. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isDate)`, so passing values return + * `Result.succeed(input)` and failing values return `Result.fail(input)`. + * + * **Gotchas** + * + * The check uses `instanceof Date`, so invalid `Date` objects still pass; the + * filter does not validate the timestamp. + * + * @see {@link Predicate.isDate} for the underlying guard + * @see {@link instanceOf} for constructor-based filtering + * @see {@link fromPredicate} for custom date checks + * + * @category constructors + * @since 4.0.0 + */ +const date = /*#__PURE__*/fromPredicate(_Predicate_js__rspack_import_1/* .isDate */.$P); +/** + * Creates a filter that checks if an input is tagged with a specific tag. + * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors + * @since 4.0.0 + */ +const tagged = function () { + return arguments.length === 0 ? taggedImpl : taggedImpl(arguments[0]); +}; +const taggedImpl = tag => input => Predicate.isTagged(input, tag) ? Result.succeed(input) : Result.fail(input); +/** + * Creates a filter that extracts a reason from a tagged error. + * + * @category constructors + * @since 4.0.0 + */ +const reason = function () { + return arguments.length === 0 ? reasonImpl : reasonImpl(arguments[0], arguments[1]); +}; +const reasonImpl = (tag, reasonTag) => input => { + if (Predicate.isTagged(input, tag) && Predicate.hasProperty(input, "reason") && Predicate.isTagged(input.reason, reasonTag)) { + return Result.succeed(input.reason); + } + return Result.fail(input); +}; +/** + * Creates a filter that only passes values equal to the specified value using structural equality. + * + * **When to use** + * + * Use to accept inputs that are structurally equal to a known expected value + * while staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Delegates to `Equal.equals`. On success it returns `Result.succeed(value)`; + * on failure it returns `Result.fail(input)`. + * + * @see {@link equalsStrict} for JavaScript `===` matching instead of structural + * equality + * @see {@link Equal.equals} for the underlying structural equality semantics + * + * @category constructors + * @since 4.0.0 + */ +const equals = value => u => Equal.equals(u, value) ? Result.succeed(value) : Result.fail(u); +/** + * Combines two filters with logical OR semantics. + * + * @category combinators + * @since 4.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => input => { + const selfResult = self(input); + return Result.isSuccess(selfResult) ? selfResult : that(input); +}))); +/** + * Combines two filters and applies a function to their results. + * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * + * Both filters must succeed (not return `fail`) for the combination to succeed. + * If both filters pass, their outputs are combined using the provided function. + * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators + * @since 4.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (left, right, f) => input => { + const leftResult = left(input); + if (Result.isFailure(leftResult)) return leftResult; + const rightResult = right(input); + if (Result.isFailure(rightResult)) return rightResult; + return Result.succeed(f(leftResult.success, rightResult.success)); +}))); +/** + * Combines two filters into a tuple of their results. + * + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) + * positiveAndEven(2) // => Result.succeed([2, 2]) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (leftResult, rightResult) => [leftResult, rightResult])))); +/** + * Combines two filters but only returns the result of the left filter. + * + * **Example** (Keeping the left filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const evenNumbers = Filter.fromPredicate((n: number) => n % 2 === 0) + * + * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) + * positiveEven(2) // => Result.succeed(2) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andLeft = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, leftResult => leftResult)))); +/** + * Combines two filters but only returns the result of the right filter. + * + * **Example** (Keeping the right filter result) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const positiveNumbers = Filter.fromPredicate((n: number) => n > 0) + * const doubleNumbers = Filter.make((n: number) => + * n > 0 ? Result.succeed(n * 2) : Result.fail(n) + * ) + * + * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) + * positiveDoubled(2) // => Result.succeed(4) + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const andRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => zipWith(left, right, (_, rightResult) => rightResult)))); +/** + * Composes two filters sequentially, feeding the output of the first into the second. + * + * **Example** (Composing filters) + * + * ```ts import.meta.vitest + * import { Filter, Result } from "effect" + * + * const stringFilter = Filter.string + * const nonEmptyUpper = Filter.make((s: string) => + * s.length > 0 ? Result.succeed(s.toUpperCase()) : Result.fail(s) + * ) + * + * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) + * stringToUpper("hello") // => Result.succeed("HELLO") + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (left, right) => input => { + const leftOut = left(input); + if (Result.isFailure(leftOut)) return leftOut; + return right(leftOut.success); +}))); +/** + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. + * + * **Details** + * + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. + * + * @category combinators + * @since 4.0.0 + */ +const composePassthrough = /*#__PURE__*/(0,_Function_js__rspack_import_2/* .dual */.XY)(2, (left, right) => input => { + const leftOut = left(input); + if (_Result_js__rspack_import_0/* .isFailure */.N6(leftOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + const rightOut = right(leftOut.success); + if (_Result_js__rspack_import_0/* .isFailure */.N6(rightOut)) return _Result_js__rspack_import_0/* .fail */.fJ(input); + return rightOut; +}); +/** + * Converts a `Filter` into a function that returns `Some` for passed values + * and `None` for filtered-out values. + * + * **When to use** + * + * Use when adapting a `Filter` to `Option`-based code where passed values + * become `Some` and filtered-out inputs become `None`. + * + * @see {@link toResult} for keeping the filter failure value + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toOption = self => input => { + const result = self(input); + return _Result_js__rspack_import_0/* .isFailure */.N6(result) ? _Option_js__rspack_import_3.none() : _Option_js__rspack_import_3.some(result.success); +}; +/** + * Converts a `Filter` into a function that returns the underlying + * `Result.Result` for each input. + * + * **When to use** + * + * Use to adapt a `Filter` to APIs that expect a plain function returning + * `Result`, while preserving both the pass value and the failure value. + * + * @see {@link toOption} for keeping only passed values + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting + * @since 4.0.0 + */ +const toResult = self => input => { + const result = self(input); + return Result.isFailure(result) ? Result.fail(result.failure) : Result.succeed(result.success); +}; +//# sourceMappingURL=Filter.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Bh: composePassthrough, + zL: toOption +}); + + +}, +"./node_modules/effect/dist/Formatter.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.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. + * + * @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. + * - 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} + * @category formatting + * @since 2.0.0 + */ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = 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) { + 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 (_Redactable_js__rspack_import_0/* .symbolRedactable */.uC in v) { + output = recur((0,_Redactable_js__rspack_import_0/* .getRedacted */.f6)(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 && _Predicate_js__rspack_import_1/* .hasProperty */.i5(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 ? `${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(v[k], d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map(k => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(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 an array of property keys as a bracket-notation path string. + * + * @internal + */ +function formatPath(path) { + return path.map(key => `[${formatPropertyKey(key)}]`).join(""); +} +/** + * 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]"; + } +} +/** + * Stringifies a value to JSON safely, silently dropping circular references. + * + * **When to use** + * + * Use when you need valid JSON output, unlike `format`, and the input may + * contain circular references that should be silently omitted rather than + * throwing a `TypeError`. + * + * **Details** + * + * Uses `JSON.stringify` internally with a replacer that tracks the current + * object ancestry. Circular references are replaced with `undefined`, which + * omits them from object output. `Redactable` values are automatically redacted + * before serialization. `BigInt` values are stringified with an `n` suffix. + * Values not supported by JSON otherwise follow standard `JSON.stringify` + * behavior. The `space` parameter controls indentation and defaults to `0`. + * + * **Gotchas** + * + * When the root input is `undefined`, a symbol, or a function, `formatJson` + * returns `"null"` instead of the `undefined` returned by `JSON.stringify`. + * Nested values retain standard `JSON.stringify` behavior. + * + * **Example** (Formatting compact JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * Formatter.formatJson({ name: "Alice", age: 30 }) // => "{\"name\":\"Alice\",\"age\":30}" + * ``` + * + * **Example** (Handling circular references) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const obj: any = { name: "test" } + * obj.self = obj + * Formatter.formatJson(obj) // => "{\"name\":\"test\"}" + * ``` + * + * **Example** (Pretty-printed JSON) + * + * ```ts import.meta.vitest + * import { Formatter } from "effect" + * + * const output = Formatter.formatJson({ name: "Alice", age: 30 }, { space: 2 }) + * output // => "{\n \"name\": \"Alice\",\n \"age\": 30\n}" + * ``` + * + * @see {@link format} + * @see {@link Formatter} + * @category serialization + * @since 4.0.0 + */ +function formatJson(input, options) { + const ancestors = []; + return JSON.stringify(input, function (key, value) { + const original = Object.getOwnPropertyDescriptor(this, key)?.value; + const redacted = _Predicate_js__rspack_import_1/* .hasProperty */.i5(original, _Redactable_js__rspack_import_0/* .symbolRedactable */.uC) ? (0,_Redactable_js__rspack_import_0/* .redact */.E$)(original) : (0,_Redactable_js__rspack_import_0/* .redact */.E$)(value); + if (typeof redacted === "bigint") { + return format(redacted); + } + if (typeof redacted !== "object" || redacted === null) { + return redacted; + } + while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) { + ancestors.pop(); + } + if (ancestors.includes(redacted)) { + return undefined; // circular reference + } + ancestors.push(redacted); + return redacted; + }, options?.space) ?? "null"; +} +//# sourceMappingURL=Formatter.js.map +__webpack_require__.d(__webpack_exports__, { + GP: () => (format), + IB: () => (formatJson) +}); + + +}, +"./node_modules/effect/dist/Function.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { + +/** + * 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 + * ``` + * + * @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) { + // @ts-expect-error + return body.apply(this, arguments); + } + const args = arguments; + return function (self) { + return body(self, ...args); + }; + }; + } +}; +/** + * Applies a function to a given value. + * + * **When to use** + * + * Use to pass a fixed value into a unary function, especially when the function + * is the value flowing through `pipe`. + * + * **Details** + * + * `apply(a)(f)` is equivalent to `f(a)`. + * + * **Example** (Applying an argument to a function) + * + * ```ts import.meta.vitest + * import { Function, pipe, String } from "effect" + * + * pipe(String.length, Function.apply("hello")) // => 5 + * ``` + * + * @see {@link pipe} for building left-to-right pipelines + * + * @category combinators + * @since 2.0.0 + */ +const apply = a => self => self(a); +/** + * 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 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const identity = a => a; +/** + * Ensures that the type of an expression matches some type, + * without changing the resulting type of that expression. + * + * **When to use** + * + * Use to check assignability while preserving the expression's precise inferred + * type. + * + * **Example** (Checking an expression against a type) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const test1 = Function.satisfies()(5 as const) // => 5 + * // ^? const test: 5 + * // @ts-expect-error + * const test2 = Function.satisfies()(5) + * // ^? Argument of type 'number' is not assignable to parameter of type 'string' + * ``` + * + * @see {@link cast} for changing only the static TypeScript type + * + * @category utility types + * @since 2.0.0 + */ +const satisfies = () => b => b; +/** + * Returns the input value with a different static type. + * + * **When to use** + * + * Use when you need an explicit type-level cast and accept that the value is + * returned unchanged at runtime. + * + * **Gotchas** + * + * This is a type-level cast only; it performs no runtime validation or + * conversion. + * + * @see {@link satisfies} for checking assignability without changing the resulting type + * + * @category utility types + * @since 4.0.0 + */ +const cast = (/* unused pure expression or super */ null && (identity)); +/** + * 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 + * ``` + * + * @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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constTrue = /*#__PURE__*/constant(true); +/** + * Returns `false` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `false` on every invocation. + * + * **Example** (Returning false from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constFalse() // => false + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constFalse = /*#__PURE__*/constant(false); +/** + * Returns `null` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `null` on every invocation. + * + * **Example** (Returning null from a thunk) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.constNull() // => null + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constNull = /*#__PURE__*/constant(null); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constUndefined = /*#__PURE__*/constant(undefined); +/** + * 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 + * ``` + * + * @category constants + * @since 2.0.0 + */ +const constVoid = constUndefined; +/** + * Reverses the order of arguments for a curried function. + * + * **When to use** + * + * Use to adapt a curried function when its argument groups need to be supplied + * in the opposite order. + * + * **Example** (Flipping curried arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const f = (a: number) => (b: string) => a - b.length + * + * Function.flip(f)("aaa")(2) // => -1 + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const flip = f => (...b) => (...a) => f(...a)(...b); +/** + * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. + * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. + * + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const increment = (n: number) => n + 1 + * const square = (n: number) => n * n + * + * Function.compose(increment, square)(2) // => 9 + * ``` + * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => bc(ab(a))))); +/** + * Marks an impossible branch by accepting a `never` value and returning any + * type. + * + * **When to use** + * + * Use when you need a return value in a branch that exhaustive checks prove + * cannot be reached. + * + * **Gotchas** + * + * Calling `absurd` throws, because a value of type `never` should be + * impossible at runtime. + * + * **Example** (Handling impossible values) + * + * ```ts import.meta.vitest + * import { absurd } from "effect" + * + * const handleNever = (value: never) => { + * return absurd(value) // This will throw an error if called + * } + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const absurd = _ => { + throw new Error("Called `absurd` function which should be uncallable"); +}; +/** + * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. + * + * **When to use** + * + * Use to adapt a multi-argument function so it accepts one tuple argument. + * + * **Example** (Converting arguments to a tuple) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const sumTupled = Function.tupled((x: number, y: number): number => x + y) + * + * sumTupled([1, 2]) // => 3 + * ``` + * + * @see {@link untupled} for adapting a tuple-argument function back to multiple arguments + * + * @category combinators + * @since 2.0.0 + */ +const tupled = f => a => f(...a); +/** + * Converts a tupled function back to an uncurried function. + * + * **When to use** + * + * Use to adapt a tuple-argument function so it accepts multiple arguments. + * + * **Example** (Converting a tuple to arguments) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * const getFirst = Function.untupled((tuple: [A, B]): A => tuple[0]) + * + * getFirst(1, 2) // => 1 + * ``` + * + * @see {@link tupled} for adapting a multi-argument function to one tuple argument + * + * @category combinators + * @since 2.0.0 + */ +const untupled = f => (...a) => f(a); +function pipe(a, ...args) { + return pipeArguments(a, args); +} +function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) { + switch (arguments.length) { + case 1: + return ab; + case 2: + return function () { + return bc(ab.apply(this, arguments)); + }; + case 3: + return function () { + return cd(bc(ab.apply(this, arguments))); + }; + case 4: + return function () { + return de(cd(bc(ab.apply(this, arguments)))); + }; + case 5: + return function () { + return ef(de(cd(bc(ab.apply(this, arguments))))); + }; + case 6: + return function () { + return fg(ef(de(cd(bc(ab.apply(this, arguments)))))); + }; + case 7: + return function () { + return gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))); + }; + case 8: + return function () { + return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))); + }; + case 9: + return function () { + return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))))); + }; + } + return; +} +/** + * Creates a compile-time placeholder for a value of any type. + * + * **When to use** + * + * Use as a temporary typed placeholder while developing incomplete code. + * + * **Gotchas** + * + * `hole` is intended for temporary development use. If the placeholder is + * evaluated at runtime, it throws. + * + * **Example** (Creating a development placeholder) + * + * ```ts import.meta.vitest + * import { hole } from "effect" + * + * // Intentionally not called: `hole` throws if the placeholder is evaluated. + * const buildUser = (id: number): { readonly id: number; readonly name: string } => ({ + * id, + * name: hole() + * }) + * + * ``` + * + * @category utility types + * @since 2.0.0 + */ +const hole = /*#__PURE__*/(/* unused pure expression or super */ null && (cast(absurd))); +/** + * Returns the second argument and discards the first. The SK combinator is + * a fundamental combinator in the lambda calculus and the SKI combinator + * calculus. + * + * **When to use** + * + * Use to discard the first argument and return the second argument. + * + * **Example** (Discarding the first argument) + * + * ```ts import.meta.vitest + * import { Function } from "effect" + * + * Function.SK(0, "hello") // => "hello" + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const SK = (_, b) => b; +/** + * Creates a memoized function whose input is an object, caching results by + * object identity. + * + * **When to use** + * + * Use to reuse the result of a synchronous computation whose output is stable + * for a given object reference. + * + * **Details** + * + * Each memoized wrapper owns a private `WeakMap` keyed by object identity. + * + * **Gotchas** + * + * `undefined` is reserved to represent a cache miss and is therefore not + * supported as a return value. + * + * Structurally equal objects do not share cache entries. If the same object is + * mutated after its first call, later calls still return the cached result for + * that reference. + * + * @category caching + * @since 4.0.0 + */ +function memoize(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + return result; + }; +} +/** + * Creates a memoized idempotent object transformation that caches both inputs + * and their outputs by object identity. + * + * **When to use** + * + * Use when an object transformation is idempotent and its output can be safely + * reused as a fixed point. + * + * **Details** + * + * After computing an input, the returned function caches both the input and + * the output. Calling it with either reference returns the output without + * invoking the supplied function again. + * + * **Gotchas** + * + * The returned function treats each computed output as a fixed point. If + * applying the supplied function to an output would produce an observably + * different value, this memoization changes that behavior. + * + * @see {@link memoize} for memoizing functions without an idempotence requirement + * @category caching + * @since 4.0.0 + */ +function memoizeIdempotent(f) { + const cache = new WeakMap(); + return a => { + const cached = cache.get(a); + if (cached !== undefined) return cached; + const result = f(a); + cache.set(a, result); + cache.set(result, result); + return result; + }; +} +//# sourceMappingURL=Function.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + D_: identity, + MN: constUndefined, + XR: constNull, + XY: dual, + Yi: constVoid, + dY: constant, + f4: constFalse, + ue: constTrue +}); + + +}, +"./node_modules/effect/dist/Hash.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/equal.js"); +/* import */ var _Predicate_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Predicate.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. + * + * @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 + * + * @category symbols + * @since 2.0.0 + */ +const symbol = "~effect/interfaces/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 + * ``` + * + * @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 "boolean": + return string(String(self)); + case "symbol": + return string(String(self)); + case "string": + return string(self); + case "undefined": + return string("undefined"); + case "function": + case "object": + { + if (self === null) { + return string("null"); + } 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 (_internal_equal_js__rspack_import_0/* .byReferenceInstances.has */.J.has(self)) { + return random(self); + } + if (hashCache.has(self)) { + return hashCache.get(self); + } + const h = withVisitedTracking(self, () => { + if (isHash(self)) { + return self[symbol](); + } else if (typeof self === "function") { + return random(self); + } else if (self instanceof DataView) { + return array(new Uint8Array(self.buffer, self.byteOffset, self.byteLength)); + } else if (Array.isArray(self) || ArrayBuffer.isView(self)) { + return array(self); + } else if (self instanceof Map) { + return hashMap(self); + } else if (self instanceof Set) { + return hashSet(self); + } + return structure(self); + }); + hashCache.set(self, h); + return h; + } + } + default: + throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`); + } +}; +/** + * 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" + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const random = self => { + if (!randomHashCache.has(self)) { + randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))); + } + return randomHashCache.get(self); +}; +/** + * 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 both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **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 + * + * @category hashing + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => self * 53 ^ b); +/** + * 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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const optimize = n => n & 0xbfffffff | n >>> 1 & 0x40000000; +/** + * 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 the Hash symbol property, + * indicating that it can provide its own hash value implementation. + * + * **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 + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isHash = u => (0,_Predicate_js__rspack_import_2/* .hasProperty */.i5)(u, symbol); +/** + * Computes a hash value for a number. + * + * **When to use** + * + * Use to hash a JavaScript number with Effect's numeric hash semantics. + * + * **Details** + * + * This function creates a hash value for numeric inputs, handling special cases + * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution + * of hash values across different numeric inputs. + * + * **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 + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const number = n => { + if (n !== n) { + return string("NaN"); + } + if (n === Infinity) { + return string("Infinity"); + } + if (n === -Infinity) { + return string("-Infinity"); + } + let h = n | 0; + if (h !== n) { + h ^= n * 0xffffffff; + } + while (n > 0xffffffff) { + h ^= n /= 0xffffffff; + } + return optimize(h); +}; +/** + * 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 + * ``` + * + * @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 // => -590673747 + * hash2 // => 284850673 + * + * const person2 = { name: "John", age: 30, city: "Boston" } + * const hash3 = Hash.structureKeys(person2, ["name", "age"]) + * hash1 === hash3 // => true + * ``` + * + * @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) // => -590673747 + * Hash.structure(obj2) // => -590160631 + * Hash.structure(obj3) // => -590673747 + * Hash.structure(obj1) === Hash.structure(obj3) // => true + * ``` + * + * @category hashing + * @since 2.0.0 + */ +const structure = o => structureKeys(o, (0,_internal_equal_js__rspack_import_0/* .getAllObjectKeys */.X)(o)); +const iterableWith = (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** + * + * The implementation folds element hashes from the seed `6151` with XOR and + * then optimizes the final hash. + * + * **Gotchas** + * + * A hash is not an equality proof. Because this implementation uses XOR, + * reordered inputs can produce the same 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) // => 6151 + * Hash.array(arr2) // => 6151 + * Hash.array(arr3) // => 6151 + * Hash.array(arr1) === Hash.array(arr2) // => true + * Hash.array(arr1) === Hash.array(arr3) // => true + * ``` + * + * @see {@link hash} for the general-purpose hash dispatcher + * + * @category hashing + * @since 2.0.0 + */ +const array = /*#__PURE__*/iterableWith(6151, hash); +const hashMap = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const hashSet = /*#__PURE__*/iterableWith(/*#__PURE__*/string("Set"), hash); +const randomHashCache = /*#__PURE__*/new WeakMap(); +const hashCache = /*#__PURE__*/new WeakMap(); +const visitedObjects = /*#__PURE__*/new WeakSet(); +function withVisitedTracking(obj, fn) { + if (visitedObjects.has(obj)) { + return string("[Circular]"); + } + visitedObjects.add(obj); + const result = fn(); + visitedObjects.delete(obj); + return result; +} +//# sourceMappingURL=Hash.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + HR: symbol, + QK: structure, + YO: array, + Yj: string, + ai: number, + kg: combine, + tW: hash, + uN: structureKeys, + yT: random +}); + + +}, +"./node_modules/effect/dist/Inspectable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/** + * Controls how values appear in logs and debugging output. + * + * Effect data types use `Inspectable` to provide stable string, JSON, and + * Node.js inspection output. This keeps custom values readable in logs, REPLs, + * test failures, and diagnostics. This module defines the Node inspect symbol, + * the `Inspectable` interface, safe conversion helpers, and shared prototype or + * class implementations for custom values. + * + * @since 2.0.0 + */ + + + +/** + * 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)" + * ``` + * + * @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 + * + * @category converting + * @since 4.0.0 + */ +const toJson = input => { + try { + input = (0,_Redactable_js__rspack_import_0/* .redact */.E$)(input); + if (_Predicate_js__rspack_import_1/* .hasProperty */.i5(input, "toJSON") && _Predicate_js__rspack_import_1/* .isFunction */.Tn(input["toJSON"]) && input["toJSON"].length === 0) { + return input.toJSON(); + } else if (Array.isArray(input)) { + return input.map(toJson); + } + return input; + } catch { + return "[toJSON threw]"; + } +}; +/** + * Converts an unknown value to a string for diagnostics. + * + * **When to use** + * + * Use to produce a diagnostic string from a value whose runtime type is unknown. + * + * **Details** + * + * Strings are returned unchanged. Objects are formatted as JSON using the + * provided whitespace setting when possible, and values that cannot be + * formatted are converted with `String`. + * + * @category converting + * @since 2.0.0 + */ +const toStringUnknown = (u, whitespace = 2) => { + if (typeof u === "string") { + return u; + } + try { + return typeof u === "object" ? (0,_Formatter_js__rspack_import_2/* .formatJson */.IB)(u, { + space: whitespace + }) : (0,_Formatter_js__rspack_import_2/* .format */.GP)(u, { + space: whitespace + }); + } catch { + return String(u); + } +}; +/** + * A base prototype object that implements the {@link Inspectable} interface. + * + * **When to use** + * + * Use as a prototype for plain objects that should share standard inspectable behavior. + * + * **Details** + * + * This object provides default implementations for the {@link Inspectable} methods. + * It can be used as a prototype for objects that want to be inspectable, + * or as a mixin to add inspection capabilities to existing objects. + * + * **Example** (Using the base inspectable prototype) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * // Use as prototype + * const myObject = Object.create(Inspectable.BaseProto) + * myObject.name = "example" + * myObject.value = 42 + * + * myObject.toString() // => "\"[toJSON threw]\"" + * + * // Or extend in a constructor + * function MyClass(this: any, name: string) { + * this.name = name + * } + * MyClass.prototype = Object.create(Inspectable.BaseProto) + * MyClass.prototype.constructor = MyClass + * ``` + * + * @category prototypes + * @since 2.0.0 + */ +const BaseProto = (/* unused pure expression or super */ null && ({ + toJSON() { + return toJson(this); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + }, + toString() { + return format(this.toJSON()); + } +})); +/** + * Provides an abstract base class that implements the Inspectable interface. + * + * **When to use** + * + * Use as a base class for inspectable objects that define their own JSON representation. + * + * **Details** + * + * This class provides a convenient way to create inspectable objects by extending it. + * Subclasses only need to implement the `toJSON()` method, and they automatically + * get proper `toString()` and Node.js inspection support. + * + * **Example** (Extending the inspectable base class) + * + * ```ts import.meta.vitest + * import { Inspectable } from "effect" + * + * class User extends Inspectable.Class { + * constructor( + * public readonly id: number, + * public readonly name: string, + * public readonly email: string + * ) { + * super() + * } + * + * toJSON() { + * return { + * _tag: "User", + * id: this.id, + * name: this.name, + * email: this.email + * } + * } + * } + * + * const user = new User(1, "Alice", "alice@example.com") + * user.toString() // => "{\"_tag\":\"User\",\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\"}" + * user[Inspectable.NodeInspectSymbol]() // => { _tag: "User", id: 1, name: "Alice", email: "alice@example.com" } + * ``` + * + * @category models + * @since 2.0.0 + */ +class Class { + /** + * Node.js custom inspection method. + * + * **When to use** + * + * Use to expose the class JSON representation to Node.js inspection. + * + * @since 2.0.0 + */ + [NodeInspectSymbol]() { + return this.toJSON(); + } + /** + * Returns a formatted string representation of this object. + * + * **When to use** + * + * Use to format the class JSON representation as a string. + * + * @since 2.0.0 + */ + toString() { + return format(this.toJSON()); + } +} +//# sourceMappingURL=Inspectable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + FX: NodeInspectSymbol, + ZK: toStringUnknown, + aB: toJson +}); + + +}, +"./node_modules/effect/dist/Iterable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Predicate_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/** + * Works with JavaScript values that implement `[Symbol.iterator]`. + * + * Iterables include arrays, strings, generators, sets, and custom lazy + * sequences. The helpers in this module let code transform, search, group, and + * fold iterable values while preserving the input as an iterable instead of + * forcing an array first. + * + * @since 2.0.0 + */ + + + + + + + +/** + * Creates an iterable by applying a function to consecutive integers. + * + * **Details** + * + * The function is called with each index starting from `0`. If no length is + * specified, the iterable is infinite. This is useful for generating + * sequences, patterns, or any indexed data. + * + * **Example** (Generating values by index) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Generate first 5 even numbers + * const evens = Iterable.makeBy((n) => n * 2, { length: 5 }) + * Array.from(evens) // => [0, 2, 4, 6, 8] + * + * // Generate squares + * const squares = Iterable.makeBy((n) => n * n, { length: 4 }) + * Array.from(squares) // => [0, 1, 4, 9] + * + * // Infinite sequence (be careful when consuming!) + * const naturals = Iterable.makeBy((n) => n) + * const first10 = Iterable.take(naturals, 10) + * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeBy = (f, options) => { + const max = options?.length !== undefined ? Math.max(1, Math.floor(options.length)) : Infinity; + return { + [Symbol.iterator]() { + let i = 0; + return { + next() { + if (i < max) { + return { + value: f(i++), + done: false + }; + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns an iterable of integers starting at `start` and increasing by `1`. + * + * **Details** + * + * When `end` is provided and `start <= end`, both endpoints are included. When + * `end` is omitted, the iterable is unbounded. When `start > end`, the + * iterable contains only `start`. + * + * **Example** (Creating a range) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.range(1, 3)) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const range = (start, end) => { + if (end === undefined) { + return makeBy(i => start + i); + } + return makeBy(i => start + i, { + length: start <= end ? end - start + 1 : 1 + }); +}; +/** + * Returns a `Iterable` containing a value repeated the specified number of times. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Repeating a value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.replicate("a", 3)) // => ["a", "a", "a"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const replicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (a, n) => makeBy(() => a, { + length: n +})))); +/** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value + * @category constructors + * @since 4.0.0 + */ +const repeat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => flatten(makeBy(() => self, { + length: n +}))))); +/** + * Repeats an iterable without an upper bound. + * + * **When to use** + * + * Use to cycle a reusable iterable without an upper bound when a downstream + * consumer controls how many values are taken. + * + * **Gotchas** + * + * The returned iterable is lazy and should usually be bounded with `take` or + * another terminating consumer before materializing it. + * + * @see {@link repeat} for repeating an iterable a specific number of times + * @see {@link take} for bounding the unbounded result before materializing it + * + * @category constructors + * @since 4.0.0 + */ +const forever = self => repeat(self, Infinity); +/** + * Takes a record and returns an Iterable of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Array.from(Iterable.fromRecord(x)) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const fromRecord = self => ({ + *[Symbol.iterator]() { + for (const key in self) { + if (Object.hasOwn(self, key)) { + yield [key, self[key]]; + } + } + } +}); +/** + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 3, 4] + * const withOne = Iterable.prepend(numbers, 1) + * Array.from(withOne) // => [1, 2, 3, 4] + * + * // Works with any iterable + * const letters = "abc" + * const withZ = Iterable.prepend(letters, "z") + * Array.from(withZ) // => ["z", "a", "b", "c"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prepend = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, head) => prependAll(self, [head])))); +/** + * Prepends the specified prefix iterable to the beginning of the specified iterable. + * + * **Example** (Prepending another iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.prependAll([1, 2], ["a", "b"])) // => ["a", "b", 1, 2] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const prependAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => appendAll(that, self)))); +/** + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4] + * ``` + * + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining + * @since 2.0.0 + */ +const append = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, last) => appendAll(self, [last])))); +/** + * Concatenates two iterables, combining their elements. + * + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6] + * + * // Works with different iterable types + * const numbers = [1, 2] + * const letters = "abc" + * const mixed = Iterable.appendAll(numbers, letters) + * Array.from(mixed) // => [1, 2, "a", "b", "c"] + * + * // Lazy evaluation - only consumes what's needed + * const infinite = Iterable.range(1) + * const finite = [0, -1, -2] + * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2] + * ``` + * + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining + * @since 2.0.0 + */ +const appendAll = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => ({ + [Symbol.iterator]() { + const iterA = self[Symbol.iterator](); + let doneA = false; + let iterB; + return { + next() { + if (!doneA) { + const r = iterA.next(); + if (r.done) { + doneA = true; + iterB = that[Symbol.iterator](); + return iterB.next(); + } + return r; + } + return iterB.next(); + } + }; + } +})))); +/** + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Running sum of numbers + * const numbers = [1, 2, 3, 4, 5] + * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n) + * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15] + * + * // Build strings progressively + * const letters = ["a", "b", "c"] + * const progressive = Iterable.scan(letters, "", (acc, letter) => acc + letter) + * Array.from(progressive) // => ["", "a", "ab", "abc"] + * + * // Track maximum values seen so far + * const values = [3, 1, 4, 1, 5, 9, 2] + * const runningMax = Iterable.scan(values, -Infinity, Math.max) + * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const scan = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => ({ + [Symbol.iterator]() { + let acc = b; + let iterator; + function next() { + if (iterator === undefined) { + iterator = self[Symbol.iterator](); + return { + done: false, + value: acc + }; + } + const result = iterator.next(); + if (result.done) { + return result; + } + acc = f(acc, result.value); + return { + done: false, + value: acc + }; + } + return { + next + }; + } +})))); +/** + * Checks whether an `Iterable` is empty. + * + * **Example** (Checking for emptiness) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.isEmpty([]) // => true + * Iterable.isEmpty([1, 2, 3]) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmpty = self => { + const iterator = self[Symbol.iterator](); + return iterator.next().done === true; +}; +/** + * Returns the number of elements in a `Iterable`. + * + * **Example** (Counting iterable elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.size(numbers) // => 5 + * + * const empty = Iterable.empty() + * Iterable.size(empty) // => 0 + * + * // Works with any iterable + * const letters = "hello" + * Iterable.size(letters) // => 5 + * + * // Note: This consumes the entire iterable + * const range = Iterable.range(1, 100) + * Iterable.size(range) // => 100 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => { + const iterator = self[Symbol.iterator](); + let count = 0; + while (!iterator.next().done) { + count++; + } + return count; +}; +/** + * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty. + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.head(numbers) // => Option.some(1) + * + * const empty = Iterable.empty() + * Iterable.head(empty) // => Option.none() + * + * // Safe way to get first element + * const firstEven = Iterable.head( + * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0) + * ) + * firstEven // => Option.some(4) + * + * // Use with Option methods + * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2) + * doubled // => Option.some(10) + * ``` + * + * @category getters + * @since 2.0.0 + */ +const head = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + return result.done ? O.none() : O.some(result.value); +}; +/** + * Gets the first element of an `Iterable` without returning an `Option`. + * + * **When to use** + * + * Use when the `Iterable` is known to be non-empty and direct access to the + * first element is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the `Iterable` is empty. + * + * **Example** (Getting the first element unsafely) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * Iterable.headUnsafe(numbers) // => 1 + * + * const letters = "hello" + * Iterable.headUnsafe(letters) // => "h" + * + * // Iterable.headUnsafe(Iterable.empty()) + * // throws Error: "headUnsafe: empty iterable" + * + * // Use only when you're certain the iterable is non-empty + * const nonEmpty = Iterable.range(1, 10) + * Iterable.headUnsafe(nonEmpty) // => 1 + * ``` + * + * @category getters + * @since 4.0.0 + */ +const headUnsafe = self => { + const iterator = self[Symbol.iterator](); + const result = iterator.next(); + if (result.done) throw new Error("headUnsafe: empty iterable"); + return result.value; +}; +/** + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Taking from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const firstThree = Iterable.take(numbers, 3) + * Array.from(firstThree) // => [1, 2, 3] + * + * // Taking more than available returns all elements + * const firstTen = Iterable.take(numbers, 10) + * Array.from(firstTen) // => [1, 2, 3, 4, 5] + * + * // Taking 0 or negative returns empty + * const none = Iterable.take(numbers, 0) + * Array.from(none) // => [] + * + * // Useful with infinite iterables + * const naturals = Iterable.range(1) + * const firstFive = Iterable.take(naturals, 5) + * Array.from(firstFive) // => [1, 2, 3, 4, 5] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const take = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + let i = 0; + const iterator = self[Symbol.iterator](); + return { + next() { + if (i < n) { + i++; + return iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [2, 4, 6, 8, 3, 10, 12] + * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0) + * Array.from(evenPrefix) // => [2, 4, 6, 8] + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3) + * Array.from(firstThreeByIndex) // => ["a", "b", "c"] + * + * // Stops at first non-matching element + * const mixed = [1, 3, 5, 4, 7, 9] + * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1) + * Array.from(oddPrefix) // => [1, 3, 5] + * + * // Type refinement + * const values: Array = ["a", "b", "c", 1, "d"] + * const stringPrefix = Iterable.takeWhile( + * values, + * (x): x is string => typeof x === "string" + * ) + * Array.from(stringPrefix) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const takeWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done || !predicate(result.value, i++)) { + return { + done: true, + value: undefined + }; + } + return result; + } + }; + } +})))); +/** + * Drops a max number of elements from the start of an `Iterable` + * + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Dropping from the start) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * const withoutFirstTwo = Iterable.drop(numbers, 2) + * Array.from(withoutFirstTwo) // => [3, 4, 5] + * + * // Dropping more than available returns empty + * const withoutFirstTen = Iterable.drop(numbers, 10) + * Array.from(withoutFirstTen) // => [] + * + * // Dropping 0 or negative returns all elements + * const all = Iterable.drop(numbers, 0) + * Array.from(all) // => [1, 2, 3, 4, 5] + * + * // Combine with take for slicing + * const slice = Iterable.take(Iterable.drop(numbers, 1), 3) + * Array.from(slice) // => [2, 3, 4] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const drop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + while (i < n) { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + i++; + } + return iterator.next(); + } + }; + } +})))); +/** + * Returns the first element that satisfies the specified + * predicate, or `None` if no such element exists. + * + * **Example** (Finding the first match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8] + * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) + * firstEven // => Option.some(4) + * + * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10) + * firstGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d"] + * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0) + * atEvenIndex // => Option.some("a") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world"] + * const firstString = Iterable.findFirst( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * firstString // => Option.some("hello") + * + * // Transform during search + * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => { + * const sqrt = Math.sqrt(x) + * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none() + * }) + * findSquareRoot // => Option.some(1) + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + let i = 0; + for (const a of self) { + const o = f(a, i); + if ((0,_Predicate_js__rspack_import_1/* .isBoolean */.Lm)(o)) { + if (o) { + return _Option_js__rspack_import_2.some(a); + } + } else { + if (_Option_js__rspack_import_2.isSome(o)) { + return o; + } + } + i++; + } + return _Option_js__rspack_import_2.none(); +}); +/** + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * const numbers = [1, 3, 4, 6, 8, 2] + * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0) + * lastEven // => Option.some(2) + * + * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10) + * lastGreaterThan10 // => Option.none() + * + * // With index + * const letters = ["a", "b", "c", "d", "e"] + * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0) + * lastAtEvenIndex // => Option.some("e") + * + * // Type refinement + * const mixed: Array = [1, "hello", 2, "world", 3] + * const lastString = Iterable.findLast( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * lastString // => Option.some("world") + * ``` + * + * @category searching + * @since 2.0.0 + */ +const findLast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + let last = O.none(); + for (const a of self) { + const o = f(a, i); + if (isBoolean(o)) { + if (o) { + last = O.some(a); + } + } else { + if (O.isSome(o)) { + last = o; + } + } + i++; + } + return last; +}))); +/** + * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. + * + * **Example** (Zipping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3] + * const letters = ["a", "b", "c"] + * const zipped = Iterable.zip(numbers, letters) + * Array.from(zipped) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Different lengths - shorter one determines result length + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const partial = Iterable.zip(short, long) + * Array.from(partial) // => [[1, "a"], [2, "b"]] + * + * // Works with any iterables + * const range = Iterable.range(1, 3) + * const word = "abc" + * const mixed = Iterable.zip(range, word) + * Array.from(mixed) // => [[1, "a"], [2, "b"], [3, "c"]] + * + * // Create indexed pairs + * const values = ["apple", "banana", "cherry"] + * const indices = Iterable.range(0, 2) + * const indexed = Iterable.zip(indices, values) + * Array.from(indexed) // => [[0, "apple"], [1, "banana"], [2, "cherry"]] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zip = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => zipWith(self, that, Tuple.make)))); +/** + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. + * + * **Example** (Zipping with a combining function) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Add corresponding elements + * const a = [1, 2, 3, 4] + * const b = [10, 20, 30, 40] + * const sums = Iterable.zipWith(a, b, (x, y) => x + y) + * Array.from(sums) // => [11, 22, 33, 44] + * + * // Combine strings + * const firstNames = ["John", "Jane", "Bob"] + * const lastNames = ["Doe", "Smith", "Johnson"] + * const fullNames = Iterable.zipWith( + * firstNames, + * lastNames, + * (first, last) => `${first} ${last}` + * ) + * Array.from(fullNames) // => ["John Doe", "Jane Smith", "Bob Johnson"] + * + * // Different lengths - stops at shorter + * const short = [1, 2] + * const long = ["a", "b", "c", "d"] + * const combined = Iterable.zipWith( + * short, + * long, + * (num, letter) => `${num}${letter}` + * ) + * Array.from(combined) // => ["1a", "2b"] + * + * // Complex transformations + * const prices = [10.99, 25.50, 5.00] + * const quantities = [2, 1, 3] + * const totals = Iterable.zipWith(prices, quantities, (price, qty) => { + * return Math.round(price * qty * 100) / 100 // round to 2 decimal places + * }) + * Array.from(totals) // => [21.98, 25.5, 15] + * ``` + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const selfIterator = self[Symbol.iterator](); + const thatIterator = that[Symbol.iterator](); + return { + next() { + const selfResult = selfIterator.next(); + const thatResult = thatIterator.next(); + if (selfResult.done || thatResult.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(selfResult.value, thatResult.value) + }; + } + }; + } +})))); +/** + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * + * If the input is a non-empty array, the result is also a non-empty array. + * + * **Example** (Interspersing separators) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Join numbers with separator + * const numbers = [1, 2, 3, 4] + * const withCommas = Iterable.intersperse(numbers, ",") + * Array.from(withCommas) // => [1, ",", 2, ",", 3, ",", 4] + * + * // Join words with spaces + * const words = ["hello", "world", "from", "effect"] + * const sentence = Iterable.intersperse(words, " ") + * Array.from(sentence).join("") // => "hello world from effect" + * + * // Empty iterable remains empty + * const empty = Iterable.empty() + * const stillEmpty = Iterable.intersperse(empty, "-") + * Array.from(stillEmpty) // => [] + * + * // Single element has no separators added + * const single = [42] + * const noSeparator = Iterable.intersperse(single, "|") + * Array.from(noSeparator) // => [42] + * + * // Build CSS-like strings + * const styles = ["color: red", "font-size: 14px", "margin: 10px"] + * const css = Iterable.intersperse(styles, "; ") + * Array.from(css).join("") // => "color: red; font-size: 14px; margin: 10px" + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersperse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, middle) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let next = iterator.next(); + let emitted = false; + return { + next() { + if (next.done) { + return next; + } else if (emitted) { + emitted = false; + return { + done: false, + value: middle + }; + } + emitted = true; + const result = next; + next = iterator.next(); + return result; + } + }; + } +})))); +/** + * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function. + * + * **Example** (Checking membership with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Custom equivalence for objects + * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id + * const containsById = Iterable.containsWith(byId) + * + * const users = [{ id: 1 }, { id: 2 }] + * const hasUser1 = containsById(users, { id: 1 }) + * hasUser1 // => true + * + * // Case-insensitive string comparison + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive) + * + * const words = ["Hello", "World"] + * const hasHello = containsCaseInsensitive(words, "hello") + * hasHello // => true + * + * // Approximate number comparison + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const containsApprox = Iterable.containsWith(approxEqual) + * + * const values = [1.0, 2.0, 3.0] + * const hasAlmostTwo = containsApprox(values, 2.05) + * hasAlmostTwo // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => dual(2, (self, a) => { + for (const i of self) { + if (isEquivalent(a, i)) { + return true; + } + } + return false; +}); +/** + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5] + * Iterable.contains(numbers, 3) // => true + * Iterable.contains(numbers, 6) // => false + * + * const letters = "hello" + * Iterable.contains(letters, "l") // => true + * Iterable.contains(letters, "x") // => false + * + * // Works with any iterable + * const range = Iterable.range(1, 100) + * Iterable.contains(range, 50) // => true + * Iterable.contains(range, 150) // => false + * + * // Curried version + * const containsThree = Iterable.contains(3) + * containsThree([1, 2, 3]) // => true + * containsThree([4, 5, 6]) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/(/* unused pure expression or super */ null && (containsWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of + * the `Iterable`. + * + * **Example** (Chunking an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] + * const chunks = Iterable.chunksOf(numbers, 3) + * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + * + * // Last chunk can be shorter + * const uneven = [1, 2, 3, 4, 5, 6, 7] + * const chunks2 = Iterable.chunksOf(uneven, 3) + * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]] + * + * // Chunk size larger than iterable + * const small = [1, 2] + * const chunks3 = Iterable.chunksOf(small, 5) + * Array.from(chunks3) // => [[1, 2]] + * + * // Process data in batches + * const data = Iterable.range(1, 100) + * const batches = Iterable.chunksOf(data, 10) + * const batchSums = Iterable.map( + * batches, + * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n) + * ) + * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255] + * ``` + * + * @category splitting + * @since 2.0.0 + */ +const chunksOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => { + const safeN = Math.max(1, Math.floor(n)); + return { + [Symbol.iterator]() { + let iterator = self[Symbol.iterator](); + return { + next() { + if (iterator === undefined) { + return { + done: true, + value: undefined + }; + } + const chunk = []; + for (let i = 0; i < safeN; i++) { + const result = iterator.next(); + if (result.done) { + iterator = undefined; + return chunk.length === 0 ? { + done: true, + value: undefined + } : { + done: false, + value: chunk + }; + } + chunk.push(result.value); + } + return { + done: false, + value: chunk + }; + } + }; + } + }; +}))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group consecutive equal numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.groupWith(numbers, (a, b) => a === b) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * // Case-insensitive grouping of strings + * const words = ["Apple", "APPLE", "banana", "Banana", "cherry"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const groupedWords = Iterable.groupWith(words, caseInsensitive) + * Array.from(groupedWords) // => [["Apple", "APPLE"], ["banana", "Banana"], ["cherry"]] + * + * // Group by approximate equality + * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2 + * const groupedFloats = Iterable.groupWith(floats, approxEqual) + * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]] + * + * // Only groups consecutive elements + * const scattered = [1, 2, 1, 2, 1] + * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b) + * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]] + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let nextResult; + return { + next() { + let result; + if (nextResult !== undefined) { + if (nextResult.done) { + return { + done: true, + value: undefined + }; + } + result = nextResult; + nextResult = undefined; + } else { + result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + } + const chunk = [result.value]; + while (true) { + const next = iterator.next(); + if (next.done || !isEquivalent(result.value, next.value)) { + nextResult = next; + return { + done: false, + value: chunk + }; + } + chunk.push(next.value); + } + } + }; + } +})))); +/** + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s. + * + * **Example** (Grouping consecutive elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const grouped = Iterable.group(numbers) + * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]] + * + * const letters = "aabbccaa" + * const groupedLetters = Iterable.group(letters) + * Array.from(groupedLetters) // => [["a", "a"], ["b", "b"], ["c", "c"], ["a", "a"]] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A", value: 1 }, + * { type: "A", value: 1 }, + * { type: "B", value: 2 }, + * { type: "A", value: 1 } + * ] + * const groupedObjects = Iterable.group(objects) + * Array.from(groupedObjects).length // => 3 + * // Note: Only consecutive equal objects are grouped together + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const group = /*#__PURE__*/(/* unused pure expression or super */ null && (groupWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Gotchas** + * + * When the key function returns a finite union of string literals or unique + * symbols, the result preserves those keys as optional properties because the + * input may not produce every key. Open `string` and `symbol` key types retain + * their record index signatures. + * + * **Example** (Grouping by a key) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Group by string length + * const words = ["a", "bb", "ccc", "dd", "eee", "f"] + * const byLength = Iterable.groupBy(words, (word) => word.length.toString()) + * byLength // => { "1": ["a", "f"], "2": ["bb", "dd"], "3": ["ccc", "eee"] } + * + * // Group by first letter + * const names = ["Alice", "Bob", "Charlie", "David", "Anna", "Betty"] + * const byFirstLetter = Iterable.groupBy(names, (name) => name[0]) + * byFirstLetter // => { A: ["Alice", "Anna"], B: ["Bob", "Betty"], C: ["Charlie"], D: ["David"] } + * + * // Group by category + * const items = [ + * { name: "apple", category: "fruit" }, + * { name: "carrot", category: "vegetable" }, + * { name: "banana", category: "fruit" }, + * { name: "broccoli", category: "vegetable" } + * ] + * const byCategory = Iterable.groupBy(items, (item) => item.category) + * Object.keys(byCategory) // => ["fruit", "vegetable"] + * + * // Group numbers by even/odd + * const numbers = [1, 2, 3, 4, 5, 6] + * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? "even" : "odd") + * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] } + * ``` + * + * @category grouping + * @since 2.0.0 + */ +const groupBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const a of self) { + const k = f(a); + if (Object.hasOwn(out, k)) { + out[k].push(a); + } else { + InternalRecord.assignProperty(out, k, [a]); + } + } + return out; +}))); +const constEmpty = { + [Symbol.iterator]() { + return constEmptyIterator; + } +}; +const constEmptyIterator = { + next() { + return { + done: true, + value: undefined + }; + } +}; +/** + * Creates an empty iterable that yields no elements. + * + * **When to use** + * + * Use when you need an empty iterable as a typed "no data" value or a base + * case for iterable operations. + * + * **Example** (Creating an empty iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Array.from(Iterable.empty()) // => [] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => constEmpty; +/** + * Creates an iterable containing a single element. + * + * **When to use** + * + * Use to wrap a single value in an iterable context so it can be combined + * with other iterable operations. + * + * **Example** (Wrapping a single value) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const single = Iterable.of(42) + * Array.from(single) // => [42] + * + * // Useful for creating homogeneous sequences + * const sequences = [ + * Iterable.of("hello"), + * Iterable.range(1, 3), + * Iterable.empty() + * ] + * + * // Can be used with flatMap for conditional inclusion + * const numbers = [1, 2, 3, 4, 5] + * const evensOnly = Iterable.flatMap( + * numbers, + * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty() + * ) + * Array.from(evensOnly) // => [2, 4] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = a => [a]; +/** + * Transforms each element of an iterable using a function. + * + * **Details** + * + * This is one of the most fundamental operations for working with iterables. + * It applies a transformation function to each element, creating a new iterable + * with the transformed values. The operation is lazy, so elements are only + * transformed when the iterable is consumed. + * + * **Example** (Mapping elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Transform numbers to their squares + * const numbers = [1, 2, 3, 4, 5] + * const squares = Iterable.map(numbers, (x) => x * x) + * Array.from(squares) // => [1, 4, 9, 16, 25] + * + * // Use index in transformation + * const indexed = Iterable.map(["a", "b", "c"], (char, i) => `${i}: ${char}`) + * Array.from(indexed) // => ["0: a", "1: b", "2: c"] + * + * Array.from(Iterable.map( + * Iterable.map([1, 2, 3], (x) => x * 2), + * (x) => x + 1 + * )) // => [3, 5, 7] + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + return { + done: false, + value: f(result.value, i++) + }; + } + }; + } +})))); +/** + * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. + * + * **Example** (Flat mapping iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Expand each number to a range + * const numbers = [1, 2, 3] + * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n)) + * Array.from(expanded) // => [1, 1, 2, 1, 2, 3] + * + * // Split strings into characters + * const words = ["hi", "bye"] + * const chars = Iterable.flatMap(words, (word) => word) + * Array.from(chars) // => ["h", "i", "b", "y", "e"] + * + * // Conditional expansion with empty iterables + * const values = [1, 2, 3, 4, 5] + * const evenMultiples = Iterable.flatMap( + * values, + * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : [] + * ) + * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12] + * + * // Use index in transformation + * const letters = ["a", "b", "c"] + * const indexed = Iterable.flatMap( + * letters, + * (letter, i) => Iterable.replicate(letter, i + 1) + * ) + * Array.from(indexed) // => ["a", "b", "b", "c", "c", "c"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatten(map(self, f))))); +/** + * Flattens an Iterable of Iterables into a single Iterable + * + * **Example** (Flattening nested iterables) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Flatten nested arrays + * const nested = [[1, 2], [3, 4], [5, 6]] + * const flat = Iterable.flatten(nested) + * Array.from(flat) // => [1, 2, 3, 4, 5, 6] + * + * // Flatten different iterable types + * const mixed: Array> = ["ab", "cd"] + * const flatMixed = Iterable.flatten(mixed) + * Array.from(flatMixed) // => ["a", "b", "c", "d"] + * + * // Flatten deeply nested (only one level) + * const deepNested = [[[1, 2]], [[3, 4]]] + * const oneLevelFlat = Iterable.flatten(deepNested) + * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]] + * // [[1, 2], [3, 4]] (still contains arrays) + * + * // Empty iterables are handled correctly + * const withEmpty = [[1, 2], [], [3, 4], []] + * const flatWithEmpty = Iterable.flatten(withEmpty) + * Array.from(flatWithEmpty) // => [1, 2, 3, 4] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = self => ({ + [Symbol.iterator]() { + const outerIterator = self[Symbol.iterator](); + let innerIterator; + function next() { + while (true) { + if (innerIterator === undefined) { + const next = outerIterator.next(); + if (next.done) { + return next; + } + innerIterator = next.value[Symbol.iterator](); + } + const result = innerIterator.next(); + if (!result.done) { + return result; + } + innerIterator = undefined; + } + } + return { + next + }; + } +}); +/** + * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. + * + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse strings to numbers, keeping only valid ones + * const strings = ["1", "2", "invalid", "4", "not-a-number"] + * const numbers = Iterable.filterMap(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 4] + * + * // Extract specific properties from objects + * const users = [ + * { name: "Alice", age: 25, email: "alice@example.com" }, + * { name: "Bob", age: 17, email: undefined }, + * { name: "Charlie", age: 30, email: "charlie@example.com" }, + * { name: "David", age: 16, email: undefined } + * ] + * const adultEmails = Iterable.filterMap( + * users, + * (user) => + * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid + * ) + * Array.from(adultEmails) // => ["alice@example.com", "charlie@example.com"] + * + * // Use index in transformation + * const items = ["a", "b", "c", "d", "e"] + * const evenIndexItems = Iterable.filterMap( + * items, + * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid + * ) + * Array.from(evenIndexItems) // => ["0: a", "2: c", "4: e"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Transforms all elements of the `Iterable` for as long as the specified function succeeds. + * + * **Example** (Filtering and transforming until failure) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * // Parse numbers until we hit an invalid one + * const strings = ["1", "2", "3", "invalid", "4", "5"] + * const numbers = Iterable.filterMapWhile(strings, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? Result.failVoid : Result.succeed(num) + * }) + * Array.from(numbers) // => [1, 2, 3] + * + * // Take elements while they meet a condition and transform them + * const values = [2, 4, 6, 7, 8, 10] + * const doubledEvens = Iterable.filterMapWhile( + * values, + * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid + * ) + * Array.from(doubledEvens) // => [4, 8, 12] + * + * // Process with index until condition fails + * const letters = ["a", "b", "c", "d", "e"] + * const indexedUntilC = Iterable.filterMapWhile( + * letters, + * (letter, i) => letter !== "c" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid + * ) + * Array.from(indexedUntilC) // => ["0: a", "1: b"] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMapWhile = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + const next = f(result.value, i++); + if (R.isSuccess(next)) { + return { + done: false, + value: next.success + }; + } + return { + done: true, + value: undefined + }; + } + }; + } +})))); +/** + * Retrieves the `Some` values from an `Iterable` of `Option`s. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (O.isSome(result.value)) { + return { + done: false, + value: result.value.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the failure values from an iterable of + * `Result`s, skipping successful results. + * + * **Example** (Extracting failures) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getFailures([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => ["err"] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isFailure(result.value)) { + return { + done: false, + value: result.value.failure + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Returns a lazy iterable containing the success values from an iterable of + * `Result`s, skipping failed results. + * + * **Example** (Extracting successes) + * + * ```ts import.meta.vitest + * import { Iterable, Result } from "effect" + * + * Array.from(Iterable.getSuccesses([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ])) // => [1, 2] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + return { + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (R.isSuccess(result.value)) { + return { + done: false, + value: result.value.success + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } + }; +}; +/** + * Filters an iterable to only include elements that match a predicate. + * + * **Details** + * + * This function creates a new iterable containing only the elements for which + * the predicate function returns true. Like map, this operation is lazy and + * elements are only tested when the iterable is consumed. + * + * **Example** (Filtering elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Filter even numbers + * const numbers = [1, 2, 3, 4, 5, 6] + * const evens = Iterable.filter(numbers, (x) => x % 2 === 0) + * Array.from(evens) // => [2, 4, 6] + * + * // Filter with index + * const items = ["a", "b", "c", "d"] + * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1) + * Array.from(oddPositions) // => ["b", "d"] + * + * // Type refinement + * const mixed: Array = ["hello", 42, "world", 100] + * const onlyStrings = Iterable.filter( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * Array.from(onlyStrings) // => ["hello", "world"] + * + * // Combine with map + * const processed = Iterable.map( + * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2), + * (x) => x * 10 + * ) + * Array.from(processed) // => [30, 40, 50] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, predicate) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let i = 0; + return { + next() { + let result = iterator.next(); + while (!result.done) { + if (predicate(result.value, i++)) { + return { + done: false, + value: result.value + }; + } + result = iterator.next(); + } + return { + done: true, + value: undefined + }; + } + }; + } +})); +/** + * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. + * + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (Flat mapping nullable results) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Extract valid elements from nullable function results + * const data = ["1", "2", "invalid", "4"] + * const parsed = Iterable.flatMapNullishOr(data, (s) => { + * const num = parseInt(s) + * return isNaN(num) ? null : num * 2 + * }) + * Array.from(parsed) // => [2, 4, 8] + * + * // Safe property access + * const objects = [ + * { nested: { value: 10 } }, + * { nested: null }, + * { nested: { value: 20 } }, + * {} + * ] + * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value) + * Array.from(values) // => [10, 20] + * + * // Working with Map.get (returns undefined for missing keys) + * const map = new Map([ + * ["a", 1], + * ["b", 2], + * ["c", 3] + * ]) + * const keys = ["a", "x", "b", "y", "c"] + * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key)) + * Array.from(foundValues) // => [1, 2, 3] + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => filterMap(self, a => { + const b = f(a); + return b == null ? R.failVoid : R.succeed(b); +})))); +/** + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * const numbers = [1, 3, 5, 7, 8] + * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0) + * hasEven // => true + * + * const allOdd = [1, 3, 5, 7] + * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0) + * hasEvenInAllOdd // => false + * + * // With index + * const letters = ["a", "b", "c"] + * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2) + * hasElementAtIndex2 // => true + * + * // Early termination - stops at first match + * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1) + * const hasEvenInInfiniteOdds = Iterable.some( + * Iterable.take(infiniteOdds, 1000), + * (x) => x % 2 === 0 + * ) + * hasEvenInInfiniteOdds // => false + * + * // Type guard usage + * const mixed: Array = [1, 2, "hello"] + * const hasString = Iterable.some( + * mixed, + * (x): x is string => typeof x === "string" + * ) + * hasString // => true + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + let i = 0; + for (const a of self) { + if (predicate(a, i++)) { + return true; + } + } + return false; +}))); +/** + * Generates an iterable by repeatedly applying a function that produces the + * next element and state. + * + * **Details** + * + * This is useful for creating iterables from a generating function that + * maintains state. The function should return `Option.some([value, nextState])` + * to continue or `Option.none()` to stop. + * + * **Example** (Unfolding state into values) + * + * ```ts import.meta.vitest + * import { Iterable, Option } from "effect" + * + * // Generate Fibonacci sequence + * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]])) + * const first10Fib = Iterable.take(fibonacci, 10) + * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] + * + * // Generate powers of 2 up to a limit + * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none()) + * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] + * + * // Generate countdown + * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none()) + * Array.from(countdown) // => [5, 4, 3, 2, 1] + * + * // Generate collatz sequence + * const collatz = Iterable.unfold(7, (n) => { + * if (n === 1) return Option.none() + * const next = n % 2 === 0 ? n / 2 : n * 3 + 1 + * return Option.some([n, next]) + * }) + * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const unfold = (b, f) => ({ + [Symbol.iterator]() { + let next = b; + return { + next() { + const ab = f(next); + if (O.isNone(ab)) { + return { + done: true, + value: undefined + }; + } + const [a, b] = ab.value; + next = b; + return { + done: false, + value: a + }; + } + }; + } +}); +/** + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Collect each visited element + * const numbers = [1, 2, 3, 4, 5] + * const visited: Array = [] + * Iterable.forEach(numbers, (n) => visited.push(n)) + * visited // => [1, 2, 3, 4, 5] + * + * // Use index in the callback + * const letters = ["a", "b", "c"] + * const indexed: Array = [] + * Iterable.forEach(letters, (letter, i) => { + * indexed.push(`${i}: ${letter}`) + * }) + * indexed // => ["0: a", "1: b", "2: c"] + * + * // Side effects with any iterable + * const results: Array = [] + * Iterable.forEach(Iterable.range(1, 5), (n) => { + * results.push(n * n) + * }) + * results // => [1, 4, 9, 16, 25] + * + * // Process in chunks + * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2) + * const processed: Array> = [] + * Iterable.forEach(data, (chunk) => { + * processed.push(Array.from(chunk)) + * }) + * processed // => [[1, 2], [3, 4], [5, 6]] + * ``` + * + * @category traversing + * @since 2.0.0 + */ +const forEach = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let i = 0; + for (const a of self) { + f(a, i++); + } +}))); +/** + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** + * + * This function applies a reducing function against an accumulator and each element + * of the iterable (from left to right) to reduce it to a single value. + * + * **Example** (Reducing an iterable) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Sum all numbers + * const numbers = [1, 2, 3, 4, 5] + * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n) + * sum // => 15 + * + * // Find maximum value + * const values = [3, 1, 4, 1, 5, 9, 2] + * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9 + * + * // Build an object from key-value pairs + * const pairs = [["a", 1], ["b", 2], ["c", 3]] as const + * const obj = Iterable.reduce( + * pairs, + * {} as Record, + * (acc, [key, value]) => { + * acc[key] = value + * return acc + * } + * ) + * obj // => { a: 1, b: 2, c: 3 } + * + * // Use index in the reducer + * const letters = ["a", "b", "c"] + * const indexed = Iterable.reduce( + * letters, + * [] as Array, + * (acc, letter, i) => { + * acc.push(`${i}: ${letter}`) + * return acc + * } + * ) + * indexed // => ["0: a", "1: b", "2: c"] + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, b, f) => { + if (Array.isArray(self)) { + return self.reduce(f, b); + } + let i = 0; + let result = b; + for (const n of self) { + result = f(result, n, i++); + } + return result; +}))); +/** + * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. + * + * **Example** (Deduplicating adjacent elements with custom equivalence) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicates with custom equality + * const numbers = [1, 1, 2, 2, 3, 1, 1] + * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b) + * Array.from(dedupedNumbers) // => [1, 2, 3, 1] + * + * // Case-insensitive deduplication + * const words = ["Hello", "HELLO", "world", "World", "test"] + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() + * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive) + * Array.from(dedupedWords) // => ["Hello", "world", "test"] + * + * // Deduplication by object property + * const users = [ + * { id: 1, name: "Alice" }, + * { id: 1, name: "Alice Updated" }, // different name, same id + * { id: 2, name: "Bob" }, + * { id: 2, name: "Bob" }, + * { id: 3, name: "Charlie" } + * ] + * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id + * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId) + * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3] + * + * // Approximate numeric equality + * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0] + * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1 + * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual) + * Array.from(dedupedFloats) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacentWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, isEquivalent) => ({ + [Symbol.iterator]() { + const iterator = self[Symbol.iterator](); + let first = true; + let last; + function next() { + const result = iterator.next(); + if (result.done) { + return { + done: true, + value: undefined + }; + } + if (first) { + first = false; + last = result.value; + return result; + } + const current = result.value; + if (isEquivalent(last, current)) { + return next(); + } + last = current; + return result; + } + return { + next + }; + } +})))); +/** + * Deduplicates adjacent elements that are identical. + * + * **Example** (Deduplicating adjacent elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Remove adjacent duplicate numbers + * const numbers = [1, 1, 2, 2, 2, 3, 1, 1] + * const deduped = Iterable.dedupeAdjacent(numbers) + * Array.from(deduped) // => [1, 2, 3, 1] + * + * // Remove adjacent duplicate characters + * const letters = "aabbccaa" + * const dedupedLetters = Iterable.dedupeAdjacent(letters) + * Array.from(dedupedLetters) // => ["a", "b", "c", "a"] + * + * // Works with objects using deep equality + * const objects = [ + * { type: "A" }, + * { type: "A" }, + * { type: "B" }, + * { type: "B" }, + * { type: "A" } + * ] + * const dedupedObjects = Iterable.dedupeAdjacent(objects) + * Array.from(dedupedObjects, (object) => object.type) // => ["A", "B", "A"] + * + * // Clean up streaming data + * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100] + * const cleanedData = Iterable.dedupeAdjacent(sensorData) + * Array.from(cleanedData) // => [100, 101, 102, 100] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const dedupeAdjacent = /*#__PURE__*/(/* unused pure expression or super */ null && (dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Zips this Iterable crosswise with the specified Iterable using the specified combiner. + * + * **Example** (Combining cartesian products) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // Create coordinate pairs + * const xs = [1, 2] + * const ys = ["a", "b", "c"] + * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`) + * Array.from(coordinates) // => ["(1,a)", "(1,b)", "(1,c)", "(2,a)", "(2,b)", "(2,c)"] + * + * // Generate all combinations of options + * const sizes = ["S", "M", "L"] + * const colors = ["red", "blue"] + * const products = Iterable.cartesianWith( + * sizes, + * colors, + * (size, color) => ({ size, color }) + * ) + * Array.from(products, ({ color, size }) => `${size}:${color}`) // => ["S:red", "S:blue", "M:red", "M:blue", "L:red", "L:blue"] + * + * // Mathematical operations on all pairs + * const a = [1, 2, 3] + * const b = [10, 20] + * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y) + * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60] + * + * // Create test data combinations + * const userTypes = ["admin", "user"] + * const features = ["read", "write", "delete"] + * const testCases = Iterable.cartesianWith( + * userTypes, + * features, + * (user, feature) => `${user}_can_${feature}` + * ) + * Array.from(testCases) // => ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesianWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, f) => ({ + [Symbol.iterator]() { + const cache = []; + let iterator; + let done = false; + const replay = { + [Symbol.iterator]() { + let index = 0; + return { + next() { + if (index < cache.length) { + return { + done: false, + value: cache[index++] + }; + } + if (done) { + return { + done: true, + value: undefined + }; + } + iterator ??= that[Symbol.iterator](); + const result = iterator.next(); + if (result.done) { + done = true; + return { + done: true, + value: undefined + }; + } + cache.push(result.value); + index++; + return result; + } + }; + } + }; + return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator](); + } +})))); +/** + * Zips this Iterable crosswise with the specified Iterable. + * + * **Example** (Generating cartesian pairs) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * // All pairs of numbers and letters + * const numbers = [1, 2, 3] + * const letters = ["a", "b"] + * const pairs = Iterable.cartesian(numbers, letters) + * Array.from(pairs) // => [[1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]] + * + * // Generate coordinate grid + * const x = [0, 1, 2] + * const y = [0, 1] + * const grid = Iterable.cartesian(x, y) + * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]] + * + * // All combinations for testing + * const browsers = ["chrome", "firefox"] + * const devices = ["desktop", "mobile", "tablet"] + * const testMatrix = Iterable.cartesian(browsers, devices) + * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => ["chrome:desktop", "chrome:mobile", "chrome:tablet", "firefox:desktop", "firefox:mobile", "firefox:tablet"] + * + * // Empty iterable results in empty cartesian product + * const empty = Iterable.empty() + * const withEmpty = Iterable.cartesian([1, 2], empty) + * Array.from(withEmpty) // => [] + * ``` + * + * @category combining + * @since 2.0.0 + */ +const cartesian = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b])))); +/** + * Computes how many elements of the iterable pass the given predicate. + * + * **Example** (Counting matching elements) + * + * ```ts import.meta.vitest + * import { Iterable } from "effect" + * + * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2 + * ``` + * + * @category folding + * @since 3.16.0 + */ +const countBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + let count = 0; + let i = 0; + for (const a of self) { + if (f(a, i)) { + count++; + } + i++; + } + return count; +}))); +//# sourceMappingURL=Iterable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + i8: findFirst, + pb: filter +}); + + +}, +"./node_modules/effect/dist/Layer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Deferred_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Deferred.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Scope_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Scope.js"); + + + + + + + + + + + + +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const memoMapReuse = (entry, scope) => { + entry.observers++; + return _internal_effect_js__rspack_import_0/* .andThen */.hgn(_internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, exit => entry.finalizer(exit)), entry.effect); +}; +/** + * Returns `true` if the specified value is a `Layer`, `false` otherwise. + * + * **Example** (Checking whether a value is a layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * const notALayer = { someProperty: "value" } + * + * Layer.isLayer(dbLayer) // => true + * Layer.isLayer(notALayer) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isLayer = u => hasProperty(u, TypeId); +const LayerProto = { + [TypeId]: { + _ROut: _Function_js__rspack_import_1/* .identity */.D_, + _E: _Function_js__rspack_import_1/* .identity */.D_, + _RIn: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_2/* .pipeArguments */.tT)(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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuild = build => fromBuildUnsafe((memoMap, scope) => { + const layerScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope); + return _internal_effect_js__rspack_import_0/* .onExit */.cfM(build(memoMap, layerScope), exit => exit._tag === "Failure" ? _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit) : _internal_effect_js__rspack_import_0/* ["void"] */.rIH); +}); +/** + * 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" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromBuildMemo = build => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +const memoMapBuild = (memoMap, layer, scope, build) => { + const layerScope = _Scope_js__rspack_import_3/* .makeUnsafe */.LZ(); + const deferred = _Deferred_js__rspack_import_4/* .makeUnsafe */.LZ(); + const entry = { + observers: 1, + effect: _Deferred_js__rspack_import_4/* ["await"] */.Tx(deferred), + finalizer: exit => _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + entry.observers--; + if (entry.observers === 0) { + memoMap.map.delete(layer); + return _Scope_js__rspack_import_3/* .close */.VN(layerScope, exit); + } + return _internal_effect_js__rspack_import_0/* ["void"] */.rIH; + }) + }; + memoMap.map.set(layer, entry); + return _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio(scope, entry.finalizer).pipe(_internal_effect_js__rspack_import_0/* .flatMap */.qIB(() => build(memoMap, layerScope)), _internal_effect_js__rspack_import_0/* .onExit */.cfM(exit => { + entry.effect = exit; + return _Deferred_js__rspack_import_4/* .done */.Vw(deferred, exit); + })); +}; +class MemoMapImpl { + 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) { + return memoMapReuse(local, scope); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return _internal_effect_js__rspack_import_0/* .suspend */.DYE(() => { + const existing = this.get(layer, scope); + if (existing) { + return existing; + } + return memoMapBuild(this, layer, scope, build); + }); + } +} +/** + * 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" + * ``` + * + * @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 + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMapUnsafe = parent => new MemoMapImpl(parent); +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a memo map safely within an Effect + * const program = Effect.gen(function*() { + * const memoMap = yield* Layer.makeMemoMap + * 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" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const makeMemoMap = /*#__PURE__*/(/* unused pure expression or super */ null && (internalEffect.sync(makeMemoMapUnsafe))); +/** + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. + * + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category constructors + * @since 4.0.0 + */ +const forkMemoMap = parent => internalEffect.sync(() => forkMemoMapUnsafe(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 + * + * @category services + * @since 3.13.0 + */ +class CurrentMemoMap extends /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl()("effect/Layer/CurrentMemoMap") { + static forkOrCreate(self) { + const current = _Context_js__rspack_import_5/* .getOrUndefined */.Y6(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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithMemoMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, memoMap, scope) => _internal_effect_js__rspack_import_0/* .provideService */.PfK(_internal_effect_js__rspack_import_0/* .map */.TjK(self.build(memoMap, scope), _Context_js__rspack_import_5/* .add */.WQ(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** + * Builds a layer into a scoped value. + * + * **Example** (Building a layer into a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Build a layer to get its services + * const program = Effect.gen(function*() { + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) + * }) + * + * // Build the layer into Context - automatically manages scope and memoization + * const context = yield* Layer.build(dbLayer) + * + * // Extract the specific service from the built layer + * const database = Context.get(context, Database) + * + * return yield* database.query("SELECT * FROM users") + * }) + * + * Effect.runSync(Effect.scoped(program)) // => "result" + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const build = self => core.withFiber(fiber => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), Context.getUnsafe(fiber.context, Scope.Scope))); +/** + * 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"] + * ``` + * + * @category destructors + * @since 2.0.0 + */ +const buildWithScope = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, scope) => _internal_core_js__rspack_import_6/* .withFiber */.R6(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 + * + * @category constructors + * @since 2.0.0 + */ +const succeed = function () { + if (arguments.length === 1) { + return resource => succeedContext(Context.make(arguments[0], resource)); + } + return succeedContext(Context.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 + * + * @category constructors + * @since 2.0.0 + */ +const succeedContext = context => fromBuildUnsafe(constant(internalEffect.succeed(context))); +/** + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. + * + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. + * + * **Example** (Disabling optional lifecycle work) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Option } from "effect" + * + * const Service = Context.Service("Service") + * const context = Effect.runSync(Effect.scoped(Layer.build(Layer.empty))) + * Context.getOption(context, Service) // => Option.none() + * ``` + * + * @see {@link effectDiscard} for running an effect while providing no services + * + * @category constructors + * @since 2.0.0 + */ +const empty = /*#__PURE__*/(/* unused pure expression or super */ null && (succeedContext(/*#__PURE__*/Context.empty()))); +/** + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeed` where the service value is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a service) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.sync(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 succeed} for constructing layers from static values + * + * @category constructors + * @since 2.0.0 + */ +const sync = function () { + if (arguments.length === 1) { + return evaluate => syncContext(() => Context.make(arguments[0], evaluate())); + } + return syncContext(() => Context.make(arguments[0], arguments[1]())); +}; +/** + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** + * + * This is a lazy version of `succeedContext` where the `Context` is computed + * synchronously only when the layer is built. + * + * **Example** (Lazily providing a context) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layer = Layer.syncContext(() => + * 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 sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * + * @category constructors + * @since 2.0.0 + */ +const syncContext = evaluate => fromBuildMemo(constant(internalEffect.sync(evaluate))); +/** + * 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 + * + * @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(_internal_effect_js__rspack_import_0/* .map */.TjK(effect, value => _Context_js__rspack_import_5/* .make */.L8(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 + * + * @category constructors + * @since 2.0.0 + */ +const effectContext = effect => fromBuildMemo((_, scope) => _Scope_js__rspack_import_3/* .provide */.Gt(effect, scope)); +/** + * Constructs a layer from an effect, discarding its value and providing no + * services. + * + * **When to use** + * + * Use when layer construction should run an Effect for its side effects while providing no + * services. + * + * **Example** (Running an effect during layer construction) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const logs: Array = [] + * const initLayer = Layer.effectDiscard( + * Effect.sync(() => { + * logs.push("Initializing application...") + * }) + * ) + * Effect.runSync(Effect.scoped(Layer.build(initLayer))) + * logs // => ["Initializing application..."] + * ``` + * + * @see {@link empty} for a no-op layer that performs no construction work + * + * @category constructors + * @since 2.0.0 + */ +const effectDiscard = effect => effectContext(internalEffect.as(effect, Context.empty())); +/** + * Constructs a layer lazily using the specified factory. + * + * **Details** + * + * The factory is evaluated only when the suspended layer is first built, and + * the result is memoized with normal layer sharing semantics. + * + * **Example** (Choosing a layer lazily) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * const useProd = true + * + * const layer = Layer.suspend(() => + * useProd + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") + * ) + * Effect.runSync(Effect.provide(Config, layer)) // => "https://api.example.com" + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const suspend = evaluate => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope))); +/** + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** + * + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. + * + * **Example** (Unwrapping an effectful layer) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const layerEffect = Effect.succeed( + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * ) + * + * const unwrappedLayer = Layer.unwrap(layerEffect) + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, unwrappedLayer)) // => "result" + * ``` + * + * @category converting + * @since 4.0.0 + */ +const unwrap = self => { + const service = Context.Service("effect/Layer/unwrap"); + return flatMap(effect(service)(self), Context.get(service)); +}; +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(scope, "parallel"); + return _internal_effect_js__rspack_import_0/* .forEach */.jJl(layers, layer => layer.build(memoMap, _Scope_js__rspack_import_3/* .forkUnsafe */.Fp(parentScope, "sequential")), { + concurrency: layers.length + }).pipe(_internal_effect_js__rspack_import_0/* .map */.TjK(context => _Context_js__rspack_import_5/* .mergeAll */.Um(...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 + * + * @category zipping + * @since 2.0.0 + */ +const mergeAll = (...layers) => fromBuild((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 + * + * @category zipping + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => mergeAll(self, ...(Array.isArray(that) ? that : [that]))))); +const provideWith = (self, that, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), context => self.build(memoMap, scope).pipe(internalEffect.provideContext(context), internalEffect.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 + * + * @category providing services + * @since 2.0.0 + */ +const provide = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, identity)))); +/** + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) + * + * ```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") {} + * + * class UserService extends Context.Service Effect.Effect<{ + * id: string + * name: string + * }> + * }>()("UserService") {} + * + * // 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 and merge all services together + * const allServicesLayer = userServiceLayer.pipe( + * Layer.provideMerge(Layer.mergeAll(databaseLayer, loggerLayer)) + * ) + * + * // Now the resulting layer provides UserService, Database, AND Logger + * const program = Effect.gen(function*() { + * const userService = yield* UserService + * const logger = yield* Logger // Still available! + * const database = yield* Database // Still available! + * + * const user = yield* userService.getUser("123") + * yield* logger.log(`Found user: ${user.name}`) + * + * return user + * }).pipe( + * Effect.provide(allServicesLayer) + * ) + * Effect.runSync(program) // => { id: "123", name: "DB: SELECT * FROM users WHERE id = 123" } + * logs // => ["[LOG] Looking up user 123", "[LOG] Found user: DB: SELECT * FROM users WHERE id = 123"] + * ``` + * + * @see {@link provide} for keeping dependency services private + * + * @category providing services + * @since 2.0.0 + */ +const provideMerge = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => provideWith(self, that, (self, that) => Context.merge(that, self))))); +/** + * Constructs a layer dynamically based on the output of this layer. + * + * **Example** (Creating services from layer output) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class Config extends Context.Service()("Config") {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Logger extends Context.Service Effect.Effect + * }>()("Logger") {} + * + * const logs: Array = [] + * + * // Base config layer + * const configLayer = Layer.succeed(Config, { + * dbUrl: "postgres://localhost:5432/mydb", + * logLevel: "debug" + * }) + * + * // Dynamically create services based on config + * const dynamicServiceLayer = configLayer.pipe( + * Layer.flatMap((context) => { + * const config = Context.get(context, Config) + * + * // Create database layer based on config + * const dbLayer = Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => + * Effect.succeed( + * `Querying ${config.dbUrl}: ${sql}` + * )) + * }) + * + * // Create logger layer based on config + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => + * config.logLevel === "debug" + * ? Effect.sync(() => logs.push(`[DEBUG] ${msg}`)) + * : Effect.sync(() => logs.push(msg)) + * ) + * }) + * + * // Return combined layer + * return Layer.mergeAll(dbLayer, loggerLayer) + * }) + * ) + * + * // Use the dynamic services + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Starting database query") + * const result = yield* database.query("SELECT * FROM users") + * + * return result + * }).pipe( + * Effect.provide(dynamicServiceLayer) + * ) + * Effect.runSync(program) // => "Querying postgres://localhost:5432/mydb: SELECT * FROM users" + * logs // => ["[DEBUG] Starting database query"] + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => f(context).build(memoMap, scope)))))); +/** + * Performs the specified effect if this layer succeeds. + * + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.flatMap(self.build(memoMap, scope), context => Scope.provide(internalEffect.as(f(context), context), scope)))))); +/** + * Performs the specified effect if this layer fails. + * + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * + * @category sequencing + * @since 2.0.0 + */ +const tapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), error => Scope.provide(internalEffect.andThen(f(error), internalEffect.fail(error)), scope)))))); +/** + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** + * + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. + * + * **Details** + * + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer + * + * @category sequencing + * @since 4.0.0 + */ +const tapCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromBuild((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => Scope.provide(internalEffect.andThen(f(cause), internalEffect.failCause(cause)), scope)))))); +/** + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Exit, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Layer that can fail during construction + * const error = new DatabaseError({ message: "Connection failed" }) + * const flakyDatabaseLayer = Layer.effect( + * Database, + * Effect.fail(error) + * ) + * + * // Convert failures to fiber death - removes error from type + * const reliableDatabaseLayer = flakyDatabaseLayer.pipe(Layer.orDie) + * + * // Now the layer type is Layer - no error in type + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(reliableDatabaseLayer) + * ) + * + * Effect.runSync(Effect.exit(program)) // => Exit.die(error) + * ``` + * + * @category error handling + * @since 2.0.0 + */ +const orDie = self => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope))); +const catch_ = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catch_(self.build(memoMap, scope), e => onError(e).build(memoMap, scope)))))); + +/** + * Recovers from specific tagged errors. + * + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class ConfigError extends Data.TaggedError("ConfigError") {} + * + * class Config extends Context.Service()("Config") {} + * + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) + * + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) + * + * const recovered = configLayer.pipe( + * Layer.catchTag("ConfigError", () => fallbackLayer) + * ) + * const program = Config.useSync((config) => config.apiUrl) + * Effect.runSync(Effect.provide(program, recovered)) // => "http://localhost" + * ``` + * + * @see {@link catchCause} for recovering with access to the full cause + * + * @category error handling + * @since 4.0.0 + */ +const catchTag = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, k, f) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchTag(self.build(memoMap, scope), k, error => f(error).build(memoMap, scope)))))); +/** + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) + * + * ```ts import.meta.vitest + * import { Context, Data, Effect, Layer } from "effect" + * + * class DatabaseError extends Data.TaggedError("DatabaseError")<{ + * message: string + * }> {} + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) + * + * const databaseWithFallback = primaryDatabaseLayer.pipe( + * Layer.catchCause(() => { + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * return yield* database.query("SELECT * FROM users") + * }).pipe( + * Effect.provide(databaseWithFallback) + * ) + * + * await Effect.runPromise(program) // => "Memory: SELECT * FROM users" + * ``` + * + * @see {@link catchTag} for recovering from specific tagged errors + * + * @category error handling + * @since 4.0.0 + */ +const catchCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onError) => fromBuildUnsafe((memoMap, scope) => internalEffect.catchCause(self.build(memoMap, scope), cause => onError(cause).build(memoMap, scope)))))); +/** + * Updates a service in the context with a new implementation. + * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * + * **Details** + * + * This function modifies the existing implementation of a service in the + * context. It retrieves the current service, applies the provided + * transformation function `f`, and replaces the old service with the + * transformed one. + * + * @category providing services + * @since 3.13.0 + */ +const updateService = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (layer, service, f) => provide(layer, effect(service, internalEffect.map(service, f)))))); +/** + * Creates a fresh version of this layer that will not be shared. + * + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Ref } from "effect" + * + * class Counter extends Context.Service()("Counter") {} + * + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const compareIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * return left.counterId === right.counterId + * }) + * + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) + * + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * return { id } + * })) + * + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * const sharedResult = yield* Effect.provide(compareIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * const freshResult = yield* Effect.provide(compareIds, fresh) + * + * return { shared: sharedResult, fresh: freshResult } + * }) + * + * await Effect.runPromise(program) // => { shared: true, fresh: false } + * ``` + * + * @category layers + * @since 2.0.0 + */ +const fresh = self => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope)); +/** + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) + * + * ```ts import.meta.vitest + * import { Context, Deferred, Effect, Fiber, Layer, Ref } from "effect" + * + * class HttpServer extends Context.Service()("HttpServer") {} + * + * const program = Effect.gen(function*() { + * const events = yield* Ref.make>([]) + * const started = yield* Deferred.make() + * + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { + * yield* Ref.update(events, (events) => [...events, "Starting HTTP server..."]) + * yield* Deferred.succeed(started, undefined) + * return { port: 3000 } + * })) + * + * const fiber = yield* Effect.forkChild(Layer.launch(serverLayer)) + * yield* Deferred.await(started) + * yield* Fiber.interrupt(fiber) + * return yield* Ref.get(events) + * }) + * + * await Effect.runPromise(program) // => ["Starting HTTP server..."] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const launch = self => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never)); +/** + * Creates a mock layer for testing purposes. You can provide a partial + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * class UserService extends Context.Service Effect.Effect<{ id: string; name: string }, Error> + * readonly deleteUser: (id: string) => Effect.Effect + * readonly updateUser: ( + * id: string, + * data: object + * ) => Effect.Effect<{ id: string; name: string }, Error> + * }>()("UserService") {} + * + * // Create a partial mock - only implement what you need for testing + * const testUserLayer = Layer.mock(UserService, { + * config: { apiUrl: "https://test-api.com" }, // Required - non-Effect property + * getUser: (id: string) => Effect.succeed({ id, name: "Test User" }) // Mock implementation + * // deleteUser and updateUser are omitted - will throw UnimplementedError if called + * }) + * + * // Use in tests + * const testProgram = Effect.gen(function*() { + * const userService = yield* UserService + * + * // This works - we provided an implementation + * const user = yield* userService.getUser("123") + * + * // This would throw - we didn't implement deleteUser + * // yield* userService.deleteUser("123") // UnimplementedError + * + * return user.name + * }).pipe( + * Effect.provide(testUserLayer) + * ) + * Effect.runSync(testProgram) // => "Test User" + * ``` + * + * @category testing + * @since 3.17.0 + */ +const mock = function () { + if (arguments.length === 1) { + return implementation => mockImpl(arguments[0], implementation); + } + return mockImpl(arguments[0], arguments[1]); +}; +const mockImpl = (service, implementation) => succeed(service)(new Proxy({ + ...implementation +}, { + get(target, prop, _receiver) { + if (prop in target) { + return target[prop]; + } + const prevLimit = getStackTraceLimit(); + setStackTraceLimit(2); + const error = new Error(`${service.key}: Unimplemented method "${prop.toString()}"`); + setStackTraceLimit(prevLimit); + error.name = "UnimplementedError"; + return makeUnimplemented(error); + }, + has: constTrue +})); +const makeUnimplemented = error => { + const dead = Object.assign(internalEffect.die(error), { + [StreamTypeId]: StreamTypeId, + channel: { + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead), + pipe() { + return pipeArguments(this, arguments); + } + }, + [ChannelTypeId]: ChannelTypeId, + transform: () => internalEffect.succeed(dead) + }); + function unimplemented() { + return dead; + } + // @effect-diagnostics-next-line floatingEffect:off + Object.assign(unimplemented, dead); + Object.setPrototypeOf(unimplemented, Object.getPrototypeOf(dead)); + return unimplemented; +}; +const StreamTypeId = "~effect/Stream"; +const ChannelTypeId = "~effect/Channel"; +// ----------------------------------------------------------------------------- +// Type constraints +// ----------------------------------------------------------------------------- +/** + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the success + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) + * + * ```ts import.meta.vitest + * import { Context, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.succeed(NumberService, 42) + * + * // Define a constraint that the success type must be a number + * const satisfiesNumber = Layer.satisfiesSuccessType() + * + * // This works - Layer<42, never, never> extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesSuccessType = () => layer => layer; +/** + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the error + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) + * + * ```ts import.meta.vitest + * import { Effect, Layer } from "effect" + * + * const typeErrorLayer = Layer.effectDiscard(Effect.fail(new TypeError("boom"))) + * + * // Define a constraint that the error type must be an Error + * const satisfiesError = Layer.satisfiesErrorType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesError(typeErrorLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesErrorType = () => layer => layer; +/** + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** + * + * This function provides compile-time type checking to ensure that the + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * + * const NumberService = Context.Service("Number") + * const numberLayer = Layer.effectDiscard(Effect.asVoid(NumberService)) + * + * // Define a constraint that the service requirements must be numbers + * const satisfiesNumber = Layer.satisfiesServicesType() + * + * // This works - Layer extends Layer + * const validLayer = satisfiesNumber(numberLayer) + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const satisfiesServicesType = () => layer => layer; +/** + * Constructs a new `Layer` which creates a span and registers it as the current + * parent span. + * + * **Details** + * + * This allows you to create a traced scope for layer construction, making all + * operations within the layer constructor part of the same trace span. The span + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * const logs: Array = [] + * + * // Create a traced layer - all operations performed during construction of + * // the `Database` service are part of the "database-init" span + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * // These operations are traced under "database-init" span + * logs.push("Connecting to database") + * logs.push("Database connected") + * + * const parentSpan = yield* Effect.currentParentSpan + * logs.push((parentSpan as Tracer.Span).name) + * + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.provide(Layer.span("database-init", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Span ${span.name} ended with: ${exit._tag}`)) + * }))) + * + * const program = Database.use((database) => database.query("SELECT 1")) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => "Result: SELECT 1" + * logs // => ["Connecting to database", "Database connected", "database-init", "Span database-init ended with: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const span = (name, options) => { + options = internalTracer.addSpanStackTrace(options); + return effect(Tracer.ParentSpan, options?.onEnd ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options)); +}; +/** + * Constructs a layer that provides an existing span as the current parent span. + * + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Referencing an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * // Create a layer that uses an existing span as parent + * const databaseLayer = Layer.effect( + * Database, + * Effect.gen(function*() { + * const parentSpan = yield* Effect.currentParentSpan + * + * return { + * spanId: parentSpan.spanId, + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * }) + * ).pipe(Layer.provide(Layer.parentSpan(Tracer.externalSpan({ + * spanId: "42", + * traceId: "000" + * })))) + * const program = Database.use((database) => + * Effect.map(database.query("SELECT 1"), (result) => ({ spanId: database.spanId, result }))) + * Effect.runSync(Effect.provide(program, databaseLayer)) // => { spanId: "42", result: "Result: SELECT 1" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const parentSpan = span => succeedContext(Tracer.ParentSpan.context(span)); +/** + * Wraps a `Layer` with a new tracing span, making all operations in the layer + * constructor part of the named trace span. + * + * **Details** + * + * This creates a new span for the layer's construction and execution. The span + * is automatically ended when the layer's scope is closed. This is useful for + * tracking the lifecycle and performance of layer initialization. + * + * **Example** (Wrapping a layer with a span) + * + * ```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 = [] + * + * // Create layers with tracing + * const databaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) + * } + * })).pipe(Layer.withSpan("database-initialization", { + * attributes: { dbType: "postgres" } + * })) + * + * const loggerLayer = Layer.succeed(Logger, { + * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) + * }).pipe(Layer.withSpan("logger-initialization")) + * + * // Combine traced layers + * const appLayer = Layer.mergeAll(databaseLayer, loggerLayer).pipe( + * Layer.withSpan("app-initialization", { + * onEnd: (span, exit) => + * Effect.sync(() => logs.push(`Application initialization completed: ${exit._tag}`)) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const database = yield* Database + * const logger = yield* Logger + * + * yield* logger.log("Application ready") + * return yield* database.query("SELECT * FROM users") + * }).pipe(Effect.provide(appLayer)) + * Effect.runSync(program) // => "Result: SELECT * FROM users" + * logs // => ["Application ready", "Application initialization completed: Success"] + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = internalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); + } + return self => unwrap(internalEffect.map(options?.onEnd !== undefined ? internalEffect.tap(internalEffect.makeSpanScoped(name, options), span => internalEffect.addFinalizer(exit => options.onEnd(span, exit))) : internalEffect.makeSpanScoped(name, options), span => withParentSpan(self, span))); +}; +/** + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, Tracer } from "effect" + * + * class Database extends Context.Service Effect.Effect + * }>()("Database") {} + * + * class Cache extends Context.Service Effect.Effect + * }>()("Cache") {} + * + * // Create layers + * const DatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * return { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) + * } + * })) + * + * const CacheLayer = Layer.effect(Cache, Effect.gen(function*() { + * return { + * get: Effect.fn("Cache.get")((key: string) => Effect.succeed(`Cache: ${key}`)) + * } + * })) + * + * // Use with an existing parent span from Effect.withSpan + * const program = Effect.withSpan("application-startup")( + * Effect.gen(function*() { + * const parentSpan = yield* Tracer.ParentSpan + * + * // Both layers will be children of "application-startup" span + * const AppLayer = Layer.mergeAll(DatabaseLayer, CacheLayer).pipe( + * Layer.withParentSpan(parentSpan) + * ) + * + * const context = yield* Layer.build(AppLayer) + * const database = Context.get(context, Database) + * const cache = Context.get(context, Cache) + * + * const dbResult = yield* database.query("SELECT * FROM users") + * const cacheResult = yield* cache.get("user:123") + * + * return { dbResult, cacheResult } + * }) + * ) + * Effect.runSync(Effect.scoped(program)) // => { dbResult: "DB: SELECT * FROM users", cacheResult: "Cache: user:123" } + * ``` + * + * @category tracing + * @since 2.0.0 + */ +const withParentSpan = function () { + const dataFirst = isLayer(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = identity; + if (span._tag === "Span") { + options = internalTracer.addSpanStackTrace(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + const parentSpanLayer = parentSpan(span); + if (dataFirst) { + return provide(provideStackFrame(arguments[0]), parentSpanLayer); + } + return self => provide(provideStackFrame(self), parentSpanLayer); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : constUndefined; + return updateService(CurrentStackFrame, parent => ({ + name, + stack, + parent + })); +}; +//# sourceMappingURL=Layer.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + H7: buildWithMemoMap, + LT: buildWithScope, + QZ: effect, + Um: mergeAll, + j6: makeMemoMapUnsafe +}); + + +}, +"./node_modules/effect/dist/ManagedRuntime.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Effect_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Effect.js"); +/* import */ var _Exit_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Exit.js"); +/* import */ var _Fiber_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Fiber.js"); +/* import */ var _Layer_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Layer.js"); +/* import */ var _Scope_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Scope.js"); + + + + + + +const TypeId = "~effect/ManagedRuntime"; +/** + * Checks whether the provided argument is a `ManagedRuntime`. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a `ManagedRuntime`. + * + * **Details** + * + * The guard checks the internal `ManagedRuntime` marker property. It does not + * build the layer or inspect the runtime's services. + * + * **Gotchas** + * + * Disposed runtimes still carry the marker, so this guard does not prove the + * runtime is still usable. + * + * @see {@link make} for creating managed runtimes this guard recognizes + * + * @category guards + * @since 3.9.0 + */ +const isManagedRuntime = input => hasProperty(input, TypeId); +/** + * Creates a `ManagedRuntime` from a layer. + * + * **When to use** + * + * Use to create a reusable runtime from a `Layer` for application entry points + * or integration code that runs many effects without rebuilding services. + * + * **Details** + * + * The layer is built lazily on first use and its context is cached for + * subsequent runs. Resources acquired by the layer are owned by the runtime and + * are released when `dispose` or `disposeEffect` is run. `options.memoMap` can + * be used to share layer memoization with other layer builds. + * + * **Gotchas** + * + * Dispose the runtime when it is no longer needed. A runtime cannot be reused + * after disposal. + * + * **Example** (Creating a managed runtime) + * + * ```ts import.meta.vitest + * import { Context, Effect, Layer, ManagedRuntime } from "effect" + * + * const notifications: Array = [] + * + * class Notifications extends Context.Service Effect.Effect + * }>()("Notifications") { + * static readonly layer = Layer.succeed(this)({ + * notify: Effect.fn("Notifications.notify")((message) => + * Effect.sync(() => notifications.push(message)) + * ) + * }) + * } + * + * const runtime = ManagedRuntime.make(Notifications.layer) + * + * const program = Effect.flatMap( + * Notifications, + * (_) => _.notify("Hello, world!") + * ).pipe(Effect.ensuring(runtime.disposeEffect)) + * + * await runtime.runPromise(program) + * notifications // => ["Hello, world!"] + * ``` + * + * @see {@link ManagedRuntime} for the returned runtime interface + * @see {@link Layer.MemoMap} for shared layer memoization + * @see {@link Layer.build} for lower-level scoped layer construction + * + * @category constructors + * @since 2.0.0 + */ +const make = (layer, options) => { + const memoMap = options?.memoMap ?? _Layer_js__rspack_import_0/* .makeMemoMapUnsafe */.j6(); + const scope = _Scope_js__rspack_import_1/* .makeUnsafe */.LZ("parallel"); + const layerScope = _Scope_js__rspack_import_1/* .forkUnsafe */.Fp(scope, "sequential"); + const defaultRunOptions = { + onFiberStart: _Fiber_js__rspack_import_2/* .runIn */.VO(scope) + }; + const mergeRunOptions = options => options ? { + ...options, + onFiberStart: options.onFiberStart ? fiber => { + defaultRunOptions.onFiberStart(fiber); + options.onFiberStart(fiber); + } : defaultRunOptions.onFiberStart + } : defaultRunOptions; + let buildFiber; + const contextEffect = _Effect_js__rspack_import_3/* .withFiber */.R6R(fiber => { + if (!buildFiber) { + buildFiber = _Effect_js__rspack_import_3/* .runFork */.MY7(_Effect_js__rspack_import_3/* .tap */.Mim(_Layer_js__rspack_import_0/* .buildWithMemoMap */.H7(layer, memoMap, layerScope), context => _Effect_js__rspack_import_3/* .sync */.OH5(() => { + self.cachedContext = context; + })), { + ...defaultRunOptions, + scheduler: fiber.currentScheduler + }); + } + return _Effect_js__rspack_import_3/* .flatten */.Bqz(_Fiber_js__rspack_import_2/* ["await"] */.Tx(buildFiber)); + }); + const self = { + [TypeId]: TypeId, + memoMap, + scope, + contextEffect: contextEffect, + cachedContext: undefined, + context() { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runPromise */.pR5(self.contextEffect) : Promise.resolve(self.cachedContext); + }, + dispose() { + return _Effect_js__rspack_import_3/* .runPromise */.pR5(self.disposeEffect); + }, + [Symbol.asyncDispose]() { + return self.dispose(); + }, + disposeEffect: _Effect_js__rspack_import_3/* .suspend */.DYE(() => { + ; + self.contextEffect = _Effect_js__rspack_import_3/* .die */.F_Q("ManagedRuntime disposed"); + self.cachedContext = undefined; + return _Scope_js__rspack_import_1/* .close */.VN(self.scope, _Exit_js__rspack_import_4/* ["void"] */.rI); + }), + runFork(effect, options) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runFork */.MY7(provide(self, effect), mergeRunOptions(options)) : _Effect_js__rspack_import_3/* .runForkWith */.eJC(self.cachedContext)(effect, mergeRunOptions(options)); + }, + runCallback(effect, options) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runCallback */.bPG(provide(self, effect), mergeRunOptions(options)) : _Effect_js__rspack_import_3/* .runCallbackWith */.lSz(self.cachedContext)(effect, mergeRunOptions(options)); + }, + runSyncExit(effect) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runSyncExit */.lKS(provide(self, effect)) : _Effect_js__rspack_import_3/* .runSyncExitWith */.rfH(self.cachedContext)(effect); + }, + runSync(effect) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runSync */.HZF(provide(self, effect)) : _Effect_js__rspack_import_3/* .runSyncWith */.lE(self.cachedContext)(effect); + }, + runPromiseExit(effect, options) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runPromiseExit */.NpQ(provide(self, effect), mergeRunOptions(options)) : _Effect_js__rspack_import_3/* .runPromiseExitWith */.jqV(self.cachedContext)(effect, mergeRunOptions(options)); + }, + runPromise(effect, options) { + return self.cachedContext === undefined ? _Effect_js__rspack_import_3/* .runPromise */.pR5(provide(self, effect), mergeRunOptions(options)) : _Effect_js__rspack_import_3/* .runPromiseWith */.v2Q(self.cachedContext)(effect, mergeRunOptions(options)); + } + }; + return self; +}; +function provide(managed, effect) { + return _Effect_js__rspack_import_3/* .flatMap */.qIB(managed.contextEffect, context => _Effect_js__rspack_import_3/* .provideContext */.PpN(effect, context)); +} +//# sourceMappingURL=ManagedRuntime.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + L: make +}); + + +}, +"./node_modules/effect/dist/Option.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +/* import */ var _Combiner_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Combiner.js"); +/* import */ var _Equal_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Equivalence_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equivalence.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_doNotation_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _internal_option_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_record_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _internal_result_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/* import */ var _Order_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Predicate_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Reducer_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Reducer.js"); +/** + * Models a value that may be present or absent. + * + * An `Option` is `Some` when a value is available and `None` when it is + * not. This lets code handle missing values explicitly instead of relying on + * `null` or `undefined`. The module includes helpers for creating, checking, + * transforming, combining, and extracting optional values, plus conversions to + * and from common nullable or result-like shapes. It also includes `Option.gen` + * for writing small generator-based computations that stop at the first `None`. + * + * @since 2.0.0 + */ + + + + + + + + + + + +const TypeId = "~effect/data/Option"; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const none = () => _internal_option_js__rspack_import_0/* .none */.dv; +/** + * 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. + * + * @category constructors + * @since 2.0.0 + */ +const some = _internal_option_js__rspack_import_0/* .some */.zN; +/** + * Determines whether the given value is an `Option`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries, such as type-narrowing + * in union types. + * + * **Details** + * + * - Returns `true` for both `Some` and `None` instances + * - Acts as a type guard, narrowing the input to `Option` + * + * **Example** (Checking if a value is an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isOption(Option.some(1)) // => true + * Option.isOption(Option.none()) // => true + * Option.isOption({}) // => false + * ``` + * + * @see {@link isNone} to check for `None` specifically + * @see {@link isSome} to check for `Some` specifically + * + * @category guards + * @since 2.0.0 + */ +const isOption = _internal_option_js__rspack_import_0/* .isOption */.oL; +/** + * 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. + * + * @category guards + * @since 2.0.0 + */ +const isNone = _internal_option_js__rspack_import_0/* .isNone */.$I; +/** + * Checks whether an `Option` contains a value (`Some`). + * + * **When to use** + * + * Use when you need to branch on a present `Option` before accessing `.value`. + * + * **Details** + * + * - Acts as a type guard, narrowing to `Some` + * + * **Example** (Checking for Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.isSome(Option.some(1)) // => true + * Option.isSome(Option.none()) // => false + * ``` + * + * @see {@link isNone} for the opposite check. + * + * @category guards + * @since 2.0.0 + */ +const isSome = _internal_option_js__rspack_import_0/* .isSome */.Ru; +/** + * Pattern-matches on an `Option`, handling both `None` and `Some` cases. + * + * **When to use** + * + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. + * + * **Details** + * + * - If `None`, calls `onNone` and returns its result + * - If `Some`, calls `onSome` with the value and returns its result + * - Supports the `dual` API (data-last and data-first) + * + * **Example** (Matching on an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.match(Option.some(1), { + * onNone: () => "Option is empty", + * onSome: (value) => `Option has a value: ${value}` + * }) // => "Option has a value: 1" + * ``` + * + * @see {@link getOrElse} for unwrapping with a default + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onNone, + onSome +}) => isNone(self) ? onNone() : onSome(self.value)); +/** + * Converts an `Option`-returning function into a type guard (refinement). + * + * **When to use** + * + * Use when you need to turn an `Option`-returning parser into a type-narrowing + * predicate, such as for `Array.prototype.filter`. + * + * **Details** + * + * - Returns `true` when the original function returns `Some` + * - Returns `false` when the original function returns `None` + * - Narrows the input type to `B` on success + * + * **Example** (Converting a parser to a type guard) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * type MyData = string | number + * + * const parseString = (data: MyData): Option.Option => + * typeof data === "string" ? Option.some(data) : Option.none() + * + * // ┌─── (a: MyData) => a is string + * // ▼ + * const isString = Option.toRefinement(parseString) + * + * isString("a") // => true + * isString(1) // => false + * ``` + * + * @see {@link liftPredicate} for the reverse direction + * + * @category converting + * @since 2.0.0 + */ +const toRefinement = f => a => isSome(f(a)); +/** + * Wraps the first element of an `Iterable` in a `Some`, or returns `None` if + * the iterable is empty. + * + * **When to use** + * + * Use when you need to safely extract the head of a collection, including + * generators or lazy iterables. + * + * **Details** + * + * - Only consumes the first element; does not iterate the rest + * - Returns `None` for empty iterables + * + * **Example** (Getting the first element) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromIterable([1, 2, 3]) // => Option.some(1) + * Option.fromIterable([]) // => Option.none() + * ``` + * + * @see {@link toArray} for the inverse direction + * + * @category constructors + * @since 2.0.0 + */ +const fromIterable = collection => { + for (const a of collection) { + return some(a); + } + return none(); +}; +/** + * Converts a `Result` into an `Option`, keeping only the success value. + * + * **When to use** + * + * Use when you need to discard a `Result` failure and keep only the success + * value as an `Option`. + * + * **Details** + * + * - `Success` becomes `Some` with the success value + * - `Failure` becomes `None` and the failure value is discarded + * + * **Example** (Extracting the success side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * Option.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_2/* .getSuccess */.Oz; +/** + * Converts a `Result` into an `Option`, keeping only the failure value. + * + * **When to use** + * + * Use when you need to discard a `Result` success and keep only the failure + * value as an `Option`. + * + * **Details** + * + * - `Failure` becomes `Some` with the failure value + * - `Success` becomes `None` and the success value is discarded + * + * **Example** (Extracting the failure side) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getFailure(Result.succeed("ok")) // => Option.none() + * Option.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} for the opposite operation. + * + * @category converting + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_2/* .getFailure */.L8; +/** + * Extracts the value from a `Some`, or evaluates a fallback thunk on `None`. + * + * **When to use** + * + * Use when providing a default value for an absent `Option` + * - Unwrapping with lazy evaluation of the fallback + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → calls `onNone()` and returns its result + * - `onNone` is only called when needed (lazy) + * + * **Example** (Unwrapping with a fallback) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(1).pipe(Option.getOrElse(() => 0)) // => 1 + * Option.none().pipe(Option.getOrElse(() => 0)) // => 0 + * ``` + * + * @see {@link getOrNull} to fall back to `null` + * @see {@link getOrUndefined} to fall back to `undefined` + * @see {@link getOrThrow} to throw on `None` + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? onNone() : self.value); +/** + * Returns the fallback `Option` if `self` is `None`; otherwise returns `self`. + * + * **When to use** + * + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → evaluates and returns `that()` + * - `that` is lazily evaluated + * + * **Example** (Providing a fallback Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElse(() => Option.some("b"))) // => Option.some("b") + * Option.some("a").pipe(Option.orElse(() => Option.some("b"))) // => Option.some("a") + * ``` + * + * @see {@link orElseSome} to wrap the fallback value in `Some` automatically + * @see {@link firstSomeOf} to pick the first `Some` from a collection + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? that() : self); +/** + * Returns `Some` of the fallback value if `self` is `None`; otherwise returns + * `self`. + * + * **When to use** + * + * Use when providing a default plain value (not an `Option`) as fallback + * + * **Details** + * + * - `Some` → returns `self` unchanged + * - `None` → calls `onNone()`, wraps result in `Some`, and returns it + * + * **Example** (Providing a fallback value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.none().pipe(Option.orElseSome(() => "b")) // => Option.some("b") + * Option.some("a").pipe(Option.orElseSome(() => "b")) // => Option.some("a") + * ``` + * + * @see {@link orElse} when the fallback is itself an `Option` + * + * @category error handling + * @since 2.0.0 + */ +const orElseSome = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => isNone(self) ? some(onNone()) : self); +/** + * Returns the first available value and marks whether it came from the fallback. + * + * **When to use** + * + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. + * + * **Details** + * + * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) + * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) + * - Both `None` → `None` + * + * **Example** (Tracking value source) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const fallback = () => Option.some("fallback") + * + * Option.orElseResult(Option.some("primary"), fallback) // => Option.some(Result.fail("primary")) + * Option.orElseResult(Option.none(), fallback) // => Option.some(Result.succeed("fallback")) + * ``` + * + * @see {@link orElse} for the simpler variant without source tracking + * + * @category error handling + * @since 4.0.0 + */ +const orElseResult = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => isNone(self) ? map(that(), _internal_result_js__rspack_import_2/* .succeed */.Py) : map(self, _internal_result_js__rspack_import_2/* .fail */.fJ)); +/** + * Returns the first `Some` found in an iterable of `Option`s, or `None` if + * all are `None`. + * + * **When to use** + * + * Use when you need the first available `Some` value from a priority list. + * + * **Details** + * + * - Short-circuits on the first `Some` + * - Returns `None` only when every element is `None` + * + * **Example** (Finding the first Some) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.firstSomeOf([ + * Option.none(), + * Option.some(1), + * Option.some(2) + * ]) // => Option.some(1) + * ``` + * + * @see {@link orElse} for a two-option fallback + * + * @category error handling + * @since 2.0.0 + */ +const firstSomeOf = collection => { + let out = none(); + for (out of collection) { + if (isSome(out)) { + return out; + } + } + return out; +}; +/** + * Converts a nullable value (`null` or `undefined`) into an `Option`. + * + * **When to use** + * + * Use when you need JavaScript nullish values to become absence at an API + * boundary while all other values, including falsy ones, remain present. + * + * **Details** + * + * - `null` or `undefined` → `None` + * - Any other value → `Some` (typed as `NonNullable`) + * + * **Example** (Converting nullable values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullishOr(undefined) // => Option.none() + * Option.fromNullishOr(null) // => Option.none() + * Option.fromNullishOr(1) // => Option.some(1) + * ``` + * + * @see {@link fromNullOr} to only treat `null` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * @see {@link liftNullishOr} to lift a nullable-returning function + * + * @category converting + * @since 4.0.0 + */ +const fromNullishOr = a => a == null ? none() : some(a); +/** + * Converts a possibly `undefined` value into an `Option`, leaving `null` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `undefined` as absent while preserving `null` + * as a meaningful value. + * + * **Details** + * + * - `undefined` → `None` + * - Any other value (including `null`) → `Some` + * + * **Example** (Converting possibly undefined values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromUndefinedOr(undefined) // => Option.none() + * Option.fromUndefinedOr(null) // => Option.some(null) + * Option.fromUndefinedOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromNullOr} to only treat `null` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromUndefinedOr = a => a === undefined ? none() : some(a); +/** + * Converts a possibly `null` value into an `Option`, leaving `undefined` + * as a valid `Some`. + * + * **When to use** + * + * Use when you want to treat only `null` as absent while preserving + * `undefined` as a meaningful value. + * + * **Details** + * + * - `null` → `None` + * - Any other value (including `undefined`) → `Some` + * + * **Example** (Converting possibly null values to an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.fromNullOr(null) // => Option.none() + * Option.fromNullOr(undefined) // => Option.some(undefined) + * Option.fromNullOr(42) // => Option.some(42) + * ``` + * + * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent + * @see {@link fromUndefinedOr} to only treat `undefined` as absent + * + * @category converting + * @since 4.0.0 + */ +const fromNullOr = a => a === null ? none() : some(a); +/** + * Lifts a function that may return `null` or `undefined` into one that returns + * an `Option`. + * + * **When to use** + * + * Use to wrap existing nullable-returning functions for use in `Option` pipelines + * + * **Details** + * + * - Calls the original function with the given arguments + * - Wraps the result via {@link fromNullishOr} + * + * **Example** (Lifting a parser) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): number | undefined => { + * const n = parseFloat(s) + * return isNaN(n) ? undefined : n + * } + * + * const parseOption = Option.liftNullishOr(parse) + * + * parseOption("1") // => Option.some(1) + * parseOption("not a number") // => Option.none() + * ``` + * + * @see {@link fromNullishOr} for converting a single value + * @see {@link liftThrowable} for functions that throw instead + * + * @category converting + * @since 4.0.0 + */ +const liftNullishOr = f => (...a) => fromNullishOr(f(...a)); +/** + * Extracts the value from a `Some`, or returns `null` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect `null`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `null` + * + * **Example** (Unwrapping to null) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrNull(Option.some(1)) // => 1 + * Option.getOrNull(Option.none()) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constNull */.XR); +/** + * Extracts the value from a `Some`, or returns `undefined` for `None`. + * + * **When to use** + * + * Use when you need to pass absent `Option` values to APIs that expect + * `undefined`. + * + * **Details** + * + * - `Some` → the inner value + * - `None` → `undefined` + * + * **Example** (Unwrapping to undefined) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.getOrUndefined(Option.some(1)) // => 1 + * Option.getOrUndefined(Option.none()) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/getOrElse(_Function_js__rspack_import_1/* .constUndefined */.MN); +/** + * Lifts a function that may throw into one that returns an `Option`. + * + * **When to use** + * + * Use to wrap exception-throwing APIs (e.g. `JSON.parse`) for safe usage + * + * **Details** + * + * - If the function returns normally → `Some` with the result + * - If the function throws → `None` (exception is swallowed) + * + * **Example** (Lifting JSON.parse) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = Option.liftThrowable(JSON.parse) + * + * parse("1") // => Option.some(1) + * parse("") // => Option.none() + * ``` + * + * @see {@link liftNullishOr} for nullable-returning functions + * + * @category converting + * @since 2.0.0 + */ +const liftThrowable = f => (...a) => { + try { + return some(f(...a)); + } catch { + return none(); + } +}; +/** + * Extracts the value from a `Some`, or throws a custom error for `None`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws the value returned by `onNone()` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrowWith(Option.some(1), () => new Error("missing")) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrowWith(Option.none(), () => new Error("missing")), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "missing" + * ``` + * + * @see {@link getOrThrow} for a version with a default error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, onNone) => { + if (isSome(self)) { + return self.value; + } + throw onNone(); +}); +/** + * Extracts the value from a `Some`, or throws a default `Error` for `None`. + * + * **When to use** + * + * Use when you need quick fail-fast unwrapping of an `Option` and a generic + * error is acceptable. + * + * **Details** + * + * - `Some` → returns the inner value + * - `None` → throws `new Error("getOrThrow called on a None")` + * + * **Example** (Throwing a default error) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.getOrThrow(Option.some(1)) // => 1 + * + * const failure = Result.try({ + * try: () => Option.getOrThrow(Option.none()), + * catch: (error) => (error as Error).message + * }) + * Result.getFailure(failure).pipe(Option.getOrElse(() => "no error")) // => "getOrThrow called on a None" + * ``` + * + * @see {@link getOrThrowWith} for a custom error + * @see {@link getOrElse} for a non-throwing alternative + * + * @category converting + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/getOrThrowWith(() => new Error("getOrThrow called on a None")); +/** + * Transforms the value inside a `Some` using the provided function, leaving + * `None` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. + * + * **Details** + * + * - `Some` → applies `f` and wraps the result in a new `Some` + * - `None` → returns `None` unchanged + * + * **Example** (Mapping over an Option) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.map(Option.some(2), (n) => n * 2) // => Option.some(4) + * Option.map(Option.none(), (n: number) => n * 2) // => Option.none() + * ``` + * + * @see {@link flatMap} when `f` returns an `Option` + * @see {@link as} to replace the value with a constant + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : some(f(self.value))); +/** + * Replaces the value inside a `Some` with a constant, leaving `None` unchanged. + * + * **When to use** + * + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Replacing a value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.as(Option.some(42), "new value") // => Option.some("new value") + * Option.as(Option.none(), "new value") // => Option.none() + * ``` + * + * @see {@link asVoid} to replace with `undefined` + * @see {@link map} for a general transformation + * + * @category mapping + * @since 2.0.0 + */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, b) => map(self, () => b)); +/** + * Replaces the value inside a `Some` with `void` (`undefined`), leaving `None` + * unchanged. + * + * **When to use** + * + * Use when you need to discard a present `Option` value while preserving + * whether it was `Some` or `None`. + * + * **Example** (Voiding the value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.asVoid(Option.some(42)) // => Option.some(undefined) + * Option.asVoid(Option.none()) // => Option.none() + * ``` + * + * @see {@link as} to replace with a specific constant + * + * @category mapping + * @since 2.0.0 + */ +const asVoid = /*#__PURE__*/as(undefined); +const void_ = /*#__PURE__*/some(undefined); + +/** + * Applies a function that returns an `Option` to the value of a `Some`, + * flattening the result. Returns `None` if the input is `None`. + * + * **When to use** + * + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. + * + * **Details** + * + * - `Some` → applies `f` to the value and returns its `Option` result + * - `None` → returns `None` without calling `f` + * - Equivalent to `map` followed by {@link flatten} + * + * **Example** (Chaining optional lookups) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface User { + * readonly name: string + * readonly address: Option.Option<{ readonly street: Option.Option }> + * } + * + * const user: User = { + * name: "John", + * address: Option.some({ street: Option.some("123 Main St") }) + * } + * + * user.address.pipe( + * Option.flatMap((addr) => addr.street) + * ) // => Option.some("123 Main St") + * ``` + * + * @see {@link map} when `f` returns a plain value + * @see {@link andThen} for a more flexible variant + * @see {@link flatten} to unwrap a nested `Option>` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : f(self.value)); +/** + * Chains a second computation onto an `Option`. The second value can be a + * plain value, an `Option`, or a function returning either. + * + * **When to use** + * + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. + * + * **Details** + * + * - If `self` is `None`, returns `None` immediately + * - If `f` is a function, calls it with the `Some` value + * - If `f` returns an `Option`, returns it as-is; if a plain value, wraps in `Some` + * - If `f` is not a function, uses it directly (same wrapping rules) + * + * **Example** (Chaining with andThen) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * // Chain with a function returning Option + * Option.andThen(Option.some(5), (x) => Option.some(x * 2)) // => Option.some(10) + * + * // Chain with a static value + * Option.andThen(Option.some(5), "hello") // => Option.some("hello") + * + * // Chain with None - skips + * Option.andThen(Option.none(), (x) => Option.some(x * 2)) // => Option.none() + * ``` + * + * @see {@link flatMap} for the standard monadic bind + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => { + const b = (0,_Predicate_js__rspack_import_3/* .isFunction */.Tn)(f) ? f(a) : f; + return isOption(b) ? b : some(b); +})); +/** + * Combines {@link flatMap} with {@link fromNullishOr}: applies a function that + * may return `null`/`undefined` to the value of a `Some`. + * + * **When to use** + * + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. + * + * **Details** + * + * - `None` → `None` + * - `Some` → applies `f`, then wraps via {@link fromNullishOr} + * + * **Example** (Navigating optional properties) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * interface Employee { + * company?: { address?: { street?: { name?: string } } } + * } + * + * const emp: Employee = { + * company: { address: { street: { name: "high street" } } } + * } + * + * Option.some(emp).pipe( + * Option.flatMapNullishOr((e) => e.company?.address?.street?.name) + * ) // => Option.some("high street") + * ``` + * + * @see {@link flatMap} when the function already returns `Option` + * @see {@link fromNullishOr} for single-value conversion + * + * @category sequencing + * @since 4.0.0 + */ +const flatMapNullishOr = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => isNone(self) ? none() : fromNullishOr(f(self.value))); +/** + * Flattens a nested `Option>` into `Option`. + * + * **When to use** + * + * Use when you need to remove one layer of nested `Option`. + * + * **Details** + * + * - `Some(Some(value))` → `Some(value)` + * - `Some(None)` → `None` + * - `None` → `None` + * + * **Example** (Flattening nested Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.flatten(Option.some(Option.some("value"))) // => Option.some("value") + * Option.flatten(Option.some(Option.none())) // => Option.none() + * ``` + * + * @see {@link flatMap} which is `map` + `flatten` + * + * @category sequencing + * @since 2.0.0 + */ +const flatten = /*#__PURE__*/flatMap(_Function_js__rspack_import_1/* .identity */.D_); +/** + * Sequences two `Option`s, keeping the value from the second if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. + * + * **Details** + * + * - Both `Some` → returns `that` + * - Either `None` → returns `None` + * + * **Example** (Keeping the second value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipRight(Option.some(1), Option.some("hello")) // => Option.some("hello") + * Option.zipRight(Option.none(), Option.some("hello")) // => Option.none() + * ``` + * + * @see {@link zipLeft} to keep the first value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipRight = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => flatMap(self, () => that)); +/** + * Sequences two `Option`s, keeping the value from the first if both are `Some`. + * + * **When to use** + * + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. + * + * **Details** + * + * - Both `Some` → returns `self` + * - Either `None` → returns `None` + * + * **Example** (Keeping the first value) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipLeft(Option.some("hello"), Option.some(1)) // => Option.some("hello") + * Option.zipLeft(Option.some("hello"), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipRight} to keep the second value instead + * @see {@link zipWith} to combine both values + * + * @category zipping + * @since 2.0.0 + */ +const zipLeft = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => tap(self, () => that)); +/** + * Composes two `Option`-returning functions into a single function that chains + * them together. + * + * **When to use** + * + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. + * + * **Details** + * + * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value + * - Short-circuits to `None` if either function returns `None` + * + * **Example** (Composing parsers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parse = (s: string): Option.Option => + * isNaN(Number(s)) ? Option.none() : Option.some(Number(s)) + * + * const double = (n: number): Option.Option => + * n > 0 ? Option.some(n * 2) : Option.none() + * + * const parseAndDouble = Option.composeK(parse, double) + * + * parseAndDouble("42") // => Option.some(84) + * parseAndDouble("not a number") // => Option.none() + * ``` + * + * @see {@link flatMap} for single-step chaining + * + * @category sequencing + * @since 2.0.0 + */ +const composeK = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (afb, bfc) => a => flatMap(afb(a), bfc)); +/** + * Runs a side-effecting `Option`-returning function on the value of a `Some`, + * returning the original `Option` if the function returns `Some`, or `None` + * if it returns `None`. + * + * **When to use** + * + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. + * + * **Details** + * + * - `None` → `None` + * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` + * + * **Example** (Validating without transforming) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const getInteger = (n: number) => + * Number.isInteger(n) ? Option.some(n) : Option.none() + * + * Option.tap(Option.some(1), getInteger) // => Option.some(1) + * Option.tap(Option.some(1.14), getInteger) // => Option.none() + * ``` + * + * @see {@link flatMap} when you want to transform the value + * @see {@link filter} for predicate-based filtering + * + * @category sequencing + * @since 2.0.0 + */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => flatMap(self, a => map(f(a), () => a))); +/** + * Combines two `Option`s into a `Some` containing a tuple `[A, B]` if both + * are `Some`. + * + * **When to use** + * + * Use when you need to require two `Option` values to both be `Some` and keep + * both values as a tuple. + * + * **Details** + * + * - Both `Some` → `Some([a, b])` + * - Either `None` → `None` + * + * **Example** (Pairing two Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.product(Option.some("hello"), Option.some(42)) // => Option.some(["hello", 42]) + * Option.product(Option.none(), Option.some(42)) // => Option.none() + * ``` + * + * @see {@link zipWith} to combine with a function instead of a tuple + * @see {@link all} to combine many `Option`s + * + * @category combining + * @since 2.0.0 + */ +const product = (self, that) => isSome(self) && isSome(that) ? some([self.value, that.value]) : none(); +/** + * Combines a primary `Option` with an iterable of `Option`s into a tuple if + * all are `Some`. + * + * **When to use** + * + * Use when you need several `Option` values of the same type to all be `Some` + * and return them as a non-empty tuple. + * + * **Details** + * + * - All `Some` → `Some([self.value, ...rest])` + * - Any `None` → `None` + * + * **Example** (Combining many Options) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const first = Option.some(1) + * const rest = [Option.some(2), Option.some(3)] + * + * Option.productMany(first, rest) // => Option.some([1, 2, 3]) + * Option.productMany(first, [Option.some(2), Option.none()]) // => Option.none() + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link all} for tuples, structs, and iterables + * + * @category combining + * @since 2.0.0 + */ +const productMany = (self, collection) => { + if (isNone(self)) { + return none(); + } + const out = [self.value]; + for (const o of collection) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); +}; +/** + * Combines a structure of `Option`s (tuple, struct, or iterable) into a single + * `Option` containing the unwrapped structure. + * + * **When to use** + * + * Use when you need to combine multiple `Option` values into one while + * preserving the input shape, with any `None` making the result `None`. + * + * **Details** + * + * - Tuple input → `Option` of a tuple with the same length + * - Struct input → `Option` of a struct with the same keys + * - Iterable input → `Option` of an `Array` + * - Any `None` in the input → entire result is `None` + * + * **Example** (Combining a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * // ┌─── Option<[string, number]> + * // ▼ + * const tuple = Option.all([maybeName, maybeAge]) // => Option.some(["John", 25]) + * + * // ┌─── Option<{ name: string; age: number; }> + * // ▼ + * const struct = Option.all({ name: maybeName, age: maybeAge }) // => Option.some({ name: "John", age: 25 }) + * ``` + * + * @see {@link product} for combining exactly two + * @see {@link productMany} for a homogeneous collection + * + * @category combining + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const o of input) { + if (isNone(o)) { + return none(); + } + out.push(o.value); + } + return some(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const o = input[key]; + if (isNone(o)) { + return none(); + } + _internal_record_js__rspack_import_4/* .assignProperty */.x(out, key, o.value); + } + return some(out); +}; +/** + * Combines two `Option`s using a provided function. + * + * **When to use** + * + * Use when you need to combine two present `Option` values into a computed + * result. + * + * **Details** + * + * - Both `Some` → applies `f(a, b)` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Combining with a function) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.zipWith( + * Option.some("John"), + * Option.some(25), + * (name, age) => ({ name: name.toUpperCase(), age }) + * ) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link product} to combine into a tuple instead + * @see {@link lift2} to lift a binary function + * + * @category zipping + * @since 2.0.0 + */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, that, f) => map(product(self, that), ([a, b]) => f(a, b))); +/** + * Reduces an iterable of `Option`s to a single value, skipping `None` entries. + * + * **When to use** + * + * Use when you need to aggregate values from a collection where some may be + * absent. + * + * **Details** + * + * - Iterates through the collection, applying `f` only to `Some` values + * - `None` values are skipped entirely + * - Returns the accumulated result + * + * **Example** (Summing present values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * const items = [Option.some(1), Option.none(), Option.some(2), Option.none()] + * + * pipe(items, Option.reduceCompact(0, (b, a) => b + a)) // => 3 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduceCompact = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(3, (self, b, f) => { + let out = b; + for (const oa of self) { + if (isSome(oa)) { + out = f(out, oa.value); + } + } + return out; +}); +/** + * Converts an `Option` into an `Array`. + * + * **When to use** + * + * Use when you need to pass an `Option` to array-based APIs or spread optional + * values into collections. + * + * **Details** + * + * - `Some` → single-element array `[value]` + * - `None` → empty array `[]` + * + * **Example** (Converting to an array) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.toArray(Option.some(1)) // => [1] + * Option.toArray(Option.none()) // => [] + * ``` + * + * @see {@link fromIterable} for the inverse direction + * + * @category converting + * @since 2.0.0 + */ +const toArray = self => isNone(self) ? [] : [self.value]; +/** + * Splits an `Option` into two `Option`s using a function that returns a `Result`. + * + * **When to use** + * + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. + * + * **Details** + * + * - `None` → `[None, None]` + * - `Some` where `f` returns `Err` → `[Some(error), None]` + * - `Some` where `f` returns `Ok` → `[None, Some(value)]` + * + * **Example** (Partitioning by Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parseNumber = (s: string): Result.Result => { + * const n = Number(s) + * return isNaN(n) ? Result.fail("Not a number") : Result.succeed(n) + * } + * + * Option.partitionMap(Option.some("42"), parseNumber) // => [Option.none(), Option.some(42)] + * Option.partitionMap(Option.some("abc"), parseNumber) // => [Option.some("Not a number"), Option.none()] + * Option.partitionMap(Option.none(), parseNumber) // => [Option.none(), Option.none()] + * ``` + * + * @see {@link filter} for simple predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const partitionMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return [none(), none()]; + } + const e = f(self.value); + return _internal_result_js__rspack_import_2/* .isFailure */.N6(e) ? [some(e.failure), none()] : [none(), some(e.success)]; +}); +/** + * Transforms and filters an `Option` using a `Filter` callback. + * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * + * The callback returns a `Result`: `Result.succeed` keeps and transforms the + * value, while `Result.fail` discards it. + * + * **Example** (Filtering and transforming) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Option.filterMap( + * Option.some(2), + * (n) => (n % 2 === 0 ? Result.succeed(`Even: ${n}`) : Result.failVoid) + * ) // => Option.some("Even: 2") + * ``` + * + * @see {@link filter} for predicate-based filtering + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, f) => { + if (isNone(self)) { + return none(); + } + const next = f(self.value); + return _internal_result_js__rspack_import_2/* .isSuccess */.oJ(next) ? some(next.success) : none(); +}); +/** + * Filters an `Option` using a predicate. Returns `None` if the predicate is + * not satisfied or the input is `None`. + * + * **When to use** + * + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. + * + * **Details** + * + * - `None` → `None` + * - `Some` where `predicate(value)` is `true` → `Some(value)` + * - `Some` where `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Filtering with a predicate) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const removeEmpty = (input: Option.Option) => + * Option.filter(input, (value) => value !== "") + * + * removeEmpty(Option.some("hello")) // => Option.some("hello") + * removeEmpty(Option.some("")) // => Option.none() + * removeEmpty(Option.none()) // => Option.none() + * ``` + * + * @see {@link filterMap} to transform and filter simultaneously + * @see {@link exists} to test without filtering + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => isNone(self) ? none() : predicate(self.value) ? some(self.value) : none()); +/** + * Creates an `Equivalence` for `Option` from an `Equivalence` for `A`. + * + * **When to use** + * + * Use when you need equality to treat two `None` values as equal and compare + * two `Some` values with a supplied equality rule. + * + * **Details** + * + * - `None` vs `None` → `true` + * - `Some` vs `None` (or vice versa) → `false` + * - `Some(a)` vs `Some(b)` → delegates to the provided `Equivalence` + * + * **Example** (Comparing Options) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const eq = Option.makeEquivalence(Equivalence.strictEqual()) + * + * eq(Option.some(1), Option.some(1)) // => true + * eq(Option.some(1), Option.some(2)) // => false + * eq(Option.none(), Option.none()) // => true + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = isEquivalent => _Equivalence_js__rspack_import_5/* .make */.L8((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value)); +/** + * Creates an `Order` for `Option` from an `Order` for `A`. + * + * **When to use** + * + * Use when you need to sort `Some` and `None` values, with `None` ordered + * before present values and present values compared by a supplied ordering + * rule. + * + * **Details** + * + * - `None` is considered less than any `Some` + * - Two `Some` values are compared using the provided `Order` + * - Two `None` values are equal (returns `0`) + * + * **Example** (Ordering Options) + * + * ```ts import.meta.vitest + * import { Number as N, Option } from "effect" + * + * const ord = Option.makeOrder(N.Order) + * + * ord(Option.none(), Option.some(1)) // => -1 + * ord(Option.some(1), Option.none()) // => 1 + * ord(Option.some(1), Option.some(2)) // => -1 + * ``` + * + * @category sorting + * @since 4.0.0 + */ +const makeOrder = O => _Order_js__rspack_import_6/* .make */.L8((self, that) => isSome(self) ? isSome(that) ? O(self.value, that.value) : 1 : -1); +/** + * Lifts a binary function to operate on two `Option` values. + * + * **When to use** + * + * Use when you need to reuse an existing binary function with two `Option` + * values. + * + * **Details** + * + * - Both `Some` → applies `f` and wraps in `Some` + * - Either `None` → `None` + * + * **Example** (Lifting addition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const addOptions = Option.lift2((a: number, b: number) => a + b) + * + * addOptions(Option.some(2), Option.some(3)) // => Option.some(5) + * addOptions(Option.some(2), Option.none()) // => Option.none() + * ``` + * + * @see {@link zipWith} for a non-lifted variant + * + * @category lifting + * @since 2.0.0 + */ +const lift2 = f => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, that) => zipWith(self, that, f)); +/** + * Lifts a `Predicate` or `Refinement` into the `Option` context: returns + * `Some(value)` when the predicate holds, `None` otherwise. + * + * **When to use** + * + * Use to convert a boolean check into an `Option`-returning function + * - Validating input and wrapping it in `Option` + * + * **Details** + * + * - `predicate(value)` is `true` → `Some(value)` + * - `predicate(value)` is `false` → `None` + * - Supports refinements for type narrowing + * + * **Example** (Validating positive numbers) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const parsePositive = Option.liftPredicate((n: number) => n > 0) + * + * parsePositive(1) // => Option.some(1) + * parsePositive(-1) // => Option.none() + * ``` + * + * @see {@link filter} to apply a predicate to an existing `Option` + * @see {@link toRefinement} for the inverse direction + * + * @category lifting + * @since 2.0.0 + */ +const liftPredicate = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (b, predicate) => predicate(b) ? some(b) : none()); +/** + * Checks whether an `Option` contains a value equivalent to the given one, using a + * custom `Equivalence`. + * + * **When to use** + * + * Use when you need to test whether an `Option` contains a value using a + * custom equality check. + * + * **Details** + * + * - `Some` where `isEquivalent(value, a)` is `true` → `true` + * - `Some` where not equivalent, or `None` → `false` + * + * **Example** (Checking with custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Option } from "effect" + * + * const check = Option.containsWith(Equivalence.strictEqual()) + * + * Option.some(2).pipe(check(2)) // => true + * Option.some(1).pipe(check(2)) // => false + * Option.none().pipe(check(2)) // => false + * ``` + * + * @see {@link contains} for a version using default equality + * + * @category predicates + * @since 2.0.0 + */ +const containsWith = isEquivalent => (0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, a) => isNone(self) ? false : isEquivalent(self.value, a)); +/** + * Checks whether an `Option` contains a value equal to the given one, using default + * structural equality. + * + * **When to use** + * + * Use when you need a quick membership test for an `Option` value using + * standard equality. + * + * **Details** + * + * - `Some` where `Equal.equals(value, a)` is `true` → `true` + * - `Some` where not equal, or `None` → `false` + * + * **Example** (Checking containment) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * Option.some(2).pipe(Option.contains(2)) // => true + * Option.some(1).pipe(Option.contains(2)) // => false + * Option.none().pipe(Option.contains(2)) // => false + * ``` + * + * @see {@link containsWith} for custom equality + * @see {@link exists} to test with a predicate + * + * @category predicates + * @since 2.0.0 + */ +const contains = /*#__PURE__*/containsWith(/*#__PURE__*/_Equal_js__rspack_import_7/* .asEquivalence */.jI()); +/** + * Checks whether the value in a `Some` satisfies a predicate or refinement. + * + * **When to use** + * + * Use to check a condition on an optional value without unwrapping + * + * **Details** + * + * - `None` → `false` + * - `Some` where `predicate(value)` is `true` → `true` + * - `Some` where `predicate(value)` is `false` → `false` + * - With a refinement, narrows the `Option` type on `true` + * + * **Example** (Testing a condition) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * + * Option.some(2).pipe(Option.exists(isEven)) // => true + * Option.some(1).pipe(Option.exists(isEven)) // => false + * Option.none().pipe(Option.exists(isEven)) // => false + * ``` + * + * @see {@link filter} to keep or discard based on a predicate + * @see {@link contains} to test for a specific value + * + * @category predicates + * @since 2.0.0 + */ +const exists = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, refinement) => isNone(self) ? false : refinement(self.value)); +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Gives a name to the value of an `Option`, creating a single-key record + * inside `Some`. Starting point for the do notation pipeline. + * + * **When to use** + * + * Use when you need to start an `Option` do notation chain by naming the first + * value. + * + * **Example** (Starting do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.some(2), + * Option.bindTo("x"), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting with an empty record + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bindTo */.Jr(map); +const let_ = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .let_ */.zM(map); + +/** + * Adds an `Option` value to the do notation record under a given name. If the + * `Option` is `None`, the whole pipeline short-circuits to `None`. + * + * **When to use** + * + * Use when you need to sequence `Option` computations in do notation. + * + * **Example** (Binding Option values) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link Do} for starting the chain + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/_internal_doNotation_js__rspack_import_8/* .bind */.oI(map, flatMap); +/** + * Provides an `Option` containing an empty record `{}`, used as the starting point for + * do notation chains. + * + * **When to use** + * + * Use when you need to start an `Option` do notation pipeline before adding + * bindings. + * + * **Example** (Building Option pipelines with do notation) + * + * ```ts import.meta.vitest + * import { Option, pipe } from "effect" + * + * pipe( + * Option.Do, + * Option.bind("x", () => Option.some(2)), + * Option.bind("y", () => Option.some(3)), + * Option.let("sum", ({ x, y }) => x + y), + * Option.filter(({ x, y }) => x * y > 5) + * ) // => Option.some({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add `Option` values + * @see {@link let_ let} to add plain values + * @see {@link bindTo} to start by naming an existing `Option` + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/some({}); +/** + * Provides generator-based syntax for `Option`, similar to `async`/`await` but for + * optional values. Yielding a `None` short-circuits the generator to `None`. + * + * **When to use** + * + * Use when you need generator syntax for a sequence of `Option` steps that + * should short-circuit on `None`. + * + * **Details** + * + * - Each `yield*` unwraps a `Some` value or short-circuits to `None` + * - The return value is wrapped in `Some` + * - No `Effect` runtime is needed + * + * **Example** (Sequencing Option computations with generator syntax) + * + * ```ts import.meta.vitest + * import { Option } from "effect" + * + * const maybeName: Option.Option = Option.some("John") + * const maybeAge: Option.Option = Option.some(25) + * + * Option.gen(function*() { + * const name = (yield* maybeName).toUpperCase() + * const age = yield* maybeAge + * return { name, age } + * }) // => Option.some({ name: "JOHN", age: 25 }) + * ``` + * + * @see {@link Do} / {@link bind} for the do notation alternative + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isNone(current)) { + return current; + } + state = iterator.next(current.value); + } + return some(state.value); +}; +/** + * Creates a `Reducer` for `Option` that prioritizes the first non-`None` + * value and combines values when both are `Some`. + * + * **When to use** + * + * Use to build an `Option` reducer that falls back to the first available value + * when either side may be absent. + * + * **Details** + * + * - `None` + `None` → `None` + * - `Some(a)` + `None` → `Some(a)` + * - `None` + `Some(b)` → `Some(b)` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * - Initial value is `None` + * + * **Example** (Reducing with first-wins semantics) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducer(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.none(), Option.some(2)]) // => Option.some(3) + * ``` + * + * @see {@link makeReducerFailFast} for fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducer(combiner) { + return _Reducer_js__rspack_import_9/* .make */.L((self, that) => { + if (isNone(self)) return that; + if (isNone(that)) return self; + return some(combiner.combine(self.value, that.value)); + }, none()); +} +/** + * Creates a `Combiner` for `Option` with fail-fast semantics: returns `None` + * if either operand is `None`. + * + * **When to use** + * + * Use when you need an `Option` combiner that returns `None` unless both + * operands are `Some`. + * + * **Details** + * + * - `None` + anything → `None` + * - anything + `None` → `None` + * - `Some(a)` + `Some(b)` → `Some(combine(a, b))` + * + * **Example** (Fail-fast combining) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const combiner = Option.makeCombinerFailFast(Number.ReducerSum) + * combiner.combine(Option.some(1), Option.some(2)) // => Option.some(3) + * combiner.combine(Option.some(1), Option.none()) // => Option.none() + * ``` + * + * @see {@link makeReducerFailFast} to get a full `Reducer` + * + * @category constructors + * @since 4.0.0 + */ +function makeCombinerFailFast(combiner) { + return _Combiner_js__rspack_import_10/* .make */.L8((self, that) => { + if (isNone(self) || isNone(that)) return none(); + return some(combiner.combine(self.value, that.value)); + }); +} +/** + * Creates a `Reducer` for `Option` by lifting an existing `Reducer` with + * fail-fast semantics. + * + * **When to use** + * + * Use when you need to reduce `Option` values with fail-fast semantics, where + * any `None` aborts the entire result instead of being skipped. + * + * **Details** + * + * - Initial value is `Some(reducer.initialValue)` + * - Combines only when both operands are `Some` + * - Any `None` causes the result to become `None` immediately + * + * **Example** (Fail-fast reducing) + * + * ```ts import.meta.vitest + * import { Number, Option } from "effect" + * + * const reducer = Option.makeReducerFailFast(Number.ReducerSum) + * reducer.combineAll([Option.some(1), Option.some(2)]) // => Option.some(3) + * reducer.combineAll([Option.some(1), Option.none()]) // => Option.none() + * ``` + * + * @see {@link makeCombinerFailFast} for just the combiner + * @see {@link makeReducer} for non-fail-fast semantics + * + * @category constructors + * @since 4.0.0 + */ +function makeReducerFailFast(reducer) { + const combine = makeCombinerFailFast(reducer).combine; + const initialValue = some(reducer.initialValue); + return _Reducer_js__rspack_import_9/* .make */.L(combine, initialValue, collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + if (isNone(out)) return out; + } + return out; + }); +} +//# sourceMappingURL=Option.js.map +__webpack_require__.d(__webpack_exports__, { + makeCombinerFailFast: () => (makeCombinerFailFast), + makeReducer: () => (makeReducer), + makeReducerFailFast: () => (makeReducerFailFast) +}, { + Do: Do, + all: all, + andThen: andThen, + as: as, + asVoid: asVoid, + bind: bind, + bindTo: bindTo, + composeK: composeK, + contains: contains, + containsWith: containsWith, + exists: exists, + filter: filter, + filterMap: filterMap, + firstSomeOf: firstSomeOf, + flatMap: flatMap, + flatMapNullishOr: flatMapNullishOr, + flatten: flatten, + fromIterable: fromIterable, + fromNullOr: fromNullOr, + fromNullishOr: fromNullishOr, + fromUndefinedOr: fromUndefinedOr, + gen: gen, + getFailure: getFailure, + getOrElse: getOrElse, + getOrNull: getOrNull, + getOrThrow: getOrThrow, + getOrThrowWith: getOrThrowWith, + getOrUndefined: getOrUndefined, + getSuccess: getSuccess, + isNone: isNone, + isOption: isOption, + isSome: isSome, + "let": let_, + lift2: lift2, + liftNullishOr: liftNullishOr, + liftPredicate: liftPredicate, + liftThrowable: liftThrowable, + makeEquivalence: makeEquivalence, + makeOrder: makeOrder, + map: map, + match: match, + none: none, + orElse: orElse, + orElseResult: orElseResult, + orElseSome: orElseSome, + partitionMap: partitionMap, + product: product, + productMany: productMany, + reduceCompact: reduceCompact, + some: some, + tap: tap, + toArray: toArray, + toRefinement: toRefinement, + "void": void_, + zipLeft: zipLeft, + zipRight: zipRight, + zipWith: zipWith +}); + + +}, +"./node_modules/effect/dist/Order.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/** + * Defines comparison functions for ordered values. + * + * An `Order` compares two `A` values and returns whether the first is less + * than, equal to, or greater than the second. Orders are used for sorting, + * choosing minimum or maximum values, checking ranges, and building ordered data + * structures. This module includes built-in orders, constructors for custom + * orders, tools for reversing and combining comparisons, tuple and struct + * helpers, comparison predicates, clamping, and reducer support. + * + * @since 2.0.0 + */ + + +/** + * Creates a new `Order` instance from a comparison function. + * + * **When to use** + * + * Use when you need a sorting rule not covered by the built-in orders or input + * mapping helpers, and you can provide a total comparison. + * + * **Details** + * + * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns + * `0` without calling the comparison function. The comparison function should + * return `-1`, `0`, or `1`, and the returned order satisfies total ordering + * laws when the comparison function does. + * + * **Example** (Creating an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.make<{ name: string; age: number }>((self, that) => { + * if (self.age < that.age) return -1 + * if (self.age > that.age) return 1 + * return 0 + * }) + * + * byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1 + * byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1 + * ``` + * + * @see {@link mapInput} to transform an order by mapping the input type + * @see {@link combine} to combine multiple orders + * @category constructors + * @since 2.0.0 + */ +function make(compare) { + return (self, that) => self === that ? 0 : compare(self, that); +} +/** + * Order instance for strings that compares them lexicographically using JavaScript's `<` operator. + * + * **When to use** + * + * Use when you need lexicographic string ordering. + * + * **Details** + * + * Uses lexicographic dictionary ordering. The empty string is less than any + * non-empty string, and comparisons are case-sensitive. + * + * **Example** (Ordering strings) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.String("apple", "banana") // => -1 + * Order.String("banana", "apple") // => 1 + * Order.String("apple", "apple") // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a string property + * @see {@link Struct} to combine with other orders for struct comparison + * @category instances + * @since 4.0.0 + */ +const String = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for numbers that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for numbers. + * + * **Details** + * + * `0` is considered equal to `-0`. All `NaN` values are considered equal to + * each other, and any `NaN` is considered less than any non-`NaN` number. All + * other values use standard numeric comparison. + * + * **Example** (Ordering numbers) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Number(1, 1) // => 0 + * Order.Number(1, 2) // => -1 + * Order.Number(2, 1) // => 1 + * + * Order.Number(0, -0) // => 0 + * Order.Number(NaN, 1) // => -1 + * ``` + * + * @see {@link mapInput} to compare objects by a number property + * @see {@link BigInt} for bigint comparisons + * @category instances + * @since 4.0.0 + */ +const Number = /*#__PURE__*/make((self, that) => { + if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0; + if (globalThis.Number.isNaN(self)) return -1; // NaN < any number + if (globalThis.Number.isNaN(that)) return 1; // any number > NaN + return self < that ? -1 : 1; +}); +/** + * Order instance for booleans where `false` is considered less than `true`. + * + * **When to use** + * + * Use when you need boolean ordering where `false` comes before `true`. + * + * **Details** + * + * `false` is less than `true`, and equal values return `0`. + * + * **Example** (Ordering booleans) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.Boolean(false, true) // => -1 + * Order.Boolean(true, false) // => 1 + * Order.Boolean(true, true) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a boolean property + * @category instances + * @since 4.0.0 + */ +const Boolean = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Order instance for bigints that compares them numerically. + * + * **When to use** + * + * Use when you need numeric ordering for `bigint` values. + * + * **Details** + * + * Uses standard numeric comparison for bigint values and handles arbitrarily + * large integers. + * + * **Example** (Ordering BigInts) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * Order.BigInt(1n, 2n) // => -1 + * Order.BigInt(2n, 1n) // => 1 + * Order.BigInt(1n, 1n) // => 0 + * ``` + * + * @see {@link Number} for regular number comparisons + * @see {@link mapInput} to compare objects by a bigint property + * @category instances + * @since 4.0.0 + */ +const BigInt = /*#__PURE__*/(/* unused pure expression or super */ null && (make((self, that) => self < that ? -1 : 1))); +/** + * Creates a new `Order` that reverses the comparison order of the input `Order`. + * + * **When to use** + * + * Use when you need the reverse of an existing order. + * + * **Details** + * + * Returns a new order that swaps the arguments before comparison. If the + * original order returns `-1`, the flipped order returns `1`, and vice versa. + * Equal comparisons remain `0`. + * + * **Example** (Reversing an Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const flip = Order.flip(Order.Number) + * + * flip(1, 2) // => 1 + * flip(2, 1) // => -1 + * flip(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine orders for multi-criteria comparison + * @category combinators + * @since 4.0.0 + */ +function flip(O) { + return make((self, that) => O(that, self)); +} +/** + * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, + * and if the values are equal, then compares using the second `Order`. + * + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** + * + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. + * + * **Example** (Combining two Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * const byAgeAndName = Order.combine(byAge, byName) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * const person3 = { name: "Charlie", age: 25 } + * + * byAgeAndName(person1, person2) // => -1 + * byAgeAndName(person1, person3) // => 1 + * ``` + * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types + * @category combining + * @since 2.0.0 + */ +const combine = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => make((a1, a2) => { + const out = self(a1, a2); + if (out !== 0) { + return out; + } + return that(a1, a2); +})))); +/** + * Creates an `Order` that considers all values as equal. + * + * **When to use** + * + * Use when you need an order that treats all values as equal. + * + * **Details** + * + * Always returns `0` regardless of input values, making it useful as a neutral + * element in order composition. + * + * **Example** (Ordering with an always-equal Order) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const alwaysEqualOrder = Order.alwaysEqual() + * + * alwaysEqualOrder(1, 2) // => 0 + * alwaysEqualOrder(2, 1) // => 0 + * alwaysEqualOrder(1, 1) // => 0 + * ``` + * + * @see {@link combine} to combine with other orders + * @category constructors + * @since 4.0.0 + */ +function alwaysEqual() { + return make(() => 0); +} +/** + * Combines all `Order` instances in the provided collection into a single `Order`. + * The resulting `Order` compares using each `Order` in sequence until a non-zero result is found. + * + * **When to use** + * + * Use when you need tie-breaking across a variable number of orders. + * + * **Details** + * + * Applies orders in iteration order and short-circuits on the first non-zero + * result. It returns `0` only if all orders return `0`. + * + * **Example** (Combining multiple Orders) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byAge = Order.mapInput( + * Order.Number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.String, + * (person: { name: string; age: number }) => person.name + * ) + * + * const combinedOrder = Order.combineAll([byAge, byName]) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 30 } + * + * combinedOrder(person1, person2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link makeReducer} to create a reducer for combining orders + * @category combining + * @since 2.0.0 + */ +function combineAll(collection) { + return make((a1, a2) => { + let out = 0; + for (const O of collection) { + out = O(a1, a2); + if (out !== 0) { + return out; + } + } + return out; + }); +} +/** + * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that + * maps values of type `B` to values of type `A`. + * + * **When to use** + * + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. + * + * **Example** (Mapping Input) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const byLength = Order.mapInput(Order.Number, (s: string) => s.length) + * + * byLength("a", "bb") // => -1 + * byLength("bb", "a") // => 1 + * byLength("aa", "bb") // => 0 + * ``` + * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields + * @category mapping + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => make((b1, b2) => self(f(b1), f(b2)))); +/** + * Order instance for `Date` objects that compares them chronologically by their timestamp. + * + * **When to use** + * + * Use when you need chronological ordering for JavaScript date values. + * + * **Details** + * + * Compares dates by their underlying timestamp in milliseconds since the epoch. + * Earlier dates are less than later dates. Invalid dates are compared through + * their `getTime()` result. + * + * **Example** (Ordering Dates) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const date1 = new Date("2023-01-01") + * const date2 = new Date("2023-01-02") + * + * Order.Date(date1, date2) // => -1 + * Order.Date(date2, date1) // => 1 + * Order.Date(date1, date1) // => 0 + * ``` + * + * @see {@link mapInput} to compare objects by a date property + * @category instances + * @since 2.0.0 + */ +const Date = /*#__PURE__*/(/* unused pure expression or super */ null && (mapInput(Number, date => date.getTime()))); +/** + * Creates an `Order` for a tuple type based on orders for each element. + * + * **When to use** + * + * Use when you need fixed-length tuple ordering with per-position orders. + * + * **Details** + * + * Compares tuples element-by-element using the corresponding order and stops at + * the first non-zero comparison result. Tuples must have the same length as the + * order collection, and the result is `0` only if all elements are equal. + * + * **Example** (Ordering tuples) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const tupleOrder = Order.Tuple([Order.Number, Order.String]) + * + * tupleOrder([1, "a"], [2, "b"]) // => -1 + * tupleOrder([1, "b"], [1, "a"]) // => 1 + * tupleOrder([1, "a"], [1, "a"]) // => 0 + * ``` + * + * @see {@link Array} to compare arrays with length consideration + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return make((self, that) => { + const len = elements.length; + for (let i = 0; i < len; i++) { + const o = elements[i](self[i], that[i]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * @since 4.0.0 + */ +function Array_(O) { + return make((self, that) => { + const aLen = self.length; + const bLen = that.length; + const len = Math.min(aLen, bLen); + for (let i = 0; i < len; i++) { + const o = O(self[i], that[i]); + if (o !== 0) { + return o; + } + } + return Number(aLen, bLen); + }); +} + +/** + * Creates an `Order` for structs by applying the given `Order`s to each property in sequence. + * + * **When to use** + * + * Use when you need multi-field ordering for objects with known properties. + * + * **Details** + * + * Compares structs field-by-field in the key order of the fields object and + * stops at the first non-zero comparison result. Field order matters: earlier + * fields take precedence. The result is `0` only if all fields are equal. + * + * **Example** (Ordering structs) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const personOrder = Order.Struct({ + * name: Order.String, + * age: Order.Number + * }) + * + * const person1 = { name: "Alice", age: 30 } + * const person2 = { name: "Bob", age: 25 } + * const person3 = { name: "Alice", age: 25 } + * + * personOrder(person1, person2) // => -1 + * personOrder(person1, person3) // => 1 + * personOrder(person1, person1) // => 0 + * ``` + * + * @see {@link combine} to combine orders manually + * @see {@link mapInput} to extract and compare by a single property + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return make((self, that) => { + for (const key of keys) { + const o = fields[key](self[key], that[key]); + if (o !== 0) { + return o; + } + } + return 0; + }); +} +/** + * Checks whether one value is strictly less than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1`, meaning the first value is less + * than the second. Equal or greater values return `false`. + * + * **Example** (Checking less-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanNumber = Order.isLessThan(Order.Number) + * + * isLessThanNumber(1, 2) // => true + * isLessThanNumber(2, 1) // => false + * isLessThanNumber(1, 1) // => false + * ``` + * + * @see {@link isLessThanOrEqualTo} for non-strict less than or equal + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThan = O => dual(2, (self, that) => O(self, that) === -1); +/** + * Checks whether one value is strictly greater than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1`, meaning the first value is greater + * than the second. Equal or lesser values return `false`. + * + * **Example** (Checking greater-than comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanNumber = Order.isGreaterThan(Order.Number) + * + * isGreaterThanNumber(2, 1) // => true + * isGreaterThanNumber(1, 2) // => false + * isGreaterThanNumber(1, 1) // => false + * ``` + * + * @see {@link isGreaterThanOrEqualTo} for non-strict greater than or equal + * @see {@link isLessThan} for strict less than + * @category predicates + * @since 4.0.0 + */ +const isGreaterThan = O => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, that) => O(self, that) === 1); +/** + * Checks whether one value is less than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than-or-equal predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `-1` or `0`, and returns `false` only if + * the order returns `1`. + * + * **Example** (Checking less-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number) + * + * isLessThanOrEqualToNumber(1, 2) // => true + * isLessThanOrEqualToNumber(1, 1) // => true + * isLessThanOrEqualToNumber(2, 1) // => false + * ``` + * + * @see {@link isLessThan} for strict less than + * @see {@link isGreaterThan} for strict greater than + * @category predicates + * @since 4.0.0 + */ +const isLessThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== 1); +/** + * Checks whether one value is greater than or equal to another according to the given order. + * + * **When to use** + * + * Use when you need a boolean greater-than-or-equal predicate using an + * `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1` or `0`, and returns `false` only if + * the order returns `-1`. + * + * **Example** (Checking greater-than-or-equal comparisons) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number) + * + * isGreaterThanOrEqualToNumber(2, 1) // => true + * isGreaterThanOrEqualToNumber(1, 1) // => true + * isGreaterThanOrEqualToNumber(1, 2) // => false + * ``` + * + * @see {@link isGreaterThan} for strict greater than + * @see {@link isLessThanOrEqualTo} for less than or equal + * @category predicates + * @since 4.0.0 + */ +const isGreaterThanOrEqualTo = O => dual(2, (self, that) => O(self, that) !== -1); +/** + * Returns the minimum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the smaller of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as less than or equal to the other value. If + * values are equal, the first argument is returned. + * + * **Example** (Selecting the minimum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const minNumber = Order.min(Order.Number) + * + * minNumber(1, 2) // => 1 + * minNumber(2, 1) // => 1 + * minNumber(1, 1) // => 1 + * ``` + * + * @see {@link max} for the maximum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const min = O => dual(2, (self, that) => self === that || O(self, that) < 1 ? self : that); +/** + * Returns the maximum of two values according to the given order. If they are equal, returns the first argument. + * + * **When to use** + * + * Use when you need to select the larger of two values according to an + * `Order`. + * + * **Details** + * + * Returns the value that compares as greater than or equal to the other value. + * If values are equal, the first argument is returned. + * + * **Example** (Selecting the maximum value) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const maxNumber = Order.max(Order.Number) + * + * maxNumber(1, 2) // => 2 + * maxNumber(2, 1) // => 2 + * maxNumber(1, 1) // => 1 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link clamp} to clamp a value between min and max + * @category comparisons + * @since 2.0.0 + */ +const max = O => dual(2, (self, that) => self === that || O(self, that) > -1 ? self : that); +/** + * Restricts a value between a minimum and a maximum according to the given order. + * + * **When to use** + * + * Use when you need to clamp a value to an inclusive range according to an + * `Order`. + * + * **Details** + * + * Returns the value itself when it is between minimum and maximum, inclusive. + * Values below the range return minimum, and values above the range return + * maximum. The minimum must be less than or equal to the maximum according to + * the order. + * + * **Example** (Clamping values) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const clamp = Order.clamp(Order.Number)({ minimum: 1, maximum: 5 }) + * + * clamp(3) // => 3 + * clamp(0) // => 1 + * clamp(6) // => 5 + * ``` + * + * @see {@link min} for the minimum of two values + * @see {@link max} for the maximum of two values + * @see {@link isBetween} to check if a value is within a range + * @category comparisons + * @since 2.0.0 + */ +const clamp = O => dual(2, (self, options) => min(O)(options.maximum, max(O)(options.minimum, self))); +/** + * Checks whether a value is between a minimum and a maximum (inclusive) according to the given order. + * + * **When to use** + * + * Use when you need range checks that respect domain-specific ordering, such as + * dates, versions, or custom priorities, instead of JavaScript numeric + * comparison. + * + * **Details** + * + * Returns `true` when the value is greater than or equal to minimum and less + * than or equal to maximum. Values outside the range return `false`. Both + * bounds are inclusive. + * + * **Example** (Checking ranges) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const betweenNumber = Order.isBetween(Order.Number) + * + * betweenNumber(5, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(1, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(10, { minimum: 1, maximum: 10 }) // => true + * betweenNumber(0, { minimum: 1, maximum: 10 }) // => false + * betweenNumber(11, { minimum: 1, maximum: 10 }) // => false + * ``` + * + * @see {@link clamp} to clamp a value to a range + * @see {@link isLessThanOrEqualTo} for less than or equal check + * @see {@link isGreaterThanOrEqualTo} for greater than or equal check + * @category predicates + * @since 4.0.0 + */ +const isBetween = O => dual(2, (self, options) => !isLessThan(O)(self, options.minimum) && !isGreaterThan(O)(self, options.maximum)); +/** + * Creates a `Reducer` for combining `Order` instances, useful for aggregating orders in collections. + * + * **When to use** + * + * Use when you need a reducer that combines orders. + * + * **Details** + * + * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as + * the identity element for empty collections, and uses `combineAll` for + * combining collections of orders. The reducer can be used with fold operations + * on collections. + * + * **Example** (Creating a Reducer) + * + * ```ts import.meta.vitest + * import { Order } from "effect" + * + * const reducer = Order.makeReducer() + * const orders = [Order.Number, Order.flip(Order.Number)] + * + * const combined = reducer.combineAll(orders) + * combined(1, 2) // => -1 + * ``` + * + * @see {@link combine} to combine two orders + * @see {@link combineAll} to combine multiple orders + * @see {@link Reducer} for reducing orders as a collection operation + * @category constructors + * @since 4.0.0 + */ +function makeReducer() { + return Reducer.make(combine, () => 0, combineAll); +} +//# sourceMappingURL=Order.js.map +__webpack_require__.d(__webpack_exports__, { + L8: () => (make), + O3: () => (Array_) +}, { + wN: Number, + yJ: isGreaterThan, + zQ: mapInput +}); + + +}, +"./node_modules/effect/dist/Pipeable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * 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. + * + * @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 + * ``` + * + * @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; + } + } +}; +/** + * Reusable prototype that implements `Pipeable.pipe`. + * + * **When to use** + * + * Use when classes or object prototypes can reuse this value when they need the + * standard pipe implementation backed by `pipeArguments`. + * + * @category prototypes + * @since 3.15.0 + */ +const Prototype = (/* unused pure expression or super */ null && ({ + pipe() { + return pipeArguments(this, arguments); + } +})); +/** + * Provides a base constructor whose instances implement the standard `Pipeable.pipe` + * method. + * + * **When to use** + * + * Use when you need to define a class that supports Effect-style method + * chaining through `.pipe(...)`. + * + * @category constructors + * @since 3.15.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function PipeableBase() {} + PipeableBase.prototype = Prototype; + return PipeableBase; +}())); +/** + * Returns a subclass of the provided class that adds the standard `pipe` + * method. + * + * **When to use** + * + * Use to add pipe support to an existing class without extending a base class + * or modifying its prototype. + * + * **Details** + * + * The original constructor and instance members are preserved, and the added + * method delegates to `pipeArguments`. + * + * @see {@link Prototype} for a reusable prototype object + * @see {@link Class} for a base constructor to extend + * @category constructors + * @since 4.0.0 + */ +const Mixin = klass => class extends klass { + pipe() { + return pipeArguments(this, arguments); + } +}; +//# sourceMappingURL=Pipeable.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + tT: pipeArguments +}); + + +}, +"./node_modules/effect/dist/Predicate.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.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. + * + * @since 2.0.0 + */ + +/** + * Transforms the input of a predicate using a mapping function. + * + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. + * + * **Details** + * + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. + * + * **Example** (Checking string length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isLongerThan2 = Predicate.mapInput((s: string) => s.length)( + * (n: number) => n > 2 + * ) + * + * isLongerThan2("hello") // => true + * ``` + * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const mapInput = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => b => self(f(b))))); +/** + * Checks whether a readonly array has exactly `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking exact length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isPair = Predicate.isTupleOf(2) + * + * isPair([1, 2]) // => true + * ``` + * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOf = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length === n))); +/** + * Checks whether a readonly array has at least `n` elements. + * + * **When to use** + * + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. + * + * **Example** (Checking minimum length) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAtLeast2 = Predicate.isTupleOfAtLeast(2) + * + * hasAtLeast2([1, 2, 3]) // => true + * ``` + * + * @see {@link isTupleOf} + * @see {@link Tuple} + * @category guards + * @since 3.3.0 + */ +const isTupleOfAtLeast = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, n) => self.length >= n))); +/** + * Checks whether a value is truthy. + * + * **When to use** + * + * Use when you want a predicate that mirrors JavaScript truthiness and filters + * out falsy values like `0`, `""`, and `false`. + * + * **Details** + * + * This uses `!!input` and treats `0`, `""`, `false`, `null`, and `undefined` + * as false. + * + * **Example** (Filtering truthy values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, 1, "", "ok", false] + * const truthy = values.filter(Predicate.isTruthy) // => [1, "ok"] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNullish} + * @category predicates + * @since 2.0.0 + */ +function isTruthy(input) { + return !!input; +} +/** + * Checks whether a value is a `Set`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Set` values. + * + * **Details** + * + * Uses `instanceof Set`. + * + * **Example** (Guarding a Set) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Set([1, 2]) + * + * if (Predicate.isSet(data)) { + * data.size // => 2 + * } + * ``` + * + * @see {@link isMap} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isSet(input) { + return input instanceof Set; +} +/** + * Checks whether a value is a `Map`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Map` values. + * + * **Details** + * + * Uses `instanceof Map`. + * + * **Example** (Guarding a Map) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Map([["a", 1]]) + * + * if (Predicate.isMap(data)) { + * data.size // => 1 + * } + * ``` + * + * @see {@link isSet} + * @see {@link isIterable} + * @category guards + * @since 2.0.0 + */ +function isMap(input) { + return input instanceof Map; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isString(input) { + return typeof input === "string"; +} +/** + * Checks whether a value is a `number`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * number. + * + * **Details** + * + * Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`. + * + * **Example** (Guarding numbers) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 42 + * + * if (Predicate.isNumber(data)) { + * data + 1 // => 43 + * } + * ``` + * + * @see {@link isBigInt} + * @see {@link isString} + * @category guards + * @since 2.0.0 + */ +function isNumber(input) { + return typeof input === "number"; +} +/** + * Checks whether a value is a `boolean`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * boolean. + * + * **Details** + * + * Uses `typeof input === "boolean"`. + * + * **Example** (Guarding booleans) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = true + * + * if (Predicate.isBoolean(data)) { + * data ? "yes" : "no" // => "yes" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBoolean(input) { + return typeof input === "boolean"; +} +/** + * Checks whether a value is a `bigint`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * bigint. + * + * **Details** + * + * Uses `typeof input === "bigint"`. + * + * **Example** (Guarding bigints) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = 1n + * + * if (Predicate.isBigInt(data)) { + * data + 2n // => 3n + * } + * ``` + * + * @see {@link isNumber} + * @category guards + * @since 2.0.0 + */ +function isBigInt(input) { + return typeof input === "bigint"; +} +/** + * Checks whether a value is a `symbol`. + * + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * symbol. + * + * **Details** + * + * Uses `typeof input === "symbol"`. + * + * **Example** (Guarding symbols) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Symbol.for("id") + * + * if (Predicate.isSymbol(data)) { + * data.description // => "id" + * } + * ``` + * + * @see {@link isPropertyKey} + * @category guards + * @since 2.0.0 + */ +function isSymbol(input) { + return typeof input === "symbol"; +} +/** + * Checks whether a value is a valid `PropertyKey` (string, number, or symbol). + * + * **When to use** + * + * Use when you need a `Predicate` guard for unknown property keys before + * indexing. + * + * **Details** + * + * Uses `isString`, `isNumber`, and `isSymbol`. + * + * **Example** (Guarding property keys) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const key: unknown = "name" + * const obj: Record = { name: "Ada" } + * + * if (Predicate.isPropertyKey(key) && key in obj) { + * obj[key] // => "Ada" + * } + * ``` + * + * @see {@link isString} + * @see {@link isNumber} + * @see {@link isSymbol} + * @category guards + * @since 4.0.0 + */ +function isPropertyKey(u) { + return isString(u) || isNumber(u) || isSymbol(u); +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isFunction(input) { + return typeof input === "function"; +} +/** + * Checks whether a value is `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for values that are exactly + * `undefined`. + * + * **Details** + * + * Uses `input === undefined`. + * + * **Example** (Guarding undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = undefined + * + * Predicate.isUndefined(data) // => true + * ``` + * + * @see {@link isNotUndefined} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isUndefined(input) { + return input === undefined; +} +/** + * Checks whether a value is not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `undefined` + * while preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `undefined`. + * + * **Example** (Filtering undefined values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, undefined, 2] + * const defined = values.filter(Predicate.isNotUndefined) // => [1, 2] + * ``` + * + * @see {@link isUndefined} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotUndefined(input) { + return input !== undefined; +} +/** + * Checks whether a value is `null`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullable values. + * + * **Details** + * + * Uses `input === null`. + * + * **Example** (Guarding null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = null + * + * Predicate.isNull(data) // => true + * ``` + * + * @see {@link isNotNull} + * @see {@link isNullish} + * @category guards + * @since 2.0.0 + */ +function isNull(input) { + return input === null; +} +/** + * Checks whether a value is not `null`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `null` while + * preserving other falsy values. + * + * **Details** + * + * Returns a refinement that excludes `null`. + * + * **Example** (Filtering null values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [1, null, 2] + * const nonNull = values.filter(Predicate.isNotNull) // => [1, 2] + * ``` + * + * @see {@link isNull} + * @see {@link isNotNullish} + * @category guards + * @since 2.0.0 + */ +function isNotNull(input) { + return input !== null; +} +/** + * Checks whether a value is `null` or `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for nullish values. + * + * **Details** + * + * Uses `input === null || input === undefined`. + * + * **Example** (Guarding nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const nullish = values.filter(Predicate.isNullish) // => [null, undefined] + * ``` + * + * @see {@link isNotNullish} + * @see {@link isUndefined} + * @see {@link isNull} + * @category guards + * @since 4.0.0 + */ +function isNullish(input) { + return input === null || input === undefined; +} +/** + * Checks whether a value is not `null` and not `undefined`. + * + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out nullish values + * but keeps other falsy ones. + * + * **Details** + * + * Uses `input != null`. + * + * **Example** (Filtering non-nullish values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const values = [0, null, "", undefined] + * const present = values.filter(Predicate.isNotNullish) // => [0, ""] + * ``` + * + * @see {@link isNullish} + * @see {@link isNotNull} + * @see {@link isNotUndefined} + * @category guards + * @since 4.0.0 + */ +function isNotNullish(input) { + return input != null; +} +/** + * Type guard that always returns `false`. + * + * **When to use** + * + * Use when you need a `Predicate` that never accepts, e.g. in default branches. + * + * **Example** (Matching no values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isNever("anything") // => false + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isNever(_) { + return false; +} +/** + * Type guard that always returns `true`. + * + * **When to use** + * + * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. + * + * **Example** (Matching every value) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isUnknown(123) // => true + * ``` + * + * @see {@link isNever} + * @category guards + * @since 2.0.0 + */ +function isUnknown(_) { + return true; +} +/** + * Checks whether a value is an object or an array (non-null object). + * + * **When to use** + * + * Use when you need a `Predicate` guard that accepts plain objects and arrays, + * but not `null`. + * + * **Details** + * + * Uses `typeof input === "object" && input !== null` and includes arrays. + * + * **Example** (Checking objects or arrays) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObjectOrArray([]) // => true + * ``` + * + * @see {@link isObject} + * @see {@link isObjectKeyword} + * @category guards + * @since 4.0.0 + */ +function isObjectOrArray(input) { + return typeof input === "object" && input !== null; +} +/** + * Checks whether a value is a non-null object value that is not an array. + * + * **When to use** + * + * Use to narrow unknown input to a non-null, non-array object with a + * `Predicate` guard. + * + * **Details** + * + * This is a structural runtime check using `typeof input === "object"`, so it + * also accepts object instances such as `Date`, `Map`, class instances, and + * typed arrays. It excludes `null` and arrays. + * + * **Example** (Guarding objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * Predicate.isObject({ a: 1 }) // => true + * Predicate.isObject([1, 2]) // => false + * ``` + * + * @see {@link isObjectOrArray} + * @see {@link isReadonlyObject} + * @category guards + * @since 2.0.0 + */ +function isObject(input) { + return typeof input === "object" && input !== null && !Array.isArray(input); +} +/** + * Checks whether a value is a non-null, non-array object and narrows it to a + * readonly indexable object type. + * + * **When to use** + * + * Use to narrow unknown input to a readonly view of a non-null, non-array + * object with a `Predicate` guard. + * + * **Details** + * + * Readonly-ness is a TypeScript type-level view; it is not observable at + * runtime. This delegates to `isObject`, so class instances and built-in object + * instances are accepted. + * + * **Example** (Checking readonly objects) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { a: 1 } + * + * Predicate.isReadonlyObject(data) // => true + * ``` + * + * @see {@link isObject} + * @category guards + * @since 4.0.0 + */ +function isReadonlyObject(input) { + return isObject(input); +} +/** + * 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} + * @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} + * @category guards + * @since 2.0.0 + */ +const hasProperty = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, property) => isObjectKeyword(self) && property in self); +/** + * Checks whether a value has a `_tag` property equal to the given tag. + * + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. + * + * **Details** + * + * Uses `hasProperty` and strict equality on `_tag`. + * + * **Example** (Guarding tagged values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isOk = Predicate.isTagged("Ok") + * + * isOk({ _tag: "Ok", value: 1 }) // => true + * ``` + * + * @see {@link hasProperty} + * @category guards + * @since 2.0.0 + */ +const isTagged = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, tag) => hasProperty(self, "_tag") && self["_tag"] === tag); +/** + * Checks whether a value is an `Error`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for errors caught from unknown sources. + * + * **Details** + * + * Uses `instanceof Error`. + * + * **Example** (Guarding errors) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Error("boom") + * + * Predicate.isError(data) // => true + * ``` + * + * @see {@link isUnknown} + * @category guards + * @since 2.0.0 + */ +function isError(input) { + return input instanceof Error; +} +/** + * Checks whether a value is a `Uint8Array`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for binary data. + * + * **Details** + * + * Uses `instanceof Uint8Array`. + * + * **Example** (Guarding Uint8Array values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Uint8Array([1, 2]) + * + * Predicate.isUint8Array(data) // => true + * ``` + * + * @see {@link isIterable} + * @see {@link isSet} + * @category guards + * @since 2.0.0 + */ +function isUint8Array(input) { + return input instanceof Uint8Array; +} +/** + * Checks whether a value is a `Date`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for dates. + * + * **Details** + * + * Uses `instanceof Date`. + * + * **Example** (Guarding Date values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = new Date() + * + * Predicate.isDate(data) // => true + * ``` + * + * @see {@link isRegExp} + * @category guards + * @since 2.0.0 + */ +function isDate(input) { + return input instanceof Date; +} +/** + * 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} + * @category guards + * @since 2.0.0 + */ +function isIterable(input) { + return hasProperty(input, Symbol.iterator) || isString(input); +} +/** + * Checks whether a value is a `Promise`-like object with `then` and `catch`. + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise instances across realms. + * + * **Details** + * + * Performs a structural check for `then` and `catch` functions. + * + * **Example** (Guarding promises) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = Promise.resolve(1) + * + * Predicate.isPromise(data) // => true + * ``` + * + * @see {@link isPromiseLike} + * @category guards + * @since 2.0.0 + */ +function isPromise(input) { + return hasProperty(input, "then") && "catch" in input && isFunction(input.then) && isFunction(input.catch); +} +/** + * Checks whether a value is `PromiseLike` (has a `then` method). + * + * **When to use** + * + * Use when you need a `Predicate` guard for promise-like values with a + * callable `then` method. + * + * **Details** + * + * Performs a structural check for a callable `then`. + * + * **Example** (Guarding promise-like values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = { then: () => {} } + * + * Predicate.isPromiseLike(data) // => true + * ``` + * + * @see {@link isPromise} + * @category guards + * @since 2.0.0 + */ +function isPromiseLike(input) { + return hasProperty(input, "then") && isFunction(input.then); +} +/** + * Checks whether a value is a `RegExp`. + * + * **When to use** + * + * Use when you need a `Predicate` runtime guard for regular expressions. + * + * **Details** + * + * Uses `instanceof RegExp`. + * + * **Example** (Guarding RegExp values) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const data: unknown = /abc/ + * + * Predicate.isRegExp(data) // => true + * ``` + * + * @see {@link isDate} + * @category guards + * @since 3.9.0 + */ +function isRegExp(input) { + return input instanceof RegExp; +} +/** + * Composes two predicates or refinements into one. + * + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. + * + * **Example** (Composing refinements) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNumber: Predicate.Refinement = (u): u is number => typeof u === "number" + * const isInteger: Predicate.Refinement = (n): n is number => Number.isInteger(n) + * + * const isIntegerNumber = Predicate.compose(isNumber, isInteger) + * + * isIntegerNumber(1) // => true + * ``` + * + * @see {@link and} + * @see {@link Refinement} + * @category combinators + * @since 2.0.0 + */ +const compose = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (ab, bc) => a => ab(a) && bc(a)))); +/** + * Creates a predicate for tuples by applying predicates to each element. + * + * **When to use** + * + * Use when you want to validate tuple positions independently by lifting + * element predicates into a tuple predicate. + * + * **Details** + * + * Returns a refinement if any element predicate is a refinement. Evaluation + * stops at the first failing element. + * + * **Example** (Checking tuples) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const tupleCheck = Predicate.Tuple([(n: number) => n > 0, Predicate.isString]) + * + * tupleCheck([1, "ok"]) // => true + * ``` + * + * @see {@link Struct} + * @see {@link isTupleOf} + * @category combinators + * @since 4.0.0 + */ +function Tuple(elements) { + return as => { + for (let i = 0; i < elements.length; i++) { + if (elements[i](as[i]) === false) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate for objects by applying predicates to named properties. + * + * **When to use** + * + * Use when you want to validate a record shape at runtime by lifting property + * predicates into an object predicate. + * + * **Details** + * + * Returns a refinement if any field predicate is a refinement. Only the + * specified keys are checked, and extra keys are ignored. + * + * **Example** (Checking structs) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const userCheck = Predicate.Struct({ + * id: Predicate.isNumber, + * name: Predicate.isString + * }) + * + * userCheck({ id: 1, name: "Ada" }) // => true + * ``` + * + * @see {@link Tuple} + * @see {@link hasProperty} + * @category combinators + * @since 4.0.0 + */ +function Struct(fields) { + const keys = Object.keys(fields); + return a => { + for (const key of keys) { + if (!fields[key](a[key])) { + return false; + } + } + return true; + }; +} +/** + * Negates a predicate. + * + * **When to use** + * + * Use when you want the inverse of an existing predicate. + * + * **Details** + * + * Returns a new predicate that flips the boolean result. + * + * **Example** (Negating a predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isNotString = Predicate.not(Predicate.isString) + * + * isNotString(1) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +function not(self) { + return a => !self(a); +} +/** + * Creates a predicate that returns `true` if either predicate is `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. + * + * **Example** (Checking either condition) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber) + * + * isStringOrNumber("a") // => true + * ``` + * + * @see {@link and} + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const or = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) || that(a)))); +/** + * Creates a predicate that returns `true` only if both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. + * + * **Example** (Checking both conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const hasAAndB = Predicate.and( + * Predicate.hasProperty("a"), + * Predicate.hasProperty("b") + * ) + * + * const input: unknown = JSON.parse(`{"a":1,"b":"ok"}`) + * if (hasAAndB(input)) { + * // input has both properties at this point + * const a = input.a + * const b = input.b + * + * const values = [a, b] // => [1, "ok"] + * } + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const and = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) && that(a)))); +/** + * Creates a predicate that returns `true` if exactly one predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with exclusive-or semantics. + * + * **Details** + * + * Returns `true` when results differ. + * + * **Example** (Checking exclusive-or conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const isPositive = (n: number) => n > 0 + * const either = Predicate.xor(isEven, isPositive) + * + * either(-2) // => true + * ``` + * + * @see {@link or} + * @see {@link and} + * @category combinators + * @since 2.0.0 + */ +const xor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) !== that(a)))); +/** + * Creates a predicate that returns `true` when both predicates agree. + * + * **When to use** + * + * Use when you want to check equivalence of two `Predicate`s. + * + * **Details** + * + * Returns `true` when both results are equal. + * + * **Example** (Defining equivalence) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isEven = (n: number) => n % 2 === 0 + * const same = Predicate.eqv(isEven, isEven) + * + * same(3) // => true + * ``` + * + * @see {@link xor} + * @category combinators + * @since 2.0.0 + */ +const eqv = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => self(a) === that(a)))); +/** + * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. + * + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. + * + * **Details** + * + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. + * + * **Example** (Checking implication) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const isAdult = (age: number) => age >= 18 + * const canVote = (age: number) => age >= 18 + * const implies = Predicate.implies(isAdult, canVote) + * + * implies(16) // => true + * ``` + * + * @see {@link and} + * @see {@link or} + * @category combinators + * @since 2.0.0 + */ +const implies = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (antecedent, consequent) => a => antecedent(a) ? consequent(a) : true))); +/** + * Creates a predicate that returns `true` when neither predicate is `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NOR semantics. + * + * **Details** + * + * Returns the negation of `or`. + * + * **Example** (Checking NOR conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const neither = Predicate.nor(Predicate.isString, Predicate.isNumber) + * + * neither(true) // => true + * ``` + * + * @see {@link or} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nor = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) || that(a))))); +/** + * Creates a predicate that returns `true` unless both predicates are `true`. + * + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NAND semantics. + * + * **Details** + * + * Returns the negation of `and`. + * + * **Example** (Checking NAND conditions) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const notBoth = Predicate.nand(Predicate.isString, Predicate.isNumber) + * + * notBoth("a") // => true + * ``` + * + * @see {@link and} + * @see {@link not} + * @category combinators + * @since 2.0.0 + */ +const nand = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => a => !(self(a) && that(a))))); +/** + * Creates a predicate that returns `true` if all predicates in the collection return `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates to apply. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking all predicates) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const allChecks = Predicate.every([Predicate.isNumber, (n: number) => n > 0]) + * + * allChecks(2) // => true + * ``` + * + * @see {@link some} + * @see {@link and} + * @category combining + * @since 2.0.0 + */ +function every(collection) { + return a => { + for (const p of collection) { + if (!p(a)) { + return false; + } + } + return true; + }; +} +/** + * Creates a predicate that returns `true` if any predicate in the collection returns `true`. + * + * **When to use** + * + * Use when you have a dynamic list of predicates and only need one to pass. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. The collection is iterated + * each time the predicate is called. + * + * **Example** (Checking any predicate) + * + * ```ts import.meta.vitest + * import { Predicate } from "effect" + * + * const anyCheck = Predicate.some([Predicate.isString, Predicate.isNumber]) + * + * anyCheck("ok") // => true + * ``` + * + * @see {@link every} + * @see {@link or} + * @category combining + * @since 2.0.0 + */ +function some(collection) { + return a => { + for (const p of collection) { + if (p(a)) { + return true; + } + } + return false; + }; +} +//# sourceMappingURL=Predicate.js.map +__webpack_require__.d(__webpack_exports__, { + $P: () => (isDate), + Bm: () => (isSymbol), + Et: () => (isNumber), + Kg: () => (isString), + Lm: () => (isBoolean), + Tn: () => (isFunction), + sI: () => (isBigInt), + xZ: () => (isIterable) +}, { + $J: isTagged, + i5: hasProperty +}); + + +}, +"./node_modules/effect/dist/Pull.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_effect_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/** + * Models one low-level pull step for stream-like consumers. + * + * A `Pull` is an `Effect` that can produce one `A`, fail with an + * ordinary error `E`, or signal end-of-input with `Cause.Done`. The + * separate done signal lets low-level consumers distinguish normal completion + * from failure. This module includes type extractors and helpers for detecting, + * filtering, catching, converting, and matching done signals separately from + * ordinary failures. + * + * @since 4.0.0 + */ + + + + + + +// ----------------------------------------------------------------------------- +// Done +// ----------------------------------------------------------------------------- +/** + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * + * @category error handling + * @since 4.0.0 + */ +const catchDone = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (effect, f) => _internal_effect_js__rspack_import_1/* .catchCauseFilter */.rNk(effect, filterDoneLeftover, l => f(l))); +/** + * Checks whether a Cause contains any done errors. + * + * **When to use** + * + * Use when you need to test whether a pull failure cause represents normal + * completion and only need a boolean result. + * + * @see {@link isDoneFailure} for checking a single `Cause.Reason` + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * @see {@link filterNoDone} for selecting causes with no done failures + * + * @category predicates + * @since 4.0.0 + */ +const isDoneCause = cause => cause.reasons.some(isDoneFailure); +/** + * Checks whether a `Cause.Reason` is a `Fail` reason whose error is a + * `Cause.Done` signal. + * + * **When to use** + * + * Use when you need to identify done completion reasons while traversing + * `cause.reasons`, before handling ordinary failures. + * + * @see {@link isDoneCause} for checking an entire `Cause` for any done reason + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * + * @category guards + * @since 4.0.0 + */ +const isDoneFailure = failure => failure._tag === "Fail" && _Cause_js__rspack_import_2/* .isDone */.$L(failure.error); +/** + * Finds a `Cause.Done` failure in a `Cause`. + * + * **When to use** + * + * Use to separate `Cause.Done` completion from ordinary causes while preserving + * the typed done value. + * + * **Details** + * + * Returns a successful `Result` with the `Cause.Done` value when the cause + * contains a done signal and no other failures besides interruptions. When the + * done signal was merged with a real failure (for example a failing + * finalizer), the `Result` fails with the remaining cause, stripped of the + * done signal. Without a done signal the `Result` fails with the original + * cause. + * + * @category filtering + * @since 4.0.0 + */ +const filterDone = cause => { + let done; + let hasFailure = false; + for (const reason of cause.reasons) { + if (isDoneFailure(reason)) { + done ??= reason.error; + } else if (reason._tag !== "Interrupt") { + hasFailure = true; + } + } + if (done === undefined) return _Result_js__rspack_import_3/* .fail */.fJ(cause); + return hasFailure ? _Result_js__rspack_import_3/* .fail */.fJ(_Cause_js__rspack_import_2/* .fromReasons */.kO(cause.reasons.filter(reason => !isDoneFailure(reason)))) : _Result_js__rspack_import_3/* .succeed */.Py(done); +}; +/** + * Finds a `Cause.Done` failure in a cause whose done value is not used. + * + * **When to use** + * + * Use to detect `Cause.Done` completion in a `Cause` when the completion value + * is not part of the downstream logic. + * + * **Details** + * + * Returns a successful `Result` with the done marker when it is the only + * failure, otherwise returns a failed `Result` with the non-done cause. + * + * @see {@link filterDone} for preserving the typed `Cause.Done` value when the done payload matters + * @see {@link filterDoneLeftover} for extracting only the done leftover value + * @see {@link filterNoDone} for the inverse filter that succeeds only when no done failure is present + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneVoid = (/* unused pure expression or super */ null && (filterDone)); +/** + * Keeps a `Cause` only when it contains no `Cause.Done` failures. + * + * **When to use** + * + * Use to select ordinary failure causes for handling while leaving `Cause.Done` + * completion causes outside that handler. + * + * **Details** + * + * Returns a successful `Result` with the cause when every failure is non-done; + * otherwise returns a failed `Result` with the original cause. + * + * @see {@link filterDone} for the inverse typed done filter + * @see {@link filterDoneVoid} for done detection when the payload is not needed + * + * @category filtering + * @since 4.0.0 + */ +const filterNoDone = /*#__PURE__*/(/* unused pure expression or super */ null && (Filter.fromPredicate(cause => cause.reasons.every(failure => !isDoneFailure(failure))))); +/** + * Filters a Cause to extract the leftover value from done errors. + * + * **When to use** + * + * Use to extract only the leftover value carried by a `Cause.Done` completion + * signal. + * + * @category filtering + * @since 4.0.0 + */ +const filterDoneLeftover = cause => { + const done = filterDone(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(done) ? done : _Result_js__rspack_import_3/* .succeed */.Py(done.success.value); +}; +/** + * Converts a `Cause` into an `Exit`, treating `Cause.Done` as successful + * completion. + * + * **When to use** + * + * Use to produce an `Exit` for finalizing a low-level pull workflow when a + * `Cause.Done` signal should be treated as success and any remaining cause + * should fail. + * + * **Details** + * + * If the done signal is the only failure in the cause, its leftover becomes + * the successful value. Otherwise the non-done cause becomes the failure + * cause. + * + * @see {@link filterDone} for extracting the done signal without converting the cause to an `Exit` + * @see {@link matchEffect} for handling `Pull` success, failure, and done outcomes directly + * + * @category converting + * @since 4.0.0 + */ +const doneExitFromCause = cause => { + const halt = filterDone(cause); + return !Result.isFailure(halt) ? Exit.succeed(halt.success.value) : Exit.failCause(halt.failure); +}; +/** + * Pattern matches on a Pull, handling success, failure, and done cases. + * + * **When to use** + * + * Use to handle all three `Pull` outcomes with effectful handlers. + * + * **Example** (Matching Pull outcomes) + * + * ```ts import.meta.vitest + * import { Cause, Effect, Pull } from "effect" + * + * const pull = Cause.done("stream ended") + * + * const result = Pull.matchEffect(pull, { + * onSuccess: (value) => Effect.succeed(`Got value: ${value}`), + * onFailure: (cause) => Effect.succeed(`Got error: ${cause}`), + * onDone: (leftover) => Effect.succeed(`Stream halted with: ${leftover}`) + * }) + * + * await Effect.runPromise(result) // => "Stream halted with: stream ended" + * ``` + * + * @category pattern matching + * @since 4.0.0 + */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, options) => _internal_effect_js__rspack_import_1/* .matchCauseEffect */.khu(self, { + onSuccess: options.onSuccess, + onFailure: cause => { + const halt = filterDone(cause); + return !_Result_js__rspack_import_3/* .isFailure */.N6(halt) ? options.onDone(halt.success.value) : options.onFailure(halt.failure); + } +})); +//# sourceMappingURL=Pull.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + m8: catchDone, + tv: matchEffect +}); + + +}, +"./node_modules/effect/dist/Record.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_record_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/** + * Works with plain JavaScript records as immutable key/value dictionaries. + * + * A record is an object whose keys are strings or symbols. This module includes + * helpers for construction, lookup, updates, mapping, filtering, folding, + * set-like combination, and typed conversions between records and iterable + * entries. Helpers that change values return new records instead of mutating the + * input. + * + * @since 2.0.0 + */ + + + + + + +/** + * Creates a new, empty record. + * + * **Example** (Creating an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * // Create an empty record + * const emptyRecord = Record.empty() + * emptyRecord // => {} + * + * // The type ensures type safety for future operations + * Record.set(emptyRecord, "count", 42) // => { count: 42 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const empty = () => ({}); +/** + * Determines if a mutable record is empty. + * + * **Example** (Checking for an empty record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyRecord({}) // => true + * Record.isEmptyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyRecord = self => Object.keys(self).length === 0; +/** + * Determines if a readonly record is empty. + * + * **Example** (Checking for an empty readonly record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isEmptyReadonlyRecord({}) // => true + * Record.isEmptyReadonlyRecord({ a: 3 }) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isEmptyReadonlyRecord = (/* unused pure expression or super */ null && (isEmptyRecord)); +/** + * Takes an iterable and a projection function and returns a record. + * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. + * + * **Example** (Building a record from mapped iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromIterableWith([1, 2, 3, 4], (a) => [String(a), a * 2]) // => { "1": 2, "2": 4, "3": 6, "4": 8 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const a of self) { + const [k, b] = f(a); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Creates a new record from an iterable, utilizing the provided function to determine the key for each element. + * + * **Example** (Building a record keyed by iterable values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const users = [ + * { id: "2", name: "name2" }, + * { id: "1", name: "name1" } + * ] + * + * Record.fromIterableBy( + * users, + * (user) => user.id + * ) // => { "1": { id: "1", name: "name1" }, "2": { id: "2", name: "name2" } } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromIterableBy = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (items, f) => fromIterableWith(items, a => [f(a), a])))); +/** + * Builds a record from an iterable of key-value pairs. + * + * **Details** + * + * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the + * previous ones. So the resulting record will only have the value of the last occurrence of each key. + * + * **Example** (Building a record from entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.fromEntries([["a", 1], ["b", 2]]) // => { a: 1, b: 2 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fromEntries = Object.fromEntries; +/** + * Transforms the values of a record into an `Array` with a custom mapping function. + * + * **Example** (Collecting mapped record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.collect(x, (key, n) => [key, n]) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const collect = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, f) => { + const out = []; + for (const key of keys(self)) { + out.push(f(key, self[key])); + } + return out; +}); +/** + * Takes a record and returns an array of tuples containing its keys and values. + * + * **Example** (Converting a record to entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * Record.toEntries(x) // => [["a", 1], ["b", 2], ["c", 3]] + * ``` + * + * @category converting + * @since 2.0.0 + */ +const toEntries = /*#__PURE__*/collect((key, value) => [key, value]); +/** + * Returns the number of key/value pairs in a record. + * + * **Example** (Getting the record size) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.size({ a: "a", b: 1, c: true }) // => 3 + * ``` + * + * @category getters + * @since 2.0.0 + */ +const size = self => keys(self).length; +/** + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.has({ a: 1, b: 2 }, "a") // => true + * Record.has(Record.empty(), "c") // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const has = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key)))); +/** + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) + * + * ```ts import.meta.vitest + * import { Option, Record as R } from "effect" + * + * const person: Record = { name: "John Doe", age: 35 } + * + * R.get(person, "name") // => Option.some("John Doe") + * R.get(person, "email") // => Option.none() + * ``` + * + * @category getters + * @since 2.0.0 + */ +const get = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => Object.hasOwn(self, key) ? Option.some(self[key]) : Option.none()))); +/** + * Applies a function to the element at the specified key safely, creating a new record, + * or return `Option.none()` if the key doesn't exist. + * + * **Example** (Modifying a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const f = (x: number) => x * 2 + * + * const input: Record = { a: 3 } + * + * Record.modify(input, "a", f) // => Option.some({ a: 6 }) + * Record.modify(input, "b", f) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const modify = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, f) => { + if (!has(self, key)) return Option.none(); + return Option.some({ + ...self, + [key]: f(self[key]) + }); +}))); +/** + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.replace({ a: 1, b: 2, c: 3 }, "a", 10) // => Option.some({ a: 10, b: 2, c: 3 }) + * Record.replace(Record.empty(), "a", 10) // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const replace = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, b) => modify(self, key, () => b)))); +/** + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.remove({ a: 1, b: 2 }, "a") // => { b: 2 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const remove = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => { + if (!has(self, key)) { + return { + ...self + }; + } + const out = { + ...self + }; + delete out[key]; + return out; +}))); +/** + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` + * of a tuple with the value and the record with the removed property. + * If the key is not present, returns `Option.none()`. + * + * **Example** (Popping a value and removing its key) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const input: Record = { a: 1, b: 2 } + * + * Record.pop(input, "a") // => Option.some([1, { b: 2 }]) + * Record.pop(input, "c") // => Option.none() + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const pop = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, key) => has(self, key) ? Option.some([self[key], remove(self, key)]) : Option.none()))); +/** + * Maps a record into another record by applying a transformation function to each of its values. + * + * **Example** (Mapping record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const f = (n: number) => `-${n}` + * + * Record.map({ a: 3, b: 5 }, f) // => { a: "-3", b: "-5" } + * + * const g = (n: number, key: string) => `${key.toUpperCase()}-${n}` + * + * Record.map({ a: 3, b: 5 }, g) // => { a: "A-3", b: "B-5" } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = { + ...self + }; + for (const key of keys(self)) { + InternalRecord.assignProperty(out, key, f(self[key], key)); + } + return out; +}))); +/** + * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. + * + * **Example** (Mapping record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()) // => { A: 3, B: 5 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapKeys = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const a = self[key]; + InternalRecord.assignProperty(out, f(key, a), a); + } + return out; +}))); +/** + * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. + * + * **Example** (Mapping record entries) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]) // => { A: 4, B: 6 } + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const mapEntries = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = {}; + for (const key of keys(self)) { + const [k, b] = f(self[key], key); + InternalRecord.assignProperty(out, k, b); + } + return out; +}))); +/** + * Transforms a record by applying the function `f` to each key and value in the original record. + * If the function succeeds, the key-value pair is included in the output record. + * + * **Example** (Filtering and mapping with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (a: number, key: string) => a > 2 ? Result.succeed(a * 2) : Result.failVoid + * Record.filterMap(x, f) // => { c: 6 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filterMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const out = empty(); + for (const key of keys(self)) { + const result = f(self[key], key); + if (R.isSuccess(result)) { + InternalRecord.assignProperty(out, key, result.success); + } + } + return out; +}))); +/** + * Selects properties from a record whose values match the given predicate. + * + * **Example** (Filtering record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const x = { a: 1, b: 2, c: 3, d: 4 } + * Record.filter(x, (n) => n > 2) // => { c: 3, d: 4 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const filter = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + const out = empty(); + for (const key of keys(self)) { + if (predicate(self[key], key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + return out; +}))); +/** + * Returns a new record containing only the `Some` values from a record of + * `Option` values, preserving the original keys. + * + * **Example** (Extracting Some values) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const getSomes = self => { + const out = empty(); + for (const key of keys(self)) { + const option = self[key]; + if (Option.isSome(option)) { + InternalRecord.assignProperty(out, key, option.value); + } + } + return out; +}; +/** + * Returns a new record containing only the `Err` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result failures) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getFailures({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { b: "err" } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getFailures = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isFailure(value)) { + InternalRecord.assignProperty(out, key, value.failure); + } + } + return out; +}; +/** + * Returns a new record containing only the `Ok` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result successes) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.getSuccesses({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }) // => { a: 1, c: 2 } + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const getSuccesses = self => { + const out = empty(); + for (const key of keys(self)) { + const value = self[key]; + if (R.isSuccess(value)) { + InternalRecord.assignProperty(out, key, value.success); + } + } + return out; +}; +/** + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * const x = { a: 1, b: 2, c: 3 } + * const f = (n: number) => (n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) + * Record.partition(x, f) // => [{ a: 1, c: 3 }, { b: 2 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const partition = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const left = empty(); + const right = empty(); + for (const key of keys(self)) { + const e = f(self[key], key); + if (R.isFailure(e)) { + InternalRecord.assignProperty(left, key, e.failure); + } else { + InternalRecord.assignProperty(right, key, e.success); + } + } + return [left, right]; +}))); +/** + * Partitions a record of `Result` values into two separate records, + * one with the `Err` values and one with the `Ok` values. + * + * **Example** (Separating Result values) + * + * ```ts import.meta.vitest + * import { Record, Result } from "effect" + * + * Record.separate({ a: Result.fail("e"), b: Result.succeed(1) }) // => [{ a: "e" }, { b: 1 }] + * ``` + * + * @category filtering + * @since 2.0.0 + */ +const separate = /*#__PURE__*/(/* unused pure expression or super */ null && (partition(identity))); +/** + * Retrieves the keys of a given record as an array. + * + * **Example** (Getting record keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.keys({ a: 1, b: 2, c: 3 }) // => ["a", "b", "c"] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const keys = self => Object.keys(self); +/** + * Retrieves the values of a given record as an array. + * + * **Example** (Getting record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.values({ a: 1, b: 2, c: 3 }) // => [1, 2, 3] + * ``` + * + * @category getters + * @since 2.0.0 + */ +const values = self => collect(self, (_, a) => a); +/** + * Adds a new key-value pair or update an existing key's value in a record. + * + * **Example** (Setting a record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.set("a", 5)({ a: 1, b: 2 }) // => { a: 5, b: 2 } + * Record.set("c", 5)({ a: 1, b: 2 }) // => { a: 1, b: 2, c: 5 } + * ``` + * + * @category mutations + * @since 2.0.0 + */ +const set = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, key, value) => { + return { + ...self, + [key]: value + }; +}))); +/** + * Mutates a record by assigning a value to a property. + * + * **When to use** + * + * Use when incrementally constructing a new record and copying it for every + * property would be unnecessary. + * + * **Gotchas** + * + * This function mutates `self`. When `key` is `"__proto__"`, it creates an + * own data property instead of changing the object's prototype. + * + * **Example** (Assigning an external key safely) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * const key: string = "__proto__" // Assume this comes from external input + * const value = { polluted: true } + * + * const unsafe: Record = {} + * unsafe[key] = value + * Object.getPrototypeOf(unsafe) === value // => true + * + * const safe: Record = {} + * Record.assignProperty(safe, key, value) + * Object.getPrototypeOf(safe) === Object.prototype // => true + * safe[key] === value // => true + * ``` + * + * @see {@link set} for an immutable update + * @category mutations + * @since 4.0.0 + */ +const assignProperty = _internal_record_js__rspack_import_1/* .assignProperty */.x; +/** + * Checks whether all the keys and values in one record are also found in another record. + * Uses the provided equivalence function to compare values. + * + * **Example** (Checking subrecords with a custom equivalence) + * + * ```ts import.meta.vitest + * import { Equivalence, Record } from "effect" + * + * const isSubrecord = Record.isSubrecordBy( + * Equivalence.make((self, that) => self.toLowerCase() === that.toLowerCase()) + * ) + * + * const required: Record.ReadonlyRecord = { role: "Admin" } + * const available: Record.ReadonlyRecord = { + * role: "admin", + * status: "active" + * } + * + * isSubrecord(required, available) // => true + * isSubrecord({ role: "Admin", status: "inactive" }, available) // => false + * isSubrecord(required, { role: "editor", status: "active" }) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecordBy = equivalence => dual(2, (self, that) => { + for (const key of keys(self)) { + if (!has(that, key) || !equivalence(self[key], that[key])) { + return false; + } + } + return true; +}); +/** + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.isSubrecord({ a: 1 } as Record, { a: 1, b: 2 }) // => true + * Record.isSubrecord({ a: 1, b: 2 }, { a: 1 } as Record) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const isSubrecord = /*#__PURE__*/(/* unused pure expression or super */ null && (isSubrecordBy(/*#__PURE__*/Equal.asEquivalence()))); +/** + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.reduce({ a: 1, b: 2, c: 3 }, 0, (acc, value) => acc + value) // => 6 + * ``` + * + * @category folding + * @since 2.0.0 + */ +const reduce = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, zero, f) => { + let out = zero; + for (const key of keys(self)) { + out = f(out, self[key], key); + } + return out; +}))); +/** + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.every({ a: 1, b: 2 }, (n) => n > 0) // => true + * Record.every({ a: 1, b: -1 }, (n) => n > 0) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const every = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, refinement) => { + for (const key of keys(self)) { + if (!refinement(self[key], key)) { + return false; + } + } + return true; +}))); +/** + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.some({ a: 1, b: 2 }, (n) => n > 1) // => true + * Record.some({ a: 1, b: 2 }, (n) => n > 2) // => false + * ``` + * + * @category predicates + * @since 2.0.0 + */ +const some = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, predicate) => { + for (const key of keys(self)) { + if (predicate(self[key], key)) { + return true; + } + } + return false; +}))); +/** + * Merges two records, preserving entries that exist in either of the records. + * For keys that exist in both records, the provided combine function is used to merge the values. + * + * **Example** (Merging records with union) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.union({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { a: 1, b: 5, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const union = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = empty(); + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } else { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(out, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Merges two records, retaining only the entries that exist in both records. + * For intersecting keys, the provided combine function is used to merge the values. + * + * **Example** (Merging intersecting keys) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.intersection({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b) // => { b: 5 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const intersection = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, that, combine) => { + const out = empty(); + if (isEmptyRecord(self) || isEmptyRecord(that)) { + return out; + } + for (const key of keys(self)) { + if (has(that, key)) { + InternalRecord.assignProperty(out, key, combine(self[key], that[key])); + } + } + return out; +}))); +/** + * Merges two records, preserving only the entries that are unique to each record. + * Keys that exist in both records are excluded from the result. + * + * **Example** (Keeping keys unique to each record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.difference({ a: 1, b: 2 }, { b: 3, c: 4 }) // => { a: 1, c: 4 } + * ``` + * + * @category combining + * @since 2.0.0 + */ +const difference = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => { + if (isEmptyRecord(self)) { + return { + ...that + }; + } + if (isEmptyRecord(that)) { + return { + ...self + }; + } + const out = {}; + for (const key of keys(self)) { + if (!has(that, key)) { + InternalRecord.assignProperty(out, key, self[key]); + } + } + for (const key of keys(that)) { + if (!has(self, key)) { + InternalRecord.assignProperty(out, key, that[key]); + } + } + return out; +}))); +/** + * Create an `Equivalence` for records using the provided `Equivalence` for values. + * Two records are considered equivalent if they have the same keys and their corresponding values are equivalent. + * + * **Example** (Comparing records with a value equivalence) + * + * ```ts import.meta.vitest + * import { Equal, Record } from "effect" + * + * const recordEquivalence = Record.makeEquivalence(Equal.asEquivalence()) + * + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 2 }) // => true + * recordEquivalence({ a: 1, b: 2 }, { a: 1, b: 3 }) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = equivalence => { + const is = isSubrecordBy(equivalence); + return (self, that) => is(self, that) && is(that, self); +}; +/** + * Create a non-empty record from a single element. + * + * **Example** (Creating a singleton record) + * + * ```ts import.meta.vitest + * import { Record } from "effect" + * + * Record.singleton("a", 1) // => { a: 1 } + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const singleton = (key, value) => ({ + [key]: value +}); +/** + * Creates a `Reducer` for combining `Record`s using union, with values for keys that exist in both records combined + * using the provided `Combiner`. + * + * **When to use** + * + * Use to build a reusable reducer for accumulating many records into one + * union-shaped record, preserving keys from every input and combining + * overlapping values with the supplied combiner. + * + * **Details** + * + * The returned reducer uses `Record.union` for combine and an empty record as + * `initialValue`, so the default `combineAll` folds from `{}` and accumulates + * keys from each input record. + * + * @see {@link union} for one-off record merging with the same union semantics + * @see {@link makeReducerIntersection} for a reducer that keeps only keys present on both sides + * + * @category combining + * @since 4.0.0 + */ +function makeReducerUnion(combiner) { + return Reducer.make((self, that) => union(self, that, combiner.combine), {}); +} +/** + * Creates a `Reducer` whose `combine` operation intersects two records and + * combines values for keys present in both records. + * + * **When to use** + * + * Use to build a `Reducer` that combines records by retaining only keys shared + * by both inputs and combining matching values with a `Combiner`. + * + * **Gotchas** + * + * The reducer's `initialValue` is an empty record. Because intersection with + * an empty record is empty, the default `combineAll` folds from `{}` and + * therefore produces `{}` for ordinary non-empty inputs. + * + * @see {@link makeReducerUnion} for a reducer that preserves keys from either input record + * @see {@link intersection} for applying the shared-key merge to one pair of records + * + * @category combining + * @since 4.0.0 + */ +function makeReducerIntersection(combiner) { + return Reducer.make((self, that) => intersection(self, that, combiner.combine), {}); +} +/** + * Returns the first entry that satisfies the specified + * predicate, or `None` if no such entry exists. + * + * **Example** (Finding the first matching entry) + * + * ```ts import.meta.vitest + * import { Option, Record } from "effect" + * + * const record = { a: 1, b: 2, c: 3 } + * Record.findFirst( + * record, + * (value, key) => value > 1 && key !== "b" + * ) // => Option.some(["c", 3]) + * ``` + * + * @category searching + * @since 3.14.0 + */ +const findFirst = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + const k = keys(self); + for (let i = 0; i < k.length; i++) { + const key = k[i]; + if (f(self[key], key)) { + return Option.some([key, self[key]]); + } + } + return Option.none(); +}))); +//# sourceMappingURL=Record.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Wo: toEntries +}); + + +}, +"./node_modules/effect/dist/Redactable.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Predicate.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 + * @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 + * @category guards + * @since 3.10.0 + */ +const isRedactable = u => (0,_Predicate_js__rspack_import_0/* .hasProperty */.i5)(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 + * @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 + * @category destructors + * @since 4.0.0 + */ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context ?? emptyContext); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/new Map(); +const emptyContext = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } +}; +//# sourceMappingURL=Redactable.js.map +__webpack_require__.d(__webpack_exports__, { + E$: () => (redact), + f6: () => (getRedacted) +}, { + fL: currentFiberTypeId, + uC: symbolRedactable +}); + + +}, +"./node_modules/effect/dist/Reducer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Reusable strategies for reducing many values into one value. A `Reducer` + * extends `Combiner.Combiner` with an `initialValue` for empty collections and + * a `combineAll` method for folding an entire iterable. This module provides a + * constructor for reducers and a helper for reversing the order in which values + * are combined. + * + * @since 4.0.0 + */ +/** + * Creates a `Reducer` from a `combine` function and an `initialValue`. + * + * **When to use** + * + * Use when you have a custom reducing operation not covered by a pre-built reducer. + * - You want to provide an optimized `combineAll` (e.g. short-circuiting on + * a known absorbing element like `0` for multiplication). + * + * **Details** + * + * - If `combineAll` is omitted, a default left-to-right fold starting from + * `initialValue` is used. + * - If `combineAll` is provided, it completely replaces the default fold. + * + * **Example** (Multiplying with short-circuit) + * + * ```ts import.meta.vitest + * import { Reducer } from "effect" + * + * const Product = Reducer.make( + * (a, b) => a * b, + * 1, + * (collection) => { + * let acc = 1 + * for (const n of collection) { + * if (n === 0) return 0 + * acc *= n + * } + * return acc + * } + * ) + * + * Product.combineAll([2, 3, 4]) // => 24 + * Product.combineAll([2, 0, 4]) // => 0 + * ``` + * + * @see {@link Reducer} – the interface this creates + * @see {@link flip} – reverse the argument order + * + * @category constructors + * @since 4.0.0 + */ +function make(combine, initialValue, combineAll) { + return { + combine, + initialValue, + combineAll: combineAll ?? (collection => { + let out = initialValue; + for (const value of collection) { + out = combine(out, value); + } + return out; + }) + }; +} +/** + * Reverses the argument order of a reducer's `combine` method. + * + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative reducer such as string concatenation. + * + * **Details** + * + * - Returns a new `Reducer` where `combine(self, that)` calls the original + * reducer as `combine(that, self)`. + * - The `initialValue` is preserved from the original reducer. + * - The `combineAll` is re-derived from the flipped `combine` (using the + * default left-to-right fold), not carried over from the original. + * + * **Example** (Reversing string concatenation) + * + * ```ts import.meta.vitest + * import { Reducer, String } from "effect" + * + * const Prepend = Reducer.flip(String.ReducerConcat) + * + * Prepend.combine("a", "b") // => "ba" + * Prepend.combineAll(["a", "b", "c"]) // => "cba" + * ``` + * + * @see {@link make} + * @see {@link Combiner.flip} – the same operation on a plain `Combiner` + * + * @category combinators + * @since 4.0.0 + */ +function flip(reducer) { + return make((self, that) => reducer.combine(that, self), reducer.initialValue); +} +//# sourceMappingURL=Reducer.js.map +__webpack_require__.d(__webpack_exports__, { + L: () => (make) +}); + + +}, +"./node_modules/effect/dist/Request.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _internal_core_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); + + + + + + +const TypeId = "~effect/Request"; +const requestVariance = /*#__PURE__*/_Equal_js__rspack_import_0/* .byReferenceUnsafe */.Xq({ + /* c8 ignore next */ + _E: _ => _, + /* c8 ignore next */ + _A: _ => _, + /* c8 ignore next */ + _R: _ => _ +}); +/** + * Prototype used by Effect's request constructors. + * + * **Details** + * + * This low-level value provides the structural request marker for values + * created by `Request.of`, `Request.tagged`, `Request.Class`, and + * `Request.TaggedClass`. Most users should use those constructors instead of + * interacting with the prototype directly. + * + * @category prototypes + * @since 4.0.0 + */ +const RequestPrototype = { + ..._internal_core_js__rspack_import_1/* .StructuralProto */.In, + [TypeId]: requestVariance +}; +/** + * Checks whether a value is a `Request`. + * + * **Example** (Checking request values) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * const GetUser = Request.tagged("GetUser") + * + * const request = GetUser({ id: "123" }) + * Request.isRequest(request) // => true + * Request.isRequest("not a request") // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isRequest = u => hasProperty(u, TypeId); +/** + * Creates a constructor function for a specific Request type. + * + * **Example** (Creating untagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const UserProfile: unique symbol + * declare const ProfileError: unique symbol + * type UserProfile = typeof UserProfile + * type ProfileError = typeof ProfileError + * + * interface GetUserProfile extends Request.Request { + * readonly id: string + * readonly includeSettings: boolean + * } + * + * const GetUserProfile = Request.of() + * + * const request = GetUserProfile({ + * id: "user-123", + * includeSettings: true + * }) + * + * request.id // => "user-123" + * request.includeSettings // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const of = () => args => Object.setPrototypeOf({ + ...args +}, RequestPrototype); +/** + * Creates a constructor function for a tagged Request type. The tag is automatically + * added to the request, making it useful for discriminated unions. + * + * **Example** (Creating tagged request constructors) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * declare const User: unique symbol + * declare const UserNotFound: unique symbol + * declare const Post: unique symbol + * declare const PostNotFound: unique symbol + * type User = typeof User + * type UserNotFound = typeof UserNotFound + * type Post = typeof Post + * type PostNotFound = typeof PostNotFound + * + * interface GetUser extends Request.Request { + * readonly _tag: "GetUser" + * readonly id: string + * } + * + * interface GetPost extends Request.Request { + * readonly _tag: "GetPost" + * readonly id: string + * } + * + * const GetUser = Request.tagged("GetUser") + * const GetPost = Request.tagged("GetPost") + * + * const userRequest = GetUser({ id: "user-123" }) + * const postRequest = GetPost({ id: "post-456" }) + * + * // _tag is automatically set + * Array.of(userRequest._tag, postRequest._tag) // => ["GetUser", "GetPost"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const tagged = tag => args => { + return Object.setPrototypeOf({ + ...args, + _tag: tag + }, RequestPrototype); +}; +/** + * Defines request types with TypeScript classes. + * + * **Details** + * + * Subclasses pass their data fields to `super`, and instances are marked as + * `Request` values while retaining the provided readonly fields. + * + * **Example** (Defining request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUser extends Request.Class<{ id: number }, string, Error> { + * constructor(readonly id: number) { + * super({ id }) + * } + * } + * + * const getUserRequest = new GetUser(123) + * getUserRequest.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const Class = /*#__PURE__*/(/* unused pure expression or super */ null && (function () { + function Class(args) { + if (args) { + InternalRecord.assignProperties(this, args); + } + } + Class.prototype = RequestPrototype; + return Class; +}())); +/** + * Creates a class constructor for requests with a fixed `_tag` field. + * + * **Details** + * + * Use this when defining class-based request types that should participate in + * tagged unions or tag-based request resolvers. + * + * **Example** (Defining tagged request classes) + * + * ```ts import.meta.vitest + * import { Request } from "effect" + * + * class GetUserById + * extends Request.TaggedClass("GetUserById")<{ id: number }, string, Error> + * {} + * + * const request = new GetUserById({ id: 123 }) + * + * request._tag // => "GetUserById" + * request.id // => 123 + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const TaggedClass = tag => { + return class TaggedClass extends Class { + _tag = tag; + }; +}; +/** + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const complete = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, result) => internalEffect.sync(() => self.completeUnsafe(result))))); +/** + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const completeEffect = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, effect) => internalEffect.matchEffect(effect, { + onFailure: error => complete(self, core.exitFail(error)), + onSuccess: value => complete(self, core.exitSucceed(value)) +})))); +/** + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const fail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, error) => complete(self, core.exitFail(error))))); +/** + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * + * @category completion + * @since 2.0.0 + */ +const failCause = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, cause) => complete(self, core.exitFailCause(cause))))); +/** + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * + * @category completion + * @since 2.0.0 + */ +const succeed = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, value) => complete(self, core.exitSucceed(value))))); +/** + * Creates a `Request.Entry` from its component fields. + * + * **Details** + * + * This is a low-level helper for request runtime and resolver infrastructure; + * most application code receives entries from a `RequestResolver` instead of + * constructing them directly. + * + * @category constructors + * @since 2.0.0 + */ +const makeEntry = options => options; +//# sourceMappingURL=Request.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + lq: makeEntry +}); + + +}, +"./node_modules/effect/dist/Result.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/internal/option.js"); +/* import */ var _internal_result_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/result.js"); +/** + * Models a value that has already succeeded or failed. + * + * A `Result` is `Success` when a value is available and + * `Failure` when an error is available. It is plain data, so inspecting + * or transforming it does not run side effects. This module includes helpers + * for creating, checking, mapping, combining, and extracting results, plus + * conversions to and from `Option` and nullable values. + * + * @since 4.0.0 + */ + + + + + + + +const TypeId = "~effect/data/Result"; +/** + * 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` + * + * @category constructors + * @since 4.0.0 + */ +const succeed = _internal_result_js__rspack_import_0/* .succeed */.Py; +/** + * 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 + * + * @category constructors + * @since 4.0.0 + */ +const fail = _internal_result_js__rspack_import_0/* .fail */.fJ; +const void_ = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed(void 0))); + +/** + * Provides a pre-built failed `Result` whose failure value is `undefined`. + * + * **When to use** + * + * Use when you need a failed `Result` value that acts only as a control signal + * without failure data. + * + * **Details** + * + * This is equivalent to `Result.fail(undefined)` with type + * `Result`, but reuses a shared `Failure` wrapper instead of + * allocating one each time. + * + * **Example** (Failing without a payload) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.failVoid // => Result.fail(undefined) + * ``` + * + * @see {@link fail} to create a Failure with a specific value + * + * @category constructors + * @since 4.0.0 + */ +const failVoid = /*#__PURE__*/(/* unused pure expression or super */ null && (fail(void 0))); +/** + * Converts a possibly `null` or `undefined` value into a `Result`. + * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * + * - Non-nullish values become `Success>` + * - `null` or `undefined` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * - The `onNullish` callback receives the original value + * + * **Example** (Handling nullable values) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.fromNullishOr(1, () => "fallback") // => Result.succeed(1) + * + * Result.fromNullishOr(null, () => "fallback") // => Result.fail("fallback") + * ``` + * + * @see {@link fromOption} to convert from an Option + * @see {@link succeed} / {@link fail} for direct construction + * + * @category constructors + * @since 4.0.0 + */ +const fromNullishOr = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onNullish) => self == null ? fail(onNullish(self)) : succeed(self)))); +/** + * Converts an `Option` into a `Result`. + * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * + * - `Some` becomes `Success` + * - `None` becomes `Failure` using the provided function + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Converting an Option to a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.fromOption(Option.some(1), () => "missing") // => Result.succeed(1) + * + * Result.fromOption(Option.none(), () => "missing") // => Result.fail("missing") + * ``` + * + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values + * + * @category constructors + * @since 2.0.0 + */ +const fromOption = _internal_result_js__rspack_import_0/* .fromOption */.sV; +const try_ = evaluate => { + if (isFunction(evaluate)) { + try { + return succeed(evaluate()); + } catch (e) { + return fail(e); + } + } else { + try { + return succeed(evaluate.try()); + } catch (e) { + return fail(evaluate.catch(e)); + } + } +}; + +/** + * Checks whether a value is a `Result` (either `Success` or `Failure`). + * + * **When to use** + * + * Use to validate unknown input before operating on it as a `Result`. + * + * **Details** + * + * - Returns `true` for both `Success` and `Failure` variants + * - Acts as a TypeScript type guard, narrowing to `Result` + * + * **Example** (Checking if a value is a Result) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.isResult(Result.succeed(1)) // => true + * + * Result.isResult({ value: 1 }) // => false + * ``` + * + * @see {@link isSuccess} / {@link isFailure} to narrow to a specific variant + * + * @category guards + * @since 4.0.0 + */ +const isResult = _internal_result_js__rspack_import_0/* .isResult */.aI; +/** + * 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 + * + * @category guards + * @since 4.0.0 + */ +const isFailure = _internal_result_js__rspack_import_0/* .isFailure */.N6; +/** + * Checks whether a `Result` is a `Success`. + * + * **When to use** + * + * Use to narrow a known `Result` to the `Success` variant. + * + * **Details** + * + * - Acts as a TypeScript type guard, narrowing to `Success` + * - After narrowing, you can access `.success` to read the value + * + * **Example** (Narrowing to success) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * const result = Result.succeed(42) + * + * if (Result.isSuccess(result)) { + * result.success // => 42 + * } + * ``` + * + * @see {@link isFailure} for the opposite check + * @see {@link isResult} to check if a value is any Result + * + * @category guards + * @since 4.0.0 + */ +const isSuccess = _internal_result_js__rspack_import_0/* .isSuccess */.oJ; +/** + * Extracts the success value as an `Option`, discarding the failure. + * + * **When to use** + * + * Use when you need to extract the success value from a `Result` as an + * `Option` and discard failure information. + * + * **Details** + * + * - `Success` becomes `Some` + * - `Failure` becomes `None` + * + * **Example** (Extracting the success as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getSuccess(Result.succeed("ok")) // => Option.some("ok") + * + * Result.getSuccess(Result.fail("err")) // => Option.none() + * ``` + * + * @see {@link getFailure} to extract the error instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getSuccess = _internal_result_js__rspack_import_0/* .getSuccess */.Oz; +/** + * Extracts the failure value as an `Option`, discarding the success. + * + * **When to use** + * + * Use when you need to extract the failure value from a `Result` as an + * `Option` and discard successful values. + * + * **Details** + * + * - `Failure` becomes `Some` + * - `Success` becomes `None` + * + * **Example** (Extracting the failure as an Option) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.getFailure(Result.succeed("ok")) // => Option.none() + * + * Result.getFailure(Result.fail("err")) // => Option.some("err") + * ``` + * + * @see {@link getSuccess} to extract the success instead + * @see {@link fromOption} for the reverse conversion + * + * @category getters + * @since 4.0.0 + */ +const getFailure = _internal_result_js__rspack_import_0/* .getFailure */.L8; +/** + * Creates an `Equivalence` for comparing two `Result` values. + * + * **Details** + * + * - Two `Success` values are equal when the `success` equivalence says so + * - Two `Failure` values are equal when the `failure` equivalence says so + * - A `Success` and a `Failure` are never equal + * + * **Example** (Comparing Results for equality) + * + * ```ts import.meta.vitest + * import { Equivalence, Result } from "effect" + * + * const eq = Result.makeEquivalence( + * Equivalence.strictEqual(), + * Equivalence.strictEqual() + * ) + * + * eq(Result.succeed(1), Result.succeed(1)) // => true + * + * eq(Result.succeed(1), Result.fail("x")) // => false + * ``` + * + * @category instances + * @since 4.0.0 + */ +const makeEquivalence = (success, failure) => Equivalence.make((x, y) => isFailure(x) ? isFailure(y) && failure(x.failure, y.failure) : isSuccess(y) && success(x.success, y.success)); +/** + * Transforms both the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * + * **Example** (Mapping both channels) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(1), + * Result.mapBoth({ + * onSuccess: (n) => n + 1, + * onFailure: (e) => `Error: ${e}` + * }) + * ) // => Result.succeed(2) + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapError} to transform only the error value + * @see {@link match} to fold into a single value + * + * @category mapping + * @since 2.0.0 + */ +const mapBoth = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? fail(onFailure(self.failure)) : succeed(onSuccess(self.success))))); +/** + * Transforms the failure channel of a `Result`, leaving the success channel unchanged. + * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * + * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` + * - If the result is a `Success`, returns it as-is + * + * **Example** (Adding context to an error) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("not found"), + * Result.mapError((e) => `Error: ${e}`) + * ) // => Result.fail("Error: not found") + * ``` + * + * @see {@link map} to transform only the success value + * @see {@link mapBoth} to transform both channels + * + * @category mapping + * @since 4.0.0 + */ +const mapError = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(f(self.failure)) : self))); +/** + * Transforms the success channel of a `Result`, leaving the failure channel unchanged. + * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * + * - If the result is a `Success`, applies `f` to the value and returns a new `Success` + * - If the result is a `Failure`, returns it as-is + * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) + * + * **Example** (Doubling the success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(3), + * Result.map((n) => n * 2) + * ) // => Result.succeed(6) + * ``` + * + * @see {@link mapError} to transform only the error value + * @see {@link mapBoth} to transform both channels + * @see {@link flatMap} when `f` returns a `Result` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isSuccess(self) ? succeed(f(self.success)) : self))); +/** + * Folds a `Result` into a single value by applying one of two functions. + * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * + * - Applies `onSuccess` if the result is a `Success` + * - Applies `onFailure` if the result is a `Failure` + * - Both branches must return the same type (or a common supertype) + * + * **Example** (Folding to a string) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const format = Result.match({ + * onSuccess: (n: number) => `Got ${n}`, + * onFailure: (e: string) => `Err: ${e}` + * }) + * + * format(Result.succeed(42)) // => "Got 42" + * + * format(Result.fail("timeout")) // => "Err: timeout" + * ``` + * + * @see {@link merge} to extract `A | E` without mapping + * @see {@link getOrElse} to unwrap only the success with a fallback + * + * @category pattern matching + * @since 2.0.0 + */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, { + onFailure, + onSuccess +}) => isFailure(self) ? onFailure(self.failure) : onSuccess(self.success)); +/** + * Lifts a value into a `Result` based on a predicate or refinement. + * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * + * - If the predicate returns `true`, the value becomes `Success` + * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - Supports both data-first and data-last (piped) usage + * + * **Example** (Validating a number) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * 5, + * Result.liftPredicate( + * (n: number) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.succeed(5) + * ``` + * + * @see {@link filterOrFail} to validate a value that is already in a `Result` + * @see {@link fromNullishOr} for nullable-based construction + * + * @category constructors + * @since 3.4.0 + */ +const liftPredicate = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (a, predicate, orFailWith) => predicate(a) ? succeed(a) : fail(orFailWith(a))))); +/** + * Validates the success value of a `Result` using a predicate, failing with a + * custom error if the predicate returns `false`. + * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * + * - If the result is already a `Failure`, it is returned as-is + * - If the predicate passes, the `Success` is returned unchanged + * - If the predicate fails, `orFailWith` produces the error for a new `Failure` + * - Also accepts a `Refinement` to narrow the success type + * - The error type of the output is the union of both error types + * + * **Example** (Filtering a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(0), + * Result.filterOrFail( + * (n) => n > 0, + * (n) => `${n} is not positive` + * ) + * ) // => Result.fail("0 is not positive") + * ``` + * + * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate + * @see {@link flatMap} for general conditional chaining + * + * @category filtering + * @since 4.0.0 + */ +const filterOrFail = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(3, (self, predicate, orFailWith) => flatMap(self, a => predicate(a) ? succeed(a) : fail(orFailWith(a)))))); +/** + * Unwraps a `Result` into `A | E` by returning the inner value regardless + * of whether it is a success or failure. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `E` + * - Useful when both channels share a compatible type + * + * **Example** (Extracting the inner value) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.merge(Result.succeed(42)) // => 42 + * + * Result.merge(Result.fail("error")) // => "error" + * ``` + * + * @see {@link match} to map each branch to a common type + * @see {@link getOrElse} to provide a fallback for failures + * + * @category getters + * @since 2.0.0 + */ +const merge = /*#__PURE__*/(/* unused pure expression or super */ null && (match({ + onFailure: identity, + onSuccess: identity +}))); +/** + * Extracts the success value, or computes a fallback from the error. + * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * + * - `Success` returns the inner value + * - `Failure` applies `onFailure` to the error and returns the result + * - The return type is `A | A2` (union of both branches) + * + * **Example** (Providing a fallback) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrElse(Result.succeed(1), () => 0) // => 1 + * + * Result.getOrElse(Result.fail("err"), () => 0) // => 0 + * ``` + * + * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks + * @see {@link getOrThrow} to throw on failure + * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping + * + * @category getters + * @since 2.0.0 + */ +const getOrElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => isFailure(self) ? onFailure(self.failure) : self.success))); +/** + * Extracts the success value, or returns `null` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `null`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `null` + * + * **Example** (Unwrapping to nullable) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrNull(Result.succeed(1)) // => 1 + * + * Result.getOrNull(Result.fail("err")) // => null + * ``` + * + * @see {@link getOrUndefined} to return `undefined` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrNull = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constNull))); +/** + * Extracts the success value, or returns `undefined` on failure. + * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `undefined`. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` returns `undefined` + * + * **Example** (Unwrapping to optional) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrUndefined(Result.succeed(1)) // => 1 + * + * Result.getOrUndefined(Result.fail("err")) // => undefined + * ``` + * + * @see {@link getOrNull} to return `null` instead + * @see {@link getOrElse} for a custom fallback + * + * @category getters + * @since 2.0.0 + */ +const getOrUndefined = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrElse(constUndefined))); +/** + * Extracts the success value or throws a custom error derived from the failure. + * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws the value returned by `onFailure(e)` + * + * **Example** (Throwing a custom error) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrowWith(Result.succeed(1), () => new Error("fail")) // => 1 + * + * const failure = Result.try({ + * try: () => Result.getOrThrowWith( + * Result.fail("oops"), + * (error) => new Error(`Unexpected: ${error}`) + * ), + * catch: (error) => (error as Error).message + * }) + * Result.merge(failure) // => "Unexpected: oops" + * ``` + * + * @see {@link getOrThrow} to throw the raw failure value + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrowWith = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, onFailure) => { + if (isSuccess(self)) { + return self.success; + } + throw onFailure(self.failure); +}))); +/** + * Extracts the success value or throws the raw failure value `E`. + * + * **When to use** + * + * Use when unchecked boundaries should turn failures into thrown exceptions. + * + * **Details** + * + * - `Success` returns `A` + * - `Failure` throws `E` directly + * - Use {@link getOrThrowWith} for a custom error object + * + * **Example** (Unwrapping or throwing) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.getOrThrow(Result.succeed(1)) // => 1 + * + * const failure = Result.try(() => Result.getOrThrow(Result.fail("error"))) + * Result.merge(failure) // => "error" + * ``` + * + * @see {@link getOrThrowWith} for custom error mapping + * @see {@link getOrElse} for a non-throwing alternative + * + * @category getters + * @since 2.0.0 + */ +const getOrThrow = /*#__PURE__*/(/* unused pure expression or super */ null && (getOrThrowWith(identity))); +/** + * Returns the original `Result` if it is a `Success`, otherwise applies + * `that` to the error and returns the resulting `Result`. + * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * + * - `Success` is returned unchanged + * - `Failure` calls `that(e)` to produce a new `Result` + * + * **Example** (Recovering from a failure) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.fail("primary failed"), + * Result.orElse(() => Result.succeed(99)) + * ) // => Result.succeed(99) + * ``` + * + * @see {@link getOrElse} to unwrap with a fallback value (not a Result) + * @see {@link mapError} to transform the error without recovering + * + * @category error handling + * @since 2.0.0 + */ +const orElse = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => isFailure(self) ? that(self.failure) : succeed(self.success)))); +/** + * Chains a function that returns a `Result` onto a successful value. + * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * + * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` + * - If `self` is a `Failure`, short-circuits and returns it unchanged + * - The error types are merged into a union (`E | E2`) + * - This is the monadic `bind` / `>>=` for `Result` + * + * **Example** (Validating sequentially) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(5), + * Result.flatMap((n) => + * n > 0 ? Result.succeed(n * 2) : Result.fail("not positive") + * ) + * ) // => Result.succeed(10) + * ``` + * + * @see {@link andThen} for a more flexible variant that also accepts plain values + * @see {@link map} when `f` does not return a `Result` + * + * @category sequencing + * @since 2.0.0 + */ +const flatMap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => isFailure(self) ? fail(self.failure) : f(self.success)))); +/** + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** + * + * The second argument can be: + * - A function `(a: A) => Result` (same as `flatMap`) + * - A function `(a: A) => A2` (auto-wrapped in `succeed`) + * - A `Result` value (ignores the success of `self`) + * - A plain value `A2` (auto-wrapped in `succeed`, ignores `self`) + * + * If `self` is a `Failure`, the second argument is never evaluated. + * + * **Example** (Chaining Result values with different argument types) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * // With a function returning a Result + * const a = pipe( + * Result.succeed(1), + * Result.andThen((n) => Result.succeed(n + 1)) + * ) // => Result.succeed(2) + * + * // With a plain mapping function + * const b = pipe( + * Result.succeed(1), + * Result.andThen((n) => n + 1) + * ) // => Result.succeed(2) + * + * // With a constant value + * const c = pipe(Result.succeed(1), Result.andThen("done")) // => Result.succeed("done") + * ``` + * + * @see {@link flatMap} for the stricter variant (function returning Result only) + * @see {@link map} when you always return a plain value + * + * @category sequencing + * @since 2.0.0 + */ +const andThen = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => flatMap(self, a => { + const out = isFunction(f) ? f(a) : f; + return isResult(out) ? out : succeed(out); +})))); +/** + * Collects a structure of `Result`s into a single `Result` of collected values. + * + * **When to use** + * + * Use to collect independent `Result` values into one `Result` while preserving + * the original structure. + * + * **Details** + * + * Accepts: + * - A tuple/array: returns `Result` with a tuple/array of success values + * - A struct (record): returns `Result` with a struct of success values + * - An iterable: returns `Result` with an array of success values + * + * Short-circuits on the first `Failure` encountered; later elements are not inspected. + * + * **Example** (Collecting a tuple and a struct) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * // Tuple + * Result.all([Result.succeed(1), Result.succeed("two")]) // => Result.succeed([1, "two"]) + * + * // Struct + * Result.all({ x: Result.succeed(1), y: Result.fail("err") }) // => Result.fail("err") + * ``` + * + * @see {@link flatMap} for chaining two Results sequentially + * @see {@link gen} for generator-based composition of multiple Results + * + * @category sequencing + * @since 2.0.0 + */ +// @ts-expect-error +const all = input => { + if (Symbol.iterator in input) { + const out = []; + for (const e of input) { + if (isFailure(e)) { + return e; + } + out.push(e.success); + } + return succeed(out); + } + const out = {}; + for (const key of Object.keys(input)) { + const e = input[key]; + if (isFailure(e)) { + return e; + } + InternalRecord.assignProperty(out, key, e.success); + } + return succeed(out); +}; +/** + * Swaps the success and failure channels of a `Result`. + * + * **When to use** + * + * Use to swap channels when failure-focused operations are easier through + * success-oriented combinators. + * + * **Details** + * + * - `Success` becomes `Failure` (i.e., `Result`) + * - `Failure` becomes `Success` (i.e., `Result`) + * - Useful when you want to apply success-oriented operations (like `map`) + * to the error channel, then flip back + * + * **Example** (Swapping channels) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.flip(Result.succeed(42)) // => Result.fail(42) + * + * Result.flip(Result.fail("error")) // => Result.succeed("error") + * ``` + * + * @see {@link mapError} to transform the error without swapping + * + * @category transforming + * @since 2.0.0 + */ +const flip = self => isFailure(self) ? succeed(self.failure) : fail(self.success); +/** + * Provides generator-based syntax for composing `Result` values sequentially. + * + * **When to use** + * + * Use when you need generator syntax to compose sequential `Result` + * computations instead of nested `flatMap` calls. + * + * **Details** + * + * - Use `yield*` to unwrap a `Result` inside the generator; if any yielded + * `Result` is a `Failure`, the generator short-circuits and returns that failure + * - The return value of the generator is wrapped in `Success` + * - Evaluated eagerly and synchronously (unlike `Effect.gen`) + * + * **Example** (Composing multiple Results) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * + * Result.gen(function*() { + * const a = yield* Result.succeed(1) + * const b = yield* Result.succeed(2) + * return a + b + * }) // => Result.succeed(3) + * ``` + * + * @see {@link flatMap} for point-free sequential composition + * @see {@link all} to collect multiple independent Results + * + * @category generators + * @since 2.0.0 + */ +const gen = (...args) => { + const f = args.length === 1 ? args[0] : args[1].bind(args[0]); + const iterator = f(); + let state = iterator.next(); + while (!state.done) { + const current = state.value; + if (isFailure(current)) { + return current; + } + state = iterator.next(current.success); + } + return succeed(state.value); +}; +// ------------------------------------------------------------------------------------- +// do notation +// ------------------------------------------------------------------------------------- +/** + * Provides the starting point for the "do notation" simulation with `Result`. + * + * **When to use** + * + * Use to start a `Result` do-notation pipeline from an empty successful record + * before adding named fields from `Result`-producing computations and pure + * computed values. + * + * **Details** + * + * Creates a `Result<{}>` (success with an empty object). Use with + * {@link bind} to add `Result`-producing fields and {@link let_ let} + * to add pure computed fields. + * + * **Example** (Building an object step by step) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", () => Result.succeed(3)), + * Result.let("sum", ({ x, y }) => x + y) + * ) // => Result.succeed({ x: 2, y: 3, sum: 5 }) + * ``` + * + * @see {@link bind} to add Result-producing fields + * @see {@link let_ let} to add pure computed fields + * @see {@link gen} for an alternative generator-based syntax + * @see {@link bindTo} for starting a do-notation chain from an existing Result + * + * @category constructors + * @since 2.0.0 + */ +const Do = /*#__PURE__*/(/* unused pure expression or super */ null && (succeed({}))); +/** + * Adds a named field to the do-notation accumulator by running a `Result`-producing + * function that receives the current accumulated object. + * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * + * - Short-circuits on the first `Failure` + * - The field name must not collide with existing keys + * - Use {@link let_ let} for pure (non-Result) computed fields + * + * **Example** (Binding Result values) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.Do, + * Result.bind("x", () => Result.succeed(2)), + * Result.bind("y", ({ x }) => Result.succeed(x + 3)) + * ) // => Result.succeed({ x: 2, y: 5 }) + * ``` + * + * @see {@link Do} to start the do-notation chain + * @see {@link let_ let} for pure computed fields + * @see {@link bindTo} to wrap an initial Result into a named field + * + * @category sequencing + * @since 2.0.0 + */ +const bind = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bind(map, flatMap))); +/** + * Wraps the success value of a `Result` into a named field, producing a + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. + * + * **Example** (Wrapping a value into a named field) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * pipe( + * Result.succeed(42), + * Result.bindTo("answer") + * ) // => Result.succeed({ answer: 42 }) + * ``` + * + * @see {@link Do} to start from an empty object + * @see {@link bind} to add more fields + * + * @category mapping + * @since 2.0.0 + */ +const bindTo = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.bindTo(map))); +const let_ = /*#__PURE__*/(/* unused pure expression or super */ null && (doNotation.let_(map))); + +/** + * Transforms `Option>` into `Result, E>`. + * + * **When to use** + * + * Use when optional absence should be treated as a successful `None`, while an + * inner `Result` failure should still fail the whole result. + * + * **Details** + * + * - `None` becomes `Success(None)` + * - `Some(Success(a))` becomes `Success(Some(a))` + * - `Some(Failure(e))` becomes `Failure(e)` + * + * **Example** (Transposing an Option of a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.transposeOption(Option.some(Result.succeed(42))) // => Result.succeed(Option.some(42)) + * + * Result.transposeOption(Option.none>()) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeMapOption} to map and transpose in one step + * + * @category transposing + * @since 3.14.0 + */ +const transposeOption = self => { + return option_.isNone(self) ? succeedNone : map(self.value, option_.some); +}; +/** + * Maps an `Option` value with a `Result`-producing function, then transposes + * the structure from `Option>` to `Result, E>`. + * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * + * - `None` becomes `Success(None)` (the function is never called) + * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` + * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` + * + * **Example** (Mapping and transposing in one step) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * const parse = (s: string) => + * isNaN(Number(s)) + * ? Result.fail("not a number" as const) + * : Result.succeed(Number(s)) + * + * Result.transposeMapOption(Option.some("42"), parse) // => Result.succeed(Option.some(42)) + * + * Result.transposeMapOption(Option.none(), parse) // => Result.succeed(Option.none()) + * ``` + * + * @see {@link transposeOption} when the Option already contains a Result + * + * @category transposing + * @since 3.15.0 + */ +const transposeMapOption = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some)))); +/** + * Provides a pre-built `Result>` that succeeds with `None`. + * + * **When to use** + * + * Use when an optional success should be absent, such as the `None` branch of + * `transposeOption` or `transposeMapOption`. + * + * **Details** + * + * This is equivalent to `Result.succeed(Option.none())`, but reuses a shared + * `Success` wrapper instead of allocating one each time. + * + * **Example** (Succeeding with None) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedNone // => Result.succeed(Option.none()) + * ``` + * + * @see {@link succeedSome} for the `Some` counterpart + * @see {@link transposeOption} to transpose an Option that already contains a Result + * @see {@link transposeMapOption} to map and transpose an Option in one step + * + * @category constructors + * @since 4.0.0 + */ +const succeedNone = /*#__PURE__*/succeed(_internal_option_js__rspack_import_2/* .none */.dv); +/** + * Creates a `Result>` that succeeds with `Some(a)`. + * + * **Details** + * + * - Equivalent to `Result.succeed(Option.some(a))` + * - Useful with {@link transposeOption} patterns + * + * **Example** (Wrapping a value in Some inside a Result) + * + * ```ts import.meta.vitest + * import { Option, Result } from "effect" + * + * Result.succeedSome(42) // => Result.succeed(Option.some(42)) + * ``` + * + * @see {@link succeedNone} for the `None` counterpart + * + * @category constructors + * @since 4.0.0 + */ +const succeedSome = a => succeed(option_.some(a)); +/** + * Runs a side-effect on the success value without altering the `Result`. + * + * **Details** + * + * - If the result is a `Success`, calls `f` with the value (return value is ignored) + * - If the result is a `Failure`, `f` is not called + * - Returns the original `Result` unchanged (same reference) + * - Useful for logging, debugging, or performing mutations outside the Result chain + * + * **Example** (Logging a success value) + * + * ```ts import.meta.vitest + * import { pipe, Result } from "effect" + * + * const values: Array = [] + * const result = pipe( + * Result.succeed(42), + * Result.tap((n) => values.push(n)) + * ) + * + * values // => [42] + * result // => Result.succeed(42) + * ``` + * + * @see {@link map} to transform the success value + * + * @category mapping + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => { + if (isSuccess(self)) { + f(self.success); + } + return self; +}))); +//# sourceMappingURL=Result.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + N6: isFailure, + Py: succeed, + YW: match, + fJ: fail, + oJ: isSuccess +}); + + +}, +"./node_modules/effect/dist/Schedule.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Cause_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Cause.js"); +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _internal_core_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _internal_effect_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/internal/effect.js"); +/* import */ var _Pipeable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Pull_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Pull.js"); + + + + + + + + + + + + +const TypeId = "~effect/Schedule"; +const randomNext = /*#__PURE__*/(/* unused pure expression or super */ null && (random.Random.useSync(random => random.nextDoubleUnsafe()))); +/** + * Context reference containing metadata for the currently running schedule step. + * + * **Details** + * + * Repeat, retry, stream, and channel scheduling operations provide this service + * to effects run between schedule steps. The default value contains undefined + * input and output values, zero duration, and zeroed timing fields before any + * schedule step has produced metadata. + * + * @category services + * @since 4.0.0 + */ +const CurrentMetadata = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Schedule/CurrentMetadata", { + defaultValue: /*#__PURE__*/(0,_Function_js__rspack_import_1/* .constant */.dY)({ + input: undefined, + output: undefined, + duration: _Duration_js__rspack_import_2/* .zero */.v_, + attempt: 0, + start: 0, + now: 0, + elapsed: 0, + elapsedSincePrevious: 0 + }) +}); +const ScheduleProto = { + [TypeId]: { + _Out: _Function_js__rspack_import_1/* .identity */.D_, + _In: _Function_js__rspack_import_1/* .identity */.D_, + _Env: _Function_js__rspack_import_1/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_3/* .pipeArguments */.tT)(this, arguments); + } +}; +/** + * Type guard that checks if a value is a Schedule. + * + * **Example** (Checking for schedules) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.exponential("100 millis") + * const notSchedule = { foo: "bar" } + * + * Schedule.isSchedule(schedule) // => true + * Schedule.isSchedule(notSchedule) // => false + * Schedule.isSchedule(null) // => false + * Schedule.isSchedule(undefined) // => false + * ``` + * + * @category guards + * @since 2.0.0 + */ +const isSchedule = u => (0,_Predicate_js__rspack_import_4/* .hasProperty */.i5)(u, TypeId); +/** + * Creates a Schedule from a step function that returns a Pull. + * + * **Example** (Creating a custom schedule from a step function) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.fromStep(Effect.sync(() => { + * let count = 0 + * + * return (_now: number, _input: string) => { + * if (count >= 3) { + * return Cause.done(count) + * } + * return Effect.succeed([count++, Duration.millis(100)] as [number, Duration.Duration]) + * } + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => 0 + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStep = step => { + const self = Object.create(ScheduleProto); + self.step = step; + return self; +}; +const metadataFn = () => { + let n = 0; + let previous; + let start; + return (now, input) => { + if (start === undefined) start = now; + const elapsed = now - start; + const elapsedSincePrevious = previous === undefined ? 0 : now - previous; + previous = now; + return { + input, + attempt: ++n, + start, + now, + elapsed, + elapsedSincePrevious + }; + }; +}; +/** + * Creates a Schedule from a step function that receives metadata about the schedule's execution. + * + * **Example** (Creating a metadata-aware schedule) + * + * ```ts import.meta.vitest + * import { Cause, Duration, Effect, Schedule } from "effect" + * + * const firstThreeInputs = Schedule.fromStepWithMetadata(Effect.succeed((metadata: Schedule.InputMetadata) => { + * if (metadata.attempt > 3) { + * return Cause.done("finished") + * } + * + * return Effect.succeed([ + * `attempt ${metadata.attempt}: ${metadata.input}`, + * Duration.millis(250) + * ] as [string, Duration.Duration]) + * })) + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(firstThreeInputs) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "attempt 1: input" + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const fromStepWithMetadata = step => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(step, f => { + const meta = metadataFn(); + return (now, input) => f(meta(now, input)); +})); +/** + * Extracts the step function from a Schedule. + * + * **Example** (Extracting a schedule step function) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * // Extract step function from an existing schedule + * const schedule = Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * + * const program = Effect.gen(function*() { + * const stepFn = yield* Schedule.toStep(schedule) + * + * // Use the step function directly for custom logic. The timestamp is + * // supplied by the caller, so tests can pass a deterministic value. + * const now = 0 + * return yield* stepFn(now, "input") + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStep = schedule => _internal_effect_js__rspack_import_5/* .catchCause */.Tyx(schedule.step, cause => _internal_effect_js__rspack_import_5/* .succeed */.PyW(() => _internal_effect_js__rspack_import_5/* .failCause */.ATB(cause))); +/** + * Extracts a step function from a `Schedule` that sleeps for each computed + * delay and returns metadata for the completed step. + * + * **When to use** + * + * Use to drive a schedule manually while preserving the computed output, + * delay, input, attempt, and elapsed timing metadata for each step. + * + * **Details** + * + * The returned step reads the current time from `Clock` when invoked, calls the + * schedule step with that timestamp and input, sleeps for the returned + * duration, and then yields `Metadata`. + * + * @see {@link toStep} for manually supplying the timestamp and handling the returned delay yourself + * @see {@link toStepWithSleep} for the same automatic sleeping behavior when only the schedule output is needed + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithMetadata = schedule => _internal_effect_js__rspack_import_5/* .clockWith */.RKA(clock => _internal_effect_js__rspack_import_5/* .map */.TjK(toStep(schedule), step => { + const metaFn = metadataFn(); + return input => _internal_effect_js__rspack_import_5/* .suspend */.DYE(() => { + const now = clock.currentTimeMillisUnsafe(); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), ([output, duration]) => { + const meta = metaFn(now, input); + meta.output = output; + meta.duration = duration; + return _internal_effect_js__rspack_import_5.as(_internal_effect_js__rspack_import_5/* .sleep */.yy4(duration), meta); + }); + }); +})); +/** + * Extracts a step function from a Schedule that automatically handles sleep delays. + * + * **Example** (Extracting a sleeping step function) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const schedule = Schedule.recurs(3) + * + * const program = Effect.gen(function*() { + * const stepWithSleep = yield* Schedule.toStepWithSleep(schedule) + * + * return [yield* stepWithSleep("first"), yield* stepWithSleep("second")] + * }) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [0, 1] + * ``` + * + * @category destructors + * @since 4.0.0 + */ +const toStepWithSleep = schedule => effect.map(toStepWithMetadata(schedule), step => input => effect.map(step(input), meta => meta.output)); +/** + * Returns a new `Schedule` that adds the delay computed by the specified + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.recurs(1).pipe( + * Schedule.addDelay(() => Effect.succeed("25 millis")) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(25) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const addDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => modifyDelay(self, metadata => effect.map(f(metadata), d => Duration.sum(Duration.fromInputUnsafe(d), metadata.duration)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concat(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 2.0.0 + */ +const concat = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => map(concatResult(self, other), ({ + output +}) => effect.succeed(Result.merge(output)))))); +/** + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.concatResult(Schedule.recurs(1), Schedule.recurs(2)) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const concatResult = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, other) => fromStep(effect.sync(() => { + let currentSide = 0; + let currentStep; + const left = map(self, ({ + output + }) => Result.fail(output)); + const right = map(other, ({ + output + }) => Result.succeed(output)); + return function recur(now, input) { + if (currentStep) return currentStep(now, input); + return toStep(currentSide === 0 ? left : right).pipe(effect.flatMap(step => { + currentSide++; + if (currentSide === 1) { + currentStep = (now, input) => Pull.catchDone(step(now, input), _ => { + currentStep = undefined; + return recur(now, input); + }); + return currentStep(now, input); + } + currentStep = step; + return currentStep(now, input); + })); + }; +}))))); +/** + * Combines schedules by recurring while all schedules want to recur, using the + * maximum delay between recurrences and outputting that maximum delay. + * + * **When to use** + * + * Use when a combined policy should continue only while every schedule still + * recurs, and should wait for the slowest schedule between recurrences. + * + * **Example** (Combining retry schedules by their maximum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.max([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const max = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = maxDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const maxDuration = results => { + let max = results[0]; + for (let i = 1; i < results.length; i++) { + max = results[i] && max && Duration.max(max, results[i]); + if (max === undefined) break; + } + return max; +}; +/** + * Returns a new `Schedule` that recurs on the specified `Cron` schedule and + * outputs the duration between recurrences. + * + * **Example** (Scheduling work with cron expressions) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const everyMinute = Schedule.cron("* * * * *") + * Schedule.isSchedule(everyMinute) // => true + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const cron = (expression, tz) => { + const parsed = Cron.isCron(expression) ? Result.succeed(expression) : Cron.parse(expression, tz); + return fromStep(effect.map(effect.fromResult(parsed), cron => (now, _) => { + if (now === Number.POSITIVE_INFINITY) { + return Cause.done(Duration.zero); + } + return effect.sync(() => { + const next = Cron.next(cron, now).getTime(); + const duration = Duration.millis(next - now); + return [duration, duration]; + }); + })); +}; +/** + * Returns a schedule that recurs once after the specified duration. + * + * **When to use** + * + * Use when you need a schedule that recurs once after a fixed delay. + * + * **Details** + * + * The schedule outputs the configured duration for its first recurrence and + * then completes. + * + * **Example** (Recurring once after a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.duration("1 second")) // => true + * ``` + * + * @see {@link during} for recurring until a duration has elapsed + * + * @category constructors + * @since 2.0.0 + */ +const duration = durationInput => { + const duration = Duration.fromInputUnsafe(durationInput); + return fromStepWithMetadata(effect.succeed(meta => meta.attempt === 1 ? effect.succeed([duration, duration]) : Cause.done(Duration.zero))); +}; +/** + * Returns a new `Schedule` that will always recur, but only during the + * specified `duration` of time. + * + * **When to use** + * + * Use to bound a repeating or retrying schedule by elapsed time. + * + * **Example** (Repeating work during a duration) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * Schedule.isSchedule(Schedule.during("5 seconds")) // => true + * ``` + * + * @see {@link duration} for one delayed recurrence + * + * @category constructors + * @since 4.0.0 + */ +const during = duration => { + const durationMillis = Duration.toMillis(duration); + return fromStepWithMetadata(effect.succeed(meta => { + const elapsed = Duration.millis(meta.elapsed); + return meta.elapsed > durationMillis ? Cause.done(elapsed) : effect.succeed([elapsed, Duration.zero]); + })); +}; +/** + * Combines schedules by recurring while at least one schedule wants to recur, + * using the minimum delay between recurrences and outputting that minimum delay. + * + * **When to use** + * + * Use when a combined policy should continue while any schedule still recurs, + * and should wait for the fastest schedule between recurrences. + * + * **Example** (Combining retry schedules by their minimum delay) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.min([Schedule.fixed("5 seconds"), Schedule.spaced("10 seconds")]) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category combining + * @since 4.0.0 + */ +const min = schedules => fromStep(effect.map(effect.all(schedules.map(toStep)), steps => (now, input) => effect.flatMap(effect.forEach(steps, step => Pull.matchEffect(step(now, input), { + onSuccess: result => effect.succeed(result[1]), + onDone: () => effect.undefined, + onFailure: effect.failCause +})), results => { + const duration = minDuration(results); + if (duration === undefined) { + return Cause.done(Duration.zero); + } + return effect.succeed([duration, duration]); +}))); +const minDuration = results => { + let min = undefined; + for (let i = 0; i < results.length; i++) { + const duration = results[i]; + if (duration !== undefined) { + min = min === undefined ? duration : Duration.min(min, duration); + } + } + return min; +}; +/** + * Schedule that always recurs, but will wait a certain amount between + * repetitions, given by `base * factor.pow(n)`, where `n` is the number of + * repetitions so far. Returns the current duration between recurrences. + * + * **Example** (Retrying with exponential backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.exponential("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const exponential = (base, factor = 2) => { + const baseMillis = Duration.toMillis(Duration.fromInputUnsafe(base)); + return fromStepWithMetadata(effect.succeed(meta => { + const duration = Duration.millis(baseMillis * Math.pow(factor, meta.attempt - 1)); + return effect.succeed([duration, duration]); + })); +}; +/** + * Schedule that always recurs, increasing delays by summing the preceding + * two delays (similar to the Fibonacci sequence). Returns the current + * duration between recurrences. + * + * **Example** (Retrying with Fibonacci backoff) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fibonacci("100 millis")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [Duration.millis(100), Duration.millis(100)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const fibonacci = one => { + const oneMillis = Duration.toMillis(Duration.fromInputUnsafe(one)); + return fromStep(effect.sync(() => { + let a = 0; + let b = oneMillis; + return constant(effect.sync(() => { + const next = a + b; + a = b; + b = next; + const duration = Duration.millis(next); + return [duration, duration]; + })); + })); +}; +/** + * Returns a `Schedule` that recurs on the specified fixed `interval` and + * outputs the number of repetitions of the schedule so far. + * + * **When to use** + * + * Use when recurrences should stay aligned to a regular cadence. + * + * **Gotchas** + * + * If the action run between recurrences takes longer than the interval, the + * next recurrence happens immediately, but missed intervals are not replayed. + * + * ```text + * |-----interval-----|-----interval-----|-----interval-----| + * |---------action--------||action|-----|action|-----------| + * ``` + * + * **Example** (Repeating on fixed intervals) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.fixed("1 second")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(1)] + * ``` + * + * @see {@link spaced} for delaying after each action completes + * + * @category constructors + * @since 2.0.0 + */ +const fixed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.sync(() => { + let start = 0; + let lastRun = 0; + return meta => effect.sync(() => { + if (window === 0) { + return [meta.attempt - 1, Duration.zero]; + } + if (meta.attempt === 1) { + start = meta.now; + lastRun = meta.now + window; + return [0, Duration.millis(window)]; + } + const runningBehind = meta.now > lastRun + window; + const boundary = window - (meta.now - start) % window; + const delay = runningBehind ? 0 : boundary === 0 ? window : boundary; + lastRun = runningBehind ? meta.now : meta.now + delay; + return [meta.attempt - 1, Duration.millis(delay)]; + }); + })); +}; +/** + * Returns a new `Schedule` that maps each schedule decision to a new output + * using the full schedule metadata. + * + * **Details** + * + * The callback receives the schedule input, output, selected delay duration, + * current attempt, and elapsed timing information. Return either a plain value + * or an `Effect` that produces the new output. + * + * **Example** (Mapping schedule outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const countSchedule = Schedule.recurs(5).pipe( + * Schedule.map(({ output: count }) => Effect.succeed(`Execution #${count + 1}`)) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(countSchedule) + * const [output] = yield* step(0, undefined) + * return output + * }) + * + * await Effect.runPromise(program) // => "Execution #1" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const map = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => Pull.matchEffect(step(now, input), { + onSuccess: ([output, duration]) => { + const result = f({ + ...meta(now, input), + output, + duration + }); + if (!isEffect(result)) return effect.succeed([result, duration]); + return effect.map(result, output => [output, duration]); + }, + onFailure: effect.failCause, + onDone: output => { + const result = f({ + ...meta(now, input), + output, + duration: Duration.zero + }); + if (!isEffect(result)) return Cause.done(result); + return effect.flatMap(result, Cause.done); + } + }); +}))))); +/** + * Returns a new `Schedule` that modifies the delay of the next recurrence + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule metadata) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const schedule = Schedule.spaced("10 millis").pipe( + * Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.times(duration, 2))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(schedule) + * const [, delay] = yield* step(0, undefined) + * return delay + * }) + * + * await Effect.runPromise(program) // => Duration.millis(20) + * ``` + * + * @category delays & timeouts + * @since 2.0.0 + */ +const modifyDelay = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.flatMap(step(now, input), ([output, duration]) => effect.map(f({ + ...meta(now, input), + output, + duration + }), replacement => [output, Duration.fromInputUnsafe(replacement)])); +}))))); +/** + * Returns a new `Schedule` that randomly adjusts each recurrence delay. + * + * **When to use** + * + * Use to add random variation to an existing schedule's recurrence delays while + * preserving its output and completion behavior. + * + * **Details** + * + * Each recurrence delay is scaled by a random factor between `0.8` and `1.2`. + * + * @see {@link modifyDelay} for replacing recurrence delays with a custom effectful transformation + * + * @category delays & timeouts + * @since 2.0.0 + */ +const jittered = self => modifyDelay(self, ({ + duration +}) => effect.map(randomNext, random => { + const millis = Duration.toMillis(duration); + return Duration.millis(millis * 0.8 * (1 - random) + millis * 1.2 * random); +})); +/** + * Returns a new `Schedule` that outputs the inputs of the specified schedule. + * + * **Example** (Passing inputs through as outputs) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const inputSchedule = Schedule.passthrough( + * Schedule.exponential("100 millis").pipe(Schedule.upTo({ times: 3 })) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(inputSchedule) + * const [output] = yield* step(0, "input") + * return output + * }) + * + * await Effect.runPromise(program) // => "input" + * ``` + * + * @category mapping + * @since 2.0.0 + */ +const passthrough = self => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => (now, input) => _Pull_js__rspack_import_6/* .matchEffect */.tv(step(now, input), { + onSuccess: result => _internal_effect_js__rspack_import_5/* .succeed */.PyW([input, result[1]]), + onFailure: _internal_effect_js__rspack_import_5/* .failCause */.ATB, + onDone: () => _Cause_js__rspack_import_7/* .done */.Vw(input) +}))); +/** + * Returns a `Schedule` which can only be stepped the specified number of + * `times` before it terminates. + * + * **When to use** + * + * Use when you need a counter schedule with no additional delay. + * + * **Gotchas** + * + * `recurs(n)` counts schedule recurrences, not the first evaluation of the + * effect being repeated or retried. For retrying, this means one initial + * attempt plus at most `n` retries. + * + * **Example** (Limiting recurrences) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(Schedule.recurs(3)), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3, 4] + * ``` + * + * @see {@link upTo} for limiting an existing schedule + * + * @category constructors + * @since 2.0.0 + */ +const recurs = times => while_(forever, ({ + attempt +}) => _internal_effect_js__rspack_import_5/* .succeed */.PyW(attempt <= times)); +/** + * Returns a schedule that recurs continuously, each repetition spaced the + * specified duration from the last run. + * + * **When to use** + * + * Use when each delay should start after the previous action completes. + * + * **Example** (Repeating with fixed spacing) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.spaced("2 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(2)] + * ``` + * + * @see {@link fixed} for recurrence aligned to a regular cadence + * + * @category constructors + * @since 2.0.0 + */ +const spaced = duration => { + const decoded = _Duration_js__rspack_import_2/* .fromInputUnsafe */.bN(duration); + return fromStepWithMetadata(_internal_effect_js__rspack_import_5/* .succeed */.PyW(meta => _internal_effect_js__rspack_import_5/* .succeed */.PyW([meta.attempt - 1, decoded]))); +}; +/** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * + * const attempts: Array = [] + * const monitoredSchedule = Schedule.recurs(2).pipe( + * Schedule.tap((metadata) => Effect.sync(() => attempts.push(metadata.attempt))) + * ) + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(monitoredSchedule) + * const [output] = yield* step(0, undefined) + * return { attempts, output } + * }) + * + * await Effect.runPromise(program) // => { attempts: [1], output: 0 } + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +const tap = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, f) => fromStep(effect.map(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => effect.tap(step(now, input), ([output, duration]) => f({ + ...meta(now, input), + output, + duration + })); +}))))); +/** + * Returns a new `Schedule` that limits an existing schedule by elapsed + * duration, number of outputs, or both. + * + * **When to use** + * + * Use to bound an existing schedule while preserving its output and delay + * behavior. When both `duration` and `times` are specified, the schedule + * stops as soon as either limit is reached. + * + * **Gotchas** + * + * The `times` option limits schedule outputs. When used with repeat or retry, + * the effect is evaluated once before the schedule is stepped, so the total + * number of evaluations can be one greater than the configured number of + * outputs. + * + * The `duration` option is based on the elapsed time observed by the schedule + * step. Long-running effects can cause the duration limit to be detected on the + * following schedule step. + * + * **Example** (Limiting by duration and recurrence count) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category filtering + * @since 4.0.0 + */ +const upTo = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, options) => { + const duration = options.duration === undefined ? undefined : Duration.fromInputUnsafe(options.duration); + return while_(self, ({ + attempt, + elapsed + }) => effect.succeed((options.times === undefined || attempt <= options.times) && (duration === undefined || Duration.isLessThanOrEqualTo(Duration.millis(elapsed), duration)))); +}))); +const while_ = /*#__PURE__*/(0,_Function_js__rspack_import_1/* .dual */.XY)(2, (self, predicate) => fromStep(_internal_effect_js__rspack_import_5/* .map */.TjK(toStep(self), step => { + const meta = metadataFn(); + return (now, input) => _internal_effect_js__rspack_import_5/* .flatMap */.qIB(step(now, input), result => { + const [output, duration] = result; + const eff = predicate({ + ...meta(now, input), + output, + duration + }); + return _internal_effect_js__rspack_import_5/* .flatMap */.qIB((0,_internal_core_js__rspack_import_8/* .isEffect */.yw)(eff) ? eff : _internal_effect_js__rspack_import_5/* .succeed */.PyW(eff), check => check ? _internal_effect_js__rspack_import_5/* .succeed */.PyW(result) : _Cause_js__rspack_import_7/* .done */.Vw(output)); + }); +}))); + +/** + * Schedule that divides the timeline to `interval`-long windows, and sleeps + * until the nearest window boundary every time it recurs. + * + * **Details** + * + * For example, `Schedule.windowed("10 seconds")` would produce a schedule as + * follows: + * + * ```text + * 10s 10s 10s 10s + * |----------|----------|----------|----------| + * |action------|sleep---|act|-sleep|action----| + * ``` + * + * **Example** (Repeating on aligned windows) + * + * ```ts import.meta.vitest + * import { Duration, Effect, Schedule } from "effect" + * + * const program = Effect.gen(function*() { + * const step = yield* Schedule.toStep(Schedule.windowed("5 seconds")) + * return yield* step(0, undefined) + * }) + * + * await Effect.runPromise(program) // => [0, Duration.seconds(5)] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const windowed = interval => { + const window = Duration.toMillis(Duration.fromInputUnsafe(interval)); + return fromStepWithMetadata(effect.succeed(meta => effect.sync(() => [meta.attempt - 1, window === 0 ? Duration.zero : Duration.millis(window - meta.elapsed % window)]))); +}; +/** + * Returns a new `Schedule` that will recur forever. + * + * **Details** + * + * The output of the schedule is the current count of its repetitions thus far + * (i.e. `0, 1, 2, ...`). + * + * **Example** (Repeating forever) + * + * ```ts import.meta.vitest + * import { Effect, Schedule } from "effect" + * import { TestClock } from "effect/testing" + * + * const executions: Array = [] + * const schedule = Schedule.forever.pipe(Schedule.upTo({ times: 2 })) + * const program = Effect.sync(() => executions.push(executions.length + 1)).pipe( + * Effect.repeat(schedule), + * Effect.as(executions) + * ) + * + * await Effect.runPromise(Effect.provide(program, TestClock.layer())) // => [1, 2, 3] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const forever = /*#__PURE__*/spaced(_Duration_js__rspack_import_2/* .zero */.v_); +const constIdentity = /*#__PURE__*/(/* unused pure expression or super */ null && (fromStep(/*#__PURE__*/effect.succeed((_now, input) => effect.succeed([input, Duration.zero]))))); +const identity_ = () => constIdentity; + +/** + * Sets the input type of the provided schedule without altering its behavior. + * + * **When to use** + * + * Use to adapt a schedule that does not depend on its input values. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Setting a schedule input type) + * + * ```ts import.meta.vitest + * import { Schedule } from "effect" + * + * const schedule = Schedule.recurs(3).pipe( + * Schedule.setInputType() + * ) + * Schedule.isSchedule(schedule) // => true + * ``` + * + * @category utility types + * @since 4.0.0 + */ +const setInputType = () => self => self; +//# sourceMappingURL=Schedule.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + E6: while_, + GM: isSchedule, + d3: CurrentMetadata, + i4: forever, + ji: spaced, + le: passthrough, + t5: recurs, + xn: toStepWithMetadata +}); + + +}, +"./node_modules/effect/dist/Scheduler.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.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. + * + * @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. + * + * @category services + * @since 2.0.0 + */ +const Scheduler = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setImmediate = "setImmediate" in globalThis ? f => { + // @ts-ignore + const timer = globalThis.setImmediate(f); + // @ts-ignore + return () => globalThis.clearImmediate(timer); +} : f => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setMicrotask = f => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +class PriorityBuckets { + 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. + * + * @category models + * @since 2.0.0 + */ +class MixedScheduler { + 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.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); + } +} +class MixedSchedulerDispatcher { + tasks = /*#__PURE__*/new PriorityBuckets(); + running = undefined; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === undefined) { + this.running = this.setImmediate(this.afterScheduled); + } + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = undefined; + 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 !== undefined) { + this.running(); + this.running = undefined; + } + 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 + * + * @category services + * @since 4.0.0 + */ +const MaxOpsBeforeYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("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 + * + * @category services + * @since 4.0.0 + */ +const PreventSchedulerYield = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +//# sourceMappingURL=Scheduler.js.map +__webpack_require__.d(__webpack_exports__, { + FG: () => (MixedScheduler) +}, { + Zm: MaxOpsBeforeYield, + _F: Scheduler, + hf: PreventSchedulerYield +}); + + +}, +"./node_modules/effect/dist/Scope.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _internal_effect_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/effect.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. + * + * @since 2.0.0 + */ + +const TypeId = _internal_effect_js__rspack_import_0/* .ScopeTypeId */.kWD; +const CloseableTypeId = _internal_effect_js__rspack_import_0/* .ScopeCloseableTypeId */.obm; +/** + * Service tag for the active resource lifetime. + * + * **When to use** + * + * Use to access the active lifetime when registering finalizers or sharing + * resources with the surrounding scope. + * + * **Example** (Accessing the scope service) + * + * ```ts import.meta.vitest + * import { Effect, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.Scope + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) + * }) + * + * Effect.runSync(Effect.scoped(program)) + * cleanups // => ["Cleanup"] + * ``` + * + * @category services + * @since 2.0.0 + */ +const Scope = _internal_effect_js__rspack_import_0/* .scopeTag */.DLK; +/** + * Creates a new `Scope` with the specified finalizer strategy. + * + * **Example** (Creating a scope) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup 2"))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * cleanups // => ["Cleanup 2", "Cleanup 1"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const make = _internal_effect_js__rspack_import_0/* .scopeMake */.RWE; +/** + * 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"] + * ``` + * + * @category constructors + * @since 4.0.0 + */ +const makeUnsafe = _internal_effect_js__rspack_import_0/* .scopeMakeUnsafe */.d97; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const provide = _internal_effect_js__rspack_import_0/* .provideScope */.AAo; +/** + * Registers an exit-aware finalizer on a scope. + * + * **When to use** + * + * Use when cleanup needs to know whether the scope closed with success, + * failure, or interruption. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes and receives + * the scope's exit value. If the scope is already closed, the finalizer runs + * immediately with the stored exit value. + * + * **Example** (Adding an exit-aware finalizer) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const exits: Array> = [] + * const withResource = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizerExit(scope, (exit) => Effect.sync(() => exits.push(exit))) + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(withResource) + * exits // => [Exit.void] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizerExit = _internal_effect_js__rspack_import_0/* .scopeAddFinalizerExit */.Uio; +/** + * Registers a finalizer effect on a scope. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes, regardless of + * whether the scope closes successfully or with an error. If the scope is + * already closed, the finalizer runs immediately. + * + * **Example** (Adding finalizers) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const events: Array = [] + * const program = Effect.gen(function*() { + * const scope = yield* Scope.make() + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 1"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 2"))) + * yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup 3"))) + * events.push("work") + * yield* Scope.close(scope, Exit.void) + * }) + * + * Effect.runSync(program) + * events // => ["work", "cleanup 3", "cleanup 2", "cleanup 1"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const addFinalizer = _internal_effect_js__rspack_import_0/* .scopeAddFinalizer */.iLB; +/** + * Creates a closeable child scope registered with a parent scope. + * + * **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) + * + * ```ts import.meta.vitest + * import { Effect, Exit, Scope } from "effect" + * + * const cleanups: Array = [] + * const nestedScopes = Effect.gen(function*() { + * const parentScope = yield* Scope.make("sequential") + * yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) + * const childScope = yield* Scope.fork(parentScope, "parallel") + * yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) + * yield* Scope.close(childScope, Exit.void) + * yield* Scope.close(parentScope, Exit.void) + * }) + * + * Effect.runSync(nestedScopes) + * cleanups // => ["child", "parent"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const fork = _internal_effect_js__rspack_import_0/* .scopeFork */.Z$R; +/** + * 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"] + * ``` + * + * @category combinators + * @since 4.0.0 + */ +const forkUnsafe = _internal_effect_js__rspack_import_0/* .scopeForkUnsafe */.pSt; +/** + * 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`. + * + * **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"] + * ``` + * + * @category combinators + * @since 2.0.0 + */ +const close = _internal_effect_js__rspack_import_0/* .scopeClose */.vDJ; +/** + * Closes a scope unsafely with the provided exit value. + * + * **When to use** + * + * Use when implementing lower-level scope machinery that must transition a + * scope to `Closed` immediately and can run the returned finalizer effect when + * one is produced. + * + * **Details** + * + * Returns an effect that runs registered finalizers, or `undefined` when the + * scope was already closed or no finalizers need to run. + * + * **Gotchas** + * + * Ignoring the returned effect skips registered finalizers. + * + * @see {@link close} for the usual effectful close operation that always returns an `Effect` + * + * @category unsafe + * @since 4.0.0 + */ +const closeUnsafe = _internal_effect_js__rspack_import_0/* .scopeCloseUnsafe */.fou; +/** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * + * @category combinators + * @since 2.0.0 + */ +const use = _internal_effect_js__rspack_import_0/* .scopeUse */.mdu; +//# sourceMappingURL=Scope.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Fp: forkUnsafe, + Gt: provide, + LZ: makeUnsafe, + VN: close +}); + + +}, +"./node_modules/effect/dist/Tracer.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Context_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Encoding_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Encoding.js"); +/* import */ var _Function_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Option_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/** + * Defines the low-level tracing model used by Effect. + * + * A span records the lifetime of an operation, including its name, parent, + * attributes, links, annotations, sampling decision, kind, and completion + * status. The module also defines the tracer service, parent-span context, + * external span support, trace propagation settings, and the default in-memory + * span implementation. + * + * @since 2.0.0 + */ + + + + +const evaluate = "~effect/Effect/evaluate"; +/** + * 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" + * ``` + * + * @category constants + * @since 4.0.0 + */ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** + * Context service containing the `Span` or `ExternalSpan` to use as the parent + * of newly-created child spans. + * + * **Example** (Accessing the parent span) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the parent span from the context + * const program = Effect.gen(function*() { + * const parentSpan = yield* Effect.service(Tracer.ParentSpan) + * return parentSpan.spanId + * }) + * + * const parent = Tracer.externalSpan({ spanId: "span-123", traceId: "trace-456" }) + * await Effect.runPromise(Effect.provideService(program, Tracer.ParentSpan, parent)) // => "span-123" + * ``` + * + * @category services + * @since 2.0.0 + */ +class ParentSpan extends /*#__PURE__*/_Context_js__rspack_import_0/* .Service */.kl()(ParentSpanKey, { + fiberCached: true +}) {} +/** + * Creates a `Tracer` value from a tracer implementation object. + * + * **When to use** + * + * Use to create a custom tracing backend value that Effect can use when + * creating spans. + * + * **Details** + * + * `make` returns the supplied implementation object unchanged. The object must + * satisfy the `Tracer` contract, including a `span` method that returns a + * `Span`. + * + * @see {@link Span} for the span values returned by tracer implementations + * + * @category constructors + * @since 2.0.0 + */ +const make = options => options; +/** + * Creates an `ExternalSpan` from trace and span identifiers, defaulting + * `sampled` to `true` and annotations to an empty context when they are not + * provided. + * + * **Example** (Creating an external span) + * + * ```ts import.meta.vitest + * import { Effect, Option, Tracer } from "effect" + * + * // Create an external span from another tracing system + * const span = Tracer.externalSpan({ + * spanId: "span-abc-123", + * traceId: "trace-xyz-789", + * sampled: true + * }) + * + * // Use the external span as a parent + * const program = Effect.succeed("Hello").pipe( + * Effect.withSpan("child-operation", { parent: span }) + * ) + * + * const spans: Array = [] + * const tracer = Tracer.make({ + * span(options) { + * const span = new Tracer.NativeSpan(options) + * spans.push(span) + * return span + * } + * }) + * const value = await Effect.runPromise(Effect.provideService(program, Tracer.Tracer, tracer)) + * + * value // => "Hello" + * spans.map((span) => Option.getOrUndefined(span.parent)?.spanId) // => ["span-abc-123"] + * ``` + * + * @category constructors + * @since 2.0.0 + */ +const externalSpan = options => ({ + _tag: "ExternalSpan", + spanId: options.spanId, + traceId: options.traceId, + sampled: options.sampled ?? true, + annotations: options.annotations ?? Context.empty() +}); +/** + * Context reference for disabling trace propagation. + * + * **When to use** + * + * Use to prevent spans in a scope from propagating tracing context. + * + * **Details** + * + * When enabled on fiber or span annotations, new spans are created as + * non-propagating no-op spans and disabled spans are skipped when deriving a + * parent span. + * + * **Example** (Disabling span propagation) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Disable span propagation for a specific effect + * const program = Tracer.DisablePropagation.pipe( + * Effect.provideService(Tracer.DisablePropagation, true) + * ) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 3.12.0 + */ +const DisablePropagation = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/DisablePropagation", { + defaultValue: _Function_js__rspack_import_1/* .constFalse */.f4 +}); +/** + * Context reference for controlling the current trace level for dynamic filtering. + * + * **When to use** + * + * Use to set the default trace level for spans in a scope when span options do + * not provide `level`. + * + * **Details** + * + * The default value is `"Info"`. Span creation uses `options.level ?? + * CurrentTraceLevel` before applying `MinimumTraceLevel`. + * + * @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled + * + * @category services + * @since 4.0.0 + */ +const CurrentTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/CurrentTraceLevel", { + defaultValue: () => "Info" +}); +/** + * Context reference for setting the minimum trace level threshold. Spans and their + * descendants below this level will have their sampling decision forced to + * false, preventing them from being exported. + * + * **When to use** + * + * Use to set the trace-level threshold that controls whether spans are sampled + * by default. + * + * **Details** + * + * The default value is `"All"`. Span creation compares the span level from + * `options.level ?? CurrentTraceLevel` against this threshold. + * + * **Gotchas** + * + * Explicit `options.sampled` bypasses threshold computation. + * + * @see {@link CurrentTraceLevel} for the default span level used when options do not specify one + * + * @category services + * @since 4.0.0 + */ +const MinimumTraceLevel = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or("effect/Tracer/MinimumTraceLevel", { + defaultValue: () => "All" +}); +/** + * 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. + * + * @category constants + * @since 4.0.0 + */ +const TracerKey = "effect/Tracer"; +/** + * Context reference for the active tracer service. By default it uses the + * native tracer, which creates `NativeSpan` instances. + * + * **Example** (Accessing the current tracer) + * + * ```ts import.meta.vitest + * import { Effect, Tracer } from "effect" + * + * // Access the current tracer from the context + * const program = Effect.gen(function*() { + * const tracer = yield* Effect.service(Tracer.Tracer) + * // Or use the built-in tracer effect + * const tracerFromAccessor = yield* Effect.tracer + * return tracer === tracerFromAccessor + * }) + * + * await Effect.runPromise(program) // => true + * ``` + * + * @category services + * @since 2.0.0 + */ +const Tracer = /*#__PURE__*/_Context_js__rspack_import_0/* .Reference */.Or(TracerKey, { + fiberCached: true, + defaultValue: () => make({ + span: options => new NativeSpan(options) + }) +}); +/** + * Default in-memory `Span` implementation used by the native tracer. It + * generates span and trace identifiers, stores attributes, events, and links, + * and records `Started` or `Ended` status. + * + * **Details** + * + * The constructor initializes the span with `Started` status, inherits the + * parent trace id or generates a new one, and always generates a new span id. + * Attributes, events, links, and status are then mutated through `Span` methods. + * + * @see {@link Span} for the interface implemented by native spans + * + * @category models + * @since 4.0.0 + */ +class NativeSpan { + _tag = "Span"; + spanId; + traceId = "native"; + sampled; + name; + parent; + annotations; + links; + startTime; + kind; + status; + attributes; + events = []; + constructor(options) { + this.name = options.name; + this.parent = options.parent; + this.annotations = options.annotations; + this.links = options.links; + this.startTime = options.startTime; + this.kind = options.kind; + this.sampled = options.sampled; + this.status = { + _tag: "Started", + startTime: options.startTime + }; + this.attributes = new Map(); + this.traceId = _Option_js__rspack_import_2.getOrUndefined(options.parent)?.traceId ?? _Encoding_js__rspack_import_3/* .randomHex */.nw(32); + this.spanId = _Encoding_js__rspack_import_3/* .randomHex */.nw(16); + } + end(endTime, exit) { + this.status = { + _tag: "Ended", + endTime, + exit, + startTime: this.status.startTime + }; + } + attribute(key, value) { + this.attributes.set(key, value); + } + event(name, startTime, attributes) { + this.events.push([name, startTime, attributes ?? {}]); + } + addLinks(links) { + // oxlint-disable-next-line no-restricted-syntax + this.links.push(...links); + } +} +//# sourceMappingURL=Tracer.js.map +__webpack_require__.d(__webpack_exports__, { + Tv: () => (ParentSpan) +}, { + DW: DisablePropagation, + EW: MinimumTraceLevel, + RL: TracerKey, + WG: ParentSpanKey, + pX: CurrentTraceLevel, + sh: Tracer +}); + + +}, +"./node_modules/effect/dist/Utils.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * Yields its wrapped value exactly once through an `IterableIterator`. + * + * **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 `{ value: self, done: false }`. Every + * subsequent call returns `{ value: a, done: true }` where `a` is the argument + * passed to `next()`. `[Symbol.iterator]()` returns a **new** `SingleShotGen` + * wrapping the same value, so the outer type can be iterated multiple times. + * + * **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", done: false } + * + * gen.next(42) // => { value: 42, done: true } + * ``` + * + * @see {@link Gen} for the type-level signature that relies on `SingleShotGen` + * @category constructors + * @since 2.0.0 + */ +class SingleShotGen { + called = false; + self; + constructor(self) { + this.self = self; + } + /** + * 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) { + return this.called ? { + value: a, + done: true + } : (this.called = true, { + value: this.self, + done: false + }); + } + /** + * Creates a fresh single-shot iterator over the stored value. + * + * **When to use** + * + * Use to iterate the wrapped value again without reusing the consumed + * iterator state. + * + * @since 2.0.0 + */ + [Symbol.iterator]() { + return new SingleShotGen(this.self); + } +} +// the probe is wrapped in a single function call (rather than module-level +// statements) so the whole selection is pure-annotated by the build and +// tree-shakable when `internalCall` is unused. +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { + [InternalTypeId]: body => { + return body(); + } + }; + const forced = { + [InternalTypeId]: body => { + try { + return body(); + } finally { + // + } + } + }; + const isNotOptimizedAway = standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true; + return isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/pickInternalCall(); +//# sourceMappingURL=Utils.js.map +__webpack_require__.d(__webpack_exports__, { + B: () => (SingleShotGen) +}, { + s: internalCall +}); + + +}, +"./node_modules/effect/dist/internal/array.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/** + * @since 2.0.0 + */ +/** @internal */ +const isArrayNonEmpty = self => self.length > 0; +//# sourceMappingURL=array.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + C: isArrayNonEmpty +}); + + +}, +"./node_modules/effect/dist/internal/core.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Equal_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Formatter_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Pipeable_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Utils_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _record_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); + + + + + + + + + +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: _Function_js__rspack_import_0/* .identity */.D_, + _E: _Function_js__rspack_import_0/* .identity */.D_, + _R: _Function_js__rspack_import_0/* .identity */.D_ +}; +/** @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 (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + }, + toJSON() { + return { + ...this + }; + }, + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } +}; +/** @internal */ +const StructuralProto = { + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .structureKeys */.uN(this, Object.keys(this)); + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + const selfKeys = Object.keys(this); + const thatKeys = Object.keys(that); + if (selfKeys.length !== thatKeys.length) return false; + for (let i = 0; i < selfKeys.length; i++) { + if (selfKeys[i] !== thatKeys[i] || !_Equal_js__rspack_import_5/* .equals */.aI(this[selfKeys[i]], that[selfKeys[i]])) { + return false; + } + } + return true; + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new _Utils_js__rspack_import_6/* .SingleShotGen */.B(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ...(args in this ? { + args: this[args] + } : undefined) + }; + } +}; +/** @internal */ +const isEffect = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, EffectTypeId); +/** @internal */ +const isExit = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, ExitTypeId); +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseTypeId); +/** @internal */ +const isCauseReason = self => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(self, CauseReasonTypeId); +/** @internal */ +class CauseImpl { + [CauseTypeId]; + reasons; + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toJSON() { + return { + _id: "Cause", + failures: this.reasons.map(f => f.toJSON()) + }; + } + toString() { + return `Cause(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.reasons)})`; + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toJSON(); + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => _Equal_js__rspack_import_5/* .equals */.aI(e, that.reasons[i])); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .array */.YO(this.reasons); + } +} +const annotationsMap = /*#__PURE__*/new WeakMap(); +/** @internal */ +class ReasonBase { + [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); + }); + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return (0,_Pipeable_js__rspack_import_1/* .pipeArguments */.tT)(this, arguments); + } + toString() { + return (0,_Formatter_js__rspack_import_2/* .format */.GP)(this); + } + [_Inspectable_js__rspack_import_3/* .NodeInspectSymbol */.FX]() { + return this.toString(); + } +} +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/new Map(); +/** @internal */ +class Fail extends ReasonBase { + error; + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isFailReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.error, that.error) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.error))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeFromReasons = reasons => new CauseImpl(reasons); +/** @internal */ +const causeEmpty = /*#__PURE__*/new CauseImpl([]); +/** @internal */ +const causeFail = error => new CauseImpl([new Fail(error)]); +/** @internal */ +class Die extends ReasonBase { + defect; + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isDieReason(that) && _Equal_js__rspack_import_5/* .equals */.aI(this.defect, that.defect) && _Equal_js__rspack_import_5/* .equals */.aI(this.annotations, that.annotations); + } + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(this._tag))(_Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .hash */.tW(this.defect))(_Hash_js__rspack_import_4/* .hash */.tW(this.annotations))); + } +} +/** @internal */ +const causeDie = defect => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/(0,_Function_js__rspack_import_0/* .dual */.XY)(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[evaluate] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = options => { + const Proto = makePrimitiveProto(options); + return function () { + const self = Object.create(Proto); + self[args] = options.single === false ? arguments : arguments[0]; + return self; + }; +}; +/** @internal */ +const makeExit = options => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${(0,_Formatter_js__rspack_import_2/* .format */.GP)(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [_Equal_js__rspack_import_5/* .symbol */.HR](that) { + return isExit(that) && that._tag === this._tag && _Equal_js__rspack_import_5/* .equals */.aI(this[args], that[args]); + }, + [_Hash_js__rspack_import_4/* .symbol */.HR]() { + return _Hash_js__rspack_import_4/* .combine */.kg(_Hash_js__rspack_import_4/* .string */.Yj(options.op), _Hash_js__rspack_import_4/* .hash */.tW(this[args])); + } + }; + return function (value) { + const self = Object.create(Proto); + self[args] = value; + return self; + }; +}; +/** @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.currentStackFrame) { + cause = causeAnnotate(cause, { + mapUnsafe: new Map([[StackTraceKey.key, fiber.currentStackFrame]]) + }); + annotated = true; + } + let cont = fiber.getCont(contE); + while (fiber.interruptible && fiber._interruptedCause && cont) { + cont = fiber.getCont(contE); + } + return cont ? cont[contE](cause, fiber, annotated ? undefined : 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 = /*#__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 + } : undefined); + if (args) { + _record_js__rspack_import_8/* .assignProperties */.z(this, args); + // @effect-diagnostics-next-line floatingEffect:off + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = tag => { + class Base extends Error { + _tag = tag; + } + ; + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const NoSuchElementErrorTypeId = "~effect/Cause/NoSuchElementError"; +/** @internal */ +const isNoSuchElementError = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, NoSuchElementErrorTypeId); +/** @internal */ +class NoSuchElementError extends /*#__PURE__*/TaggedError("NoSuchElementError") { + [NoSuchElementErrorTypeId] = NoSuchElementErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = u => (0,_Predicate_js__rspack_import_7/* .hasProperty */.i5)(u, DoneTypeId); +const DoneVoid = { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value: undefined +}; +/** @internal */ +const Done = value => { + if (value === undefined) return DoneVoid; + return { + [DoneTypeId]: DoneTypeId, + _tag: "Done", + value + }; +}; +const doneVoid = /*#__PURE__*/exitFail(DoneVoid); +/** @internal */ +const done = value => { + if (value === undefined) return doneVoid; + return exitFail(Done(value)); +}; +//# sourceMappingURL=core.js.map +__webpack_require__.d(__webpack_exports__, { + ET: () => (ReasonBase), + Xm: () => (NoSuchElementError), + dM: () => (Fail), + s0: () => (CauseImpl) +}, { + $L: isDone, + $n: EffectTypeId, + Aj: isCause, + B4: CauseReasonTypeId, + DH: causeEmpty, + Eh: causeAnnotate, + GN: Yield, + IH: ExitTypeId, + In: StructuralProto, + Iu: causeDie, + OE: causeFail, + PW: isNoSuchElementError, + PX: CauseTypeId, + QJ: InterruptorStackTrace, + R6: withFiber, + RS: Done, + Rk: exitFail, + Sc: contE, + Uf: makePrimitive, + V2: exitDie, + Vw: done, + Wg: isCauseReason, + Xb: isDieReason, + _3: evaluate, + a2: args, + b5: causeFromReasons, + b9: isExit, + cb: exitFailCause, + dO: constEmptyAnnotations, + ee: contA, + fU: PipeInspectableProto, + ik: isInterruptReason, + lC: isFailReason, + qB: NoSuchElementErrorTypeId, + q_: DoneTypeId, + rN: TaggedError, + u4: contAll, + xt: exitSucceed, + yj: makePrimitiveProto, + yw: isEffect, + z8: StackTraceKey +}); + + +}, +"./node_modules/effect/dist/internal/doNotation.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Function_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/Function.js"); + +/** @internal */ +const let_ = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => map(self, a => ({ + ...a, + [name]: f(a) +}))); +/** @internal */ +const bindTo = map => (0,_Function_js__rspack_import_0/* .dual */.XY)(2, (self, name) => map(self, a => ({ + [name]: a +}))); +/** @internal */ +const bind = (map, flatMap) => (0,_Function_js__rspack_import_0/* .dual */.XY)(3, (self, name, f) => flatMap(self, a => map(f(a), b => ({ + ...a, + [name]: b +})))); +//# sourceMappingURL=doNotation.js.map +__webpack_require__.d(__webpack_exports__, { +}, { + Jr: bindTo, + oI: bind, + zM: let_ +}); + + +}, +"./node_modules/effect/dist/internal/effect.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +/* import */ var _Array_js__rspack_import_7 = __webpack_require__("./node_modules/effect/dist/Array.js"); +/* import */ var _Context_js__rspack_import_5 = __webpack_require__("./node_modules/effect/dist/Context.js"); +/* import */ var _Duration_js__rspack_import_20 = __webpack_require__("./node_modules/effect/dist/Duration.js"); +/* import */ var _Equal_js__rspack_import_1 = __webpack_require__("./node_modules/effect/dist/Equal.js"); +/* import */ var _Filter_js__rspack_import_4 = __webpack_require__("./node_modules/effect/dist/Filter.js"); +/* import */ var _Formatter_js__rspack_import_9 = __webpack_require__("./node_modules/effect/dist/Formatter.js"); +/* import */ var _Function_js__rspack_import_6 = __webpack_require__("./node_modules/effect/dist/Function.js"); +/* import */ var _Hash_js__rspack_import_2 = __webpack_require__("./node_modules/effect/dist/Hash.js"); +/* import */ var _Inspectable_js__rspack_import_25 = __webpack_require__("./node_modules/effect/dist/Inspectable.js"); +/* import */ var _Iterable_js__rspack_import_23 = __webpack_require__("./node_modules/effect/dist/Iterable.js"); +/* import */ var _Option_js__rspack_import_17 = __webpack_require__("./node_modules/effect/dist/Option.js"); +/* import */ var _Order_js__rspack_import_24 = __webpack_require__("./node_modules/effect/dist/Order.js"); +/* import */ var _Pipeable_js__rspack_import_12 = __webpack_require__("./node_modules/effect/dist/Pipeable.js"); +/* import */ var _Predicate_js__rspack_import_11 = __webpack_require__("./node_modules/effect/dist/Predicate.js"); +/* import */ var _Redactable_js__rspack_import_10 = __webpack_require__("./node_modules/effect/dist/Redactable.js"); +/* import */ var _Result_js__rspack_import_3 = __webpack_require__("./node_modules/effect/dist/Result.js"); +/* import */ var _Scheduler_js__rspack_import_13 = __webpack_require__("./node_modules/effect/dist/Scheduler.js"); +/* import */ var _Tracer_js__rspack_import_14 = __webpack_require__("./node_modules/effect/dist/Tracer.js"); +/* import */ var _Utils_js__rspack_import_18 = __webpack_require__("./node_modules/effect/dist/Utils.js"); +/* import */ var _core_js__rspack_import_0 = __webpack_require__("./node_modules/effect/dist/internal/core.js"); +/* import */ var _doNotation_js__rspack_import_22 = __webpack_require__("./node_modules/effect/dist/internal/doNotation.js"); +/* import */ var _metric_js__rspack_import_16 = __webpack_require__("./node_modules/effect/dist/internal/metric.js"); +/* import */ var _record_js__rspack_import_21 = __webpack_require__("./node_modules/effect/dist/internal/record.js"); +/* import */ var _references_js__rspack_import_15 = __webpack_require__("./node_modules/effect/dist/internal/references.js"); +/* import */ var _stackTraceLimit_js__rspack_import_8 = __webpack_require__("./node_modules/effect/dist/internal/stackTraceLimit.js"); +/* import */ var _tracer_js__rspack_import_19 = __webpack_require__("./node_modules/effect/dist/internal/tracer.js"); + + + + + + + + + + + + + + + + + + + + + + + + + + +// ---------------------------------------------------------------------------- +// Cause +// ---------------------------------------------------------------------------- +/** @internal */ +class Interrupt extends _core_js__rspack_import_0/* .ReasonBase */.ET { + fiberId; + constructor(fiberId, annotations = _core_js__rspack_import_0/* .constEmptyAnnotations */.dO) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [_Equal_js__rspack_import_1/* .symbol */.HR](that) { + return (0,_core_js__rspack_import_0/* .isInterruptReason */.ik)(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [_Hash_js__rspack_import_2/* .symbol */.HR]() { + return _Hash_js__rspack_import_2/* .combine */.kg(_Hash_js__rspack_import_2/* .string */.Yj(`${this._tag}:${this.fiberId}`))(_Hash_js__rspack_import_2/* .random */.yT(this.annotations)); + } +} +/** @internal */ +const makeInterruptReason = fiberId => new Interrupt(fiberId); +/** @internal */ +const causeInterrupt = fiberId => new _core_js__rspack_import_0/* .CauseImpl */.s0([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = self => self.reasons.some(_core_js__rspack_import_0/* .isFailReason */.lC); +/** @internal */ +const findFail = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findError = self => { + for (let i = 0; i < self.reasons.length; i++) { + const reason = self.reasons[i]; + if (reason._tag === "Fail") { + return _Result_js__rspack_import_3/* .succeed */.Py(reason.error); + } + } + return _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findErrorOption = /*#__PURE__*/_Filter_js__rspack_import_4/* .toOption */.zL(findError); +/** @internal */ +const hasDies = self => self.reasons.some(_core_js__rspack_import_0/* .isDieReason */.Xb); +/** @internal */ +const findDie = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const findDefect = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isDieReason */.Xb); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason.defect) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const hasInterrupts = self => self.reasons.some(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const findInterrupt = self => { + const reason = self.reasons.find(_core_js__rspack_import_0/* .isInterruptReason */.ik); + return reason ? _Result_js__rspack_import_3/* .succeed */.Py(reason) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeFilterInterruptors = self => { + let interruptors; + for (let i = 0; i < self.reasons.length; i++) { + const f = self.reasons[i]; + if (f._tag !== "Interrupt") continue; + interruptors ??= new Set(); + if (f.fiberId !== undefined) { + interruptors.add(f.fiberId); + } + } + return interruptors ? _Result_js__rspack_import_3/* .succeed */.Py(interruptors) : _Result_js__rspack_import_3/* .fail */.fJ(self); +}; +/** @internal */ +const causeInterruptors = self => { + const result = causeFilterInterruptors(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? emptySet : result.success; +}; +const emptySet = /*#__PURE__*/new Set(); +/** @internal */ +const hasInterruptsOnly = self => self.reasons.length > 0 && self.reasons.every(_core_js__rspack_import_0/* .isInterruptReason */.ik); +/** @internal */ +const reasonAnnotations = self => _Context_js__rspack_import_5/* .makeUnsafe */.LZ(self.annotations); +/** @internal */ +const causeAnnotations = self => { + const map = new Map(); + for (const f of self.reasons) { + if (f.annotations.size > 0) { + for (const [key, value] of f.annotations) { + map.set(key, value); + } + } + } + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(map); +}; +/** @internal */ +const causeCombine = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, that) => { + if (self.reasons.length === 0) { + return that; + } else if (that.reasons.length === 0) { + return self; + } + const newCause = new _core_js__rspack_import_0/* .CauseImpl */.s0(_Array_js__rspack_import_7/* .union */.KC(self.reasons, that.reasons)); + return _Equal_js__rspack_import_1/* .equals */.aI(self, newCause) ? self : newCause; +}); +/** @internal */ +const causeMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + let hasFail = false; + const failures = self.reasons.map(failure => { + if ((0,_core_js__rspack_import_0/* .isFailReason */.lC)(failure)) { + hasFail = true; + return new _core_js__rspack_import_0/* .Fail */.dM(f(failure.error), failure.annotations); + } + return failure; + }); + return hasFail ? (0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures) : self; +}); +/** @internal */ +const causePartition = self => { + const obj = { + Fail: [], + Die: [], + Interrupt: [] + }; + for (let i = 0; i < self.reasons.length; i++) { + obj[self.reasons[i]._tag].push(self.reasons[i]); + } + return obj; +}; +/** @internal */ +const causeSquash = self => { + const partitioned = causePartition(self); + if (partitioned.Fail.length > 0) { + return partitioned.Fail[0].error; + } else if (partitioned.Die.length > 0) { + return partitioned.Die[0].defect; + } else if (partitioned.Interrupt.length > 0) { + return new globalThis.Error("All fibers interrupted without error"); + } + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const causePrettyErrors = (self, options) => { + const errors = []; + const interrupts = []; + if (self.reasons.length === 0) return errors; + const prevStackLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(1); + for (const failure of self.reasons) { + if (failure._tag === "Interrupt") { + interrupts.push(failure); + continue; + } + errors.push(causePrettyError(failure._tag === "Die" ? failure.defect : failure.error, failure.annotations, options)); + } + if (errors.length === 0) { + const cause = new Error("The fiber was interrupted by:"); + cause.name = "InterruptCause"; + cause.stack = interruptCauseStack(cause, interrupts); + const error = new globalThis.Error("All fibers interrupted without error", { + cause + }); + error.name = "InterruptError"; + error.stack = `${error.name}: ${error.message}`; + errors.push(causePrettyError(error, interrupts[0].annotations, options)); + } + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevStackLimit); + return errors; +}; +/** @internal */ +const causePrettyError = (original, annotations, options) => { + const kind = typeof original; + let error; + if (original && kind === "object") { + error = new globalThis.Error(causePrettyMessage(original), { + cause: original.cause ? causePrettyError(original.cause) : undefined + }); + if (typeof original.name === "string") { + error.name = original.name; + } + if (typeof original.stack === "string") { + error.stack = cleanErrorStack(original.stack, error, annotations); + } else { + const stack = `${error.name}: ${error.message}`; + error.stack = annotations ? addStackAnnotations(stack, annotations) : stack; + } + if (options?.includeCauseInStack) { + error.stack = renderPrettyError(error); + } + for (const key of Object.keys(original)) { + if (!(key in error)) { + ; + error[key] = original[key]; + } + } + } else { + error = new globalThis.Error(!original ? `Unknown error: ${original}` : kind === "string" ? original : (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(original)); + } + return error; +}; +const causePrettyMessage = u => { + if (typeof u.message === "string") { + return u.message; + } else if (typeof u.toString === "function" && u.toString !== Object.prototype.toString && u.toString !== Array.prototype.toString) { + try { + return u.toString(); + } catch { + // something's off, rollback to json + } + } + return (0,_Formatter_js__rspack_import_9/* .formatJson */.IB)(u); +}; +const locationRegExp = /\((.*)\)/g; +const cleanErrorStack = (stack, error, annotations) => { + const message = `${error.name}: ${error.message}`; + const lines = (stack.startsWith(message) ? stack.slice(message.length) : stack).split("\n"); + const out = [message]; + for (let i = 1; i < lines.length; i++) { + if (/(?:Generator\.next|~effect\/Effect)/.test(lines[i])) { + break; + } + out.push(lines[i]); + } + return annotations ? addStackAnnotations(out.join("\n"), annotations) : out.join("\n"); +}; +const addStackAnnotations = (stack, annotations) => { + const frame = annotations?.get(_core_js__rspack_import_0/* .StackTraceKey.key */.z8.key); + if (frame) { + stack = `${stack}\n${currentStackTrace(frame)}`; + } + return stack; +}; +const interruptCauseStack = (error, interrupts) => { + const out = [`${error.name}: ${error.message}`]; + for (const current of interrupts) { + const fiberId = current.fiberId !== undefined ? `#${current.fiberId}` : "unknown"; + const frame = current.annotations.get(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key); + out.push(` at fiber (${fiberId})`); + if (frame) out.push(currentStackTrace(frame)); + } + return out.join("\n"); +}; +const currentStackTrace = frame => { + const out = []; + let current = frame; + let i = 0; + while (current && i < 10) { + const stack = current.stack(); + if (stack) { + const locationMatchAll = stack.matchAll(locationRegExp); + let match = false; + for (const [, location] of locationMatchAll) { + match = true; + out.push(` at ${current.name} (${location})`); + } + if (!match) { + out.push(` at ${current.name} (${stack.replace(/^at /, "")})`); + } + } else { + out.push(` at ${current.name}`); + } + current = current.parent; + i++; + } + return out.join("\n"); +}; +/** @internal */ +const causePretty = cause => causePrettyErrors(cause).map(renderPrettyError).join("\n"); +const renderPrettyError = e => e.cause ? `${e.stack} {\n${renderErrorCause(e.cause, " ")}\n}` : e.stack; +const renderErrorCause = (cause, prefix) => { + const lines = cause.stack.split("\n"); + let stack = `${prefix}[cause]: ${lines[0]}`; + for (let i = 1, len = lines.length; i < len; i++) { + stack += `\n${prefix}${lines[i]}`; + } + if (cause.cause) { + stack += ` {\n${renderErrorCause(cause.cause, `${prefix} `)}\n${prefix}}`; + } + return stack; +}; +// ---------------------------------------------------------------------------- +// Fiber +// ---------------------------------------------------------------------------- +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: _Function_js__rspack_import_6/* .identity */.D_, + _E: _Function_js__rspack_import_6/* .identity */.D_ +}; +const fiberIdStore = { + id: 0 +}; +/** @internal */ +const getCurrentFiber = () => globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; +/** @internal */ +class FiberImpl { + constructor(context, interruptible = true) { + this[FiberTypeId] = fiberVariance; + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = []; + this._exit = undefined; + this._children = undefined; + this._interruptedCause = undefined; + this._yielded = undefined; + this._running = false; + this._deferredInterrupt = false; + this.runtimeMetrics?.recordFiberStart(this.context); + } + [FiberTypeId]; + id; + interruptible; + currentOpCount; + _stack; + _observers; + _exit; + _children; + _interruptedCause; + _yielded; + _running; + _deferredInterrupt; + // set in setContext + context; + currentScheduler; + currentTracerContext; + currentSpan; + currentLogLevel; + minimumLogLevel; + currentStackFrame; + runtimeMetrics; + maxOpsBeforeYield; + currentPreventYield; + _dispatcher = undefined; + get currentDispatcher() { + return this._dispatcher ??= this.currentScheduler.makeDispatcher(); + } + getRef(ref) { + return _Context_js__rspack_import_5/* .get */.Jt(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return _Function_js__rspack_import_6/* .constVoid */.Yi; + } + this._observers.push(cb); + return () => { + if (this._exit) 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.currentStackFrame) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, _Context_js__rspack_import_5/* .make */.L8(_core_js__rspack_import_0/* .StackTraceKey */.z8, this.currentStackFrame)); + } + if (annotations) { + cause = (0,_core_js__rspack_import_0/* .causeAnnotate */.Eh)(cause, annotations); + } + this._interruptedCause = this._interruptedCause ? causeCombine(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._yielded !== undefined) { + const yielded = this._yielded; + this._yielded = undefined; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === _core_js__rspack_import_0/* .Yield */.GN) { + return; + } + // the interruptChildren middleware is added in Effect.forkChild, so it can be + // tree-shaken if not used + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== undefined) { + return this.evaluate(flatMap(interruptChildren, () => exit)); + } + this._exit = exit; + this.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + for (let i = 0; i < this._observers.length; i++) { + this._observers[i](exit); + } + this._observers.length = 0; + this._stack.length = 0; + this._children = undefined; + this.context = _Context_js__rspack_import_5/* .empty */.Ie(); + } + runLoop(effect) { + const prevFiber = globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL]; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + if (!yielding && !this.currentPreventYield && this.currentScheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = this.currentTracerContext ? this.currentTracerContext(current, this) : current[_core_js__rspack_import_0/* .evaluate */._3](this); + if (current === _core_js__rspack_import_0/* .Yield */.GN) { + const yielded = this._yielded; + if (_core_js__rspack_import_0/* .ExitTypeId */.IH in yielded) { + this._deferredInterrupt = false; + this._yielded = undefined; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = undefined; + yielded(); + continue; + } + return _core_js__rspack_import_0/* .Yield */.GN; + } + } + } catch (error) { + if (!(0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(current, _core_js__rspack_import_0/* .evaluate */._3)) { + return (0,_core_js__rspack_import_0/* .exitDie */.V2)(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + } + return this.runLoop((0,_core_js__rspack_import_0/* .exitDie */.V2)(error)); + } finally { + this._running = prevRunning; + globalThis[_Redactable_js__rspack_import_10/* .currentFiberTypeId */.fL] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return undefined; + const cont = op[_core_js__rspack_import_0/* .contAll */.u4] && op[_core_js__rspack_import_0/* .contAll */.u4](this); + if (cont) { + ; + cont[symbol] = cont; + return cont; + } + if (op[symbol]) return op; + } + } + yieldWith(value) { + this._yielded = value; + return _core_js__rspack_import_0/* .Yield */.GN; + } + children() { + return this._children ??= new Set(); + } + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + // Every key cached below opts in to Context caching, so contexts related + // only by non-caching adds cannot have changed any of them + if (previous !== undefined && _Context_js__rspack_import_5/* .hasSameCache */.Pf(previous, context)) return; + const scheduler = this.getRef(_Scheduler_js__rspack_import_13/* .Scheduler */._F); + if (scheduler !== this.currentScheduler) { + this.currentScheduler = scheduler; + this._dispatcher = undefined; + } + // The string-keyed lookups keep the Tracer key values (and the native + // tracer behind Tracer.Tracer's default) out of every bundle + this.currentSpan = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .ParentSpanKey */.WG); + this.currentLogLevel = this.getRef(_references_js__rspack_import_15/* .CurrentLogLevel */.Gl); + this.minimumLogLevel = this.getRef(_references_js__rspack_import_15/* .MinimumLogLevel */.zQ); + this.currentStackFrame = this.getRef(_references_js__rspack_import_15/* .CurrentStackFrame */.vA); + this.maxOpsBeforeYield = this.getRef(_Scheduler_js__rspack_import_13/* .MaxOpsBeforeYield */.Zm); + this.currentPreventYield = this.getRef(_Scheduler_js__rspack_import_13/* .PreventSchedulerYield */.hf); + this.runtimeMetrics = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _metric_js__rspack_import_16/* .FiberRuntimeMetricsKey */.F); + const currentTracer = _Context_js__rspack_import_5/* .getOrUndefinedUnsafe */.Ub(context, _Tracer_js__rspack_import_14/* .TracerKey */.RL); + this.currentTracerContext = currentTracer ? currentTracer["context"] : undefined; + } + get currentSpanLocal() { + return this.currentSpan?._tag === "Span" ? this.currentSpan : undefined; + } +} +const deferredInterruptCont = { + [_core_js__rspack_import_0/* .contA */.ee](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [_core_js__rspack_import_0/* .contE */.Sc](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const fiberMiddleware = { + interruptChildren: undefined +}; +const fiberStackAnnotations = fiber => { + if (!fiber.currentStackFrame) return undefined; + const annotations = new Map(); + annotations.set(_core_js__rspack_import_0/* .InterruptorStackTrace.key */.QJ.key, fiber.currentStackFrame); + return _Context_js__rspack_import_5/* .makeUnsafe */.LZ(annotations); +}; +const fiberInterruptChildren = fiber => { + if (fiber._children === undefined || fiber._children.size === 0) { + return undefined; + } + return fiberInterruptAll(fiber._children); +}; +/** @internal */ +const fiberAwait = self => { + const impl = self; + if (impl._exit) return succeed(impl._exit); + return callback(resume => { + if (impl._exit) return resume(succeed(impl._exit)); + return sync(self.addObserver(exit => resume(succeed(exit)))); + }); +}; +/** @internal */ +const fiberAwaitAll = self => callback(resume => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = undefined; + 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 fiberJoinAll = self => callback(resume => { + const fibers = Array.from(self); + if (fibers.length === 0) return resume(succeed(_Array_js__rspack_import_7/* .empty */.Ie())); + const out = new Array(fibers.length); + const cancels = _Array_js__rspack_import_7/* .empty */.Ie(); + let done = 0; + let failed = false; + for (let i = 0; i < fibers.length; i++) { + if (failed) break; + cancels.push(fibers[i].addObserver(exit => { + done++; + if (exit._tag === "Failure") { + failed = true; + cancels.forEach(cancel => cancel()); + return resume(exit); + } + out[i] = exit.value; + if (done === fibers.length) { + resume(succeed(out)); + } + })); + } + return sync(() => { + failed = true; + cancels.forEach(cancel => cancel()); + }); +}); +/** @internal */ +const fiberInterrupt = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fiberInterruptAs(self, fiber.id)); +/** @internal */ +const fiberInterruptAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(args[0], FiberTypeId), (self, fiberId, annotations) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + let ann = fiberStackAnnotations(parent); + ann = ann && annotations ? _Context_js__rspack_import_5/* .merge */.h1(ann, annotations) : ann ?? annotations; + self.interruptUnsafe(fiberId, ann); + return asVoid(fiberAwait(self)); +})); +/** @internal */ +const fiberInterruptAll = fibers => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const fiberInterruptAllAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (fibers, fiberId) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const annotations = fiberStackAnnotations(parent); + const fiberArr = _Array_js__rspack_import_7/* .empty */.Ie(); + for (const fiber of fibers) { + fiber.interruptUnsafe(fiberId, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +})); +/** @internal */ +const succeed = _core_js__rspack_import_0/* .exitSucceed */.xt; +/** @internal */ +const failCause = _core_js__rspack_import_0/* .exitFailCause */.cb; +/** @internal */ +const fail = _core_js__rspack_import_0/* .exitFail */.Rk; +/** @internal */ +const sync = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Sync", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const value = this[_core_js__rspack_import_0/* .args */.a2](); + const cont = fiber.getCont(_core_js__rspack_import_0/* .contA */.ee); + return cont ? cont[_core_js__rspack_import_0/* .contA */.ee](value, fiber) : fiber.yieldWith((0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Suspend", + [_core_js__rspack_import_0/* .evaluate */._3](_fiber) { + return this[_core_js__rspack_import_0/* .args */.a2](); + } +}); +/** @internal */ +const fromOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => args.length >= 2 || _Option_js__rspack_import_17.isOption(args[0]), (option, onNone) => _Option_js__rspack_import_17.isNone(option) ? fail(onNone ? onNone() : new _core_js__rspack_import_0/* .NoSuchElementError */.Xm("Effect.fromOption: Option.none")) : succeed(option.value)); +/** @internal */ +const fromResult = /*#__PURE__*/_Result_js__rspack_import_3/* .match */.YW({ + onFailure: fail, + onSuccess: succeed +}); +/** @internal */ +const fromNullishOr = value => value == null ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(value); +/** @internal */ +const yieldNowWith = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Yield", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this[_core_js__rspack_import_0/* .args */.a2] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/yieldNowWith(0); +/** @internal */ +const succeedSome = a => succeed(_Option_js__rspack_import_17.some(a)); +/** @internal */ +const succeedNone = /*#__PURE__*/succeed(/*#__PURE__*/_Option_js__rspack_import_17.none()); +/** @internal */ +const transposeOption = self => _Option_js__rspack_import_17.isNone(self) ? succeedNone : map(self.value, _Option_js__rspack_import_17.some); +/** @internal */ +const failCauseSync = evaluate => suspend(() => failCause((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate))); +/** @internal */ +const die = defect => (0,_core_js__rspack_import_0/* .exitDie */.V2)(defect); +/** @internal */ +const failSync = error => suspend(() => fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(error))); +/** @internal */ +const void_ = /*#__PURE__*/succeed(void 0); +/** @internal */ + +/** @internal */ +const try_ = options => { + const evaluate = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.try") : options.catch; + return suspend(() => { + try { + return succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(evaluate)); + } catch (err) { + return fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(err))); + } + }); +}; +/** @internal */ + +/** @internal */ +const promise = evaluate => callbackOptions(function (resume, signal) { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(signal)).then(a => resume(succeed(a)), e => resume(die(e))); +}, evaluate.length !== 0); +/** @internal */ +const tryPromise = options => { + const f = typeof options === "function" ? options : options.try; + const catcher = typeof options === "function" ? cause => new UnknownError(cause, "An error occurred in Effect.tryPromise") : options.catch; + return callbackOptions(function (resume, signal) { + const failWithCatch = cause => { + try { + resume(fail((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => catcher(cause)))); + } catch (err) { + resume(die(err)); + } + }; + try { + (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(signal)).then(a => resume(succeed(a)), failWithCatch); + } catch (err) { + failWithCatch(err); + } + }, f.length !== 0); +}; +/** @internal */ +const withFiberId = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.id)); +/** @internal */ +const fiber = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(succeed); +/** @internal */ +const fiberId = /*#__PURE__*/withFiberId(succeed); +const callbackOptions = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Async", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + const register = (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => this[_core_js__rspack_import_0/* .args */.a2][0].bind(fiber.currentScheduler)); + let resumed = false; + let yielded = false; + const controller = this[_core_js__rspack_import_0/* .args */.a2][1] ? new AbortController() : undefined; + const onCancel = register(effect => { + if (resumed) return; + resumed = true; + if (yielded) { + fiber.evaluate(effect); + } else { + yielded = effect; + } + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber._yielded = () => { + resumed = true; + }; + if (controller === undefined && onCancel === undefined) { + return _core_js__rspack_import_0/* .Yield */.GN; + } + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return _core_js__rspack_import_0/* .Yield */.GN; + } +}); +const asyncFinalizer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "AsyncFinalizer", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(this[_core_js__rspack_import_0/* .args */.a2](), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = register => callbackOptions(register, register.length >= 2); +/** @internal */ +const never = /*#__PURE__*/callback(_Function_js__rspack_import_6/* .constVoid */.Yi); +/** @internal */ +const gen = (...args) => suspend(() => fromIteratorUnsafe(args.length === 1 ? args[0]() : args[1].call(args[0].self))); +/** @internal */ +const fnUntraced = (body, ...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 fnStackCleaner = /*#__PURE__*/(0,_tracer_js__rspack_import_19/* .makeStackCleaner */.R)(2); +/** @internal */ +const fn = function () { + const nameFirst = typeof arguments[0] === "string"; + const name = nameFirst ? arguments[0] : "Effect.fn"; + const spanOptions = nameFirst ? arguments[1] : undefined; + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const defError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + if (nameFirst) { + return (body, ...pipeables) => makeFn(name, body, defError, pipeables, nameFirst, spanOptions); + } + return makeFn(name, arguments[0], defError, Array.prototype.slice.call(arguments, 1), nameFirst, spanOptions); +}; +const makeFn = (name, bodyOrOptions, defError, pipeables, addSpan, spanOptions) => { + const body = typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); + return defineFunctionLength(body.length, function (...args) { + let result = suspend(() => { + const iter = body.apply(this, arguments); + return (0,_core_js__rspack_import_0/* .isEffect */.yw)(iter) ? iter : fromIteratorUnsafe(iter); + }); + for (let i = 0; i < pipeables.length; i++) { + result = pipeables[i](result, ...args); + } + if (!(0,_core_js__rspack_import_0/* .isEffect */.yw)(result)) { + return result; + } + const prevLimit = (0,_stackTraceLimit_js__rspack_import_8/* .getStackTraceLimit */.jt)(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(2); + const callError = new globalThis.Error(); + (0,_stackTraceLimit_js__rspack_import_8/* .setStackTraceLimit */.ft)(prevLimit); + return updateService(addSpan ? useSpan(name, spanOptions, span => provideParentSpan(result, span)) : result, _references_js__rspack_import_15/* .CurrentStackFrame */.vA, prev => ({ + name, + stack: fnStackCleaner(() => callError.stack), + parent: { + name: `${name} (definition)`, + stack: fnStackCleaner(() => defError.stack), + parent: prev + } + })); + }); +}; +/** @internal */ +const fnUntracedEager = (body, ...pipeables) => defineFunctionLength(body.length, pipeables.length === 0 ? function () { + return fromIteratorEagerUnsafe(() => body.apply(this, arguments)); +} : function () { + let effect = fromIteratorEagerUnsafe(() => body.apply(this, arguments)); + for (const pipeable of pipeables) { + effect = pipeable(effect); + } + return effect; +}); +const fromIteratorEagerUnsafe = evaluate => { + try { + const iterator = evaluate(); + let value = undefined; + // Try to resolve synchronously in a loop + while (true) { + const state = iterator.next(value); + if (state.done) { + return succeed(state.value); + } + const primitive = state.value; + if (primitive && primitive._tag === "Success") { + value = primitive.value; + continue; + } else if (primitive && primitive._tag === "Failure") { + return state.value; + } else { + let isFirstExecution = true; + return suspend(() => { + if (isFirstExecution) { + isFirstExecution = false; + return flatMap(state.value, value => fromIteratorUnsafe(iterator, value)); + } else { + return suspend(() => fromIteratorUnsafe(evaluate())); + } + }); + } + } + } catch (error) { + return die(error); + } +}; +const fromIteratorUnsafe = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Iterator", + single: false, + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + const iter = this[_core_js__rspack_import_0/* .args */.a2][0]; + 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; + } + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + return this[_core_js__rspack_import_0/* .contA */.ee](this[_core_js__rspack_import_0/* .args */.a2][1], fiber); + } +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const as = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, value) => { + const b = succeed(value); + return flatMap(self, _ => b); +}); +/** @internal */ +const asSome = self => map(self, _Option_js__rspack_import_17.some); +/** @internal */ +const flip = self => matchEffect(self, { + onFailure: succeed, + onSuccess: fail +}); +/** @internal */ +const andThen = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => (0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)))); +/** @internal */ +const tap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => as((0,_core_js__rspack_import_0/* .isEffect */.yw)(f) ? f : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a)), a))); +/** @internal */ +const asVoid = self => flatMap(self, _ => exitVoid); +/** @internal */ +const sandbox = self => catchCause(self, fail); +/** @internal */ +const raceAll = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + const effects = _Array_js__rspack_import_7/* .fromIterable */.Ts(all); + const len = effects.length; + let doneCount = 0; + let done = false; + const fibers = new Set(); + const failures = []; + const onExit = (exit, fiber, i) => { + doneCount++; + if (exit._tag === "Failure") { + failures.push(...exit.cause.reasons); + if (doneCount >= len) { + resume(failCause((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures))); + } + return; + } + const isWinner = !done; + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index: i, + parentFiber: parent + }); + } + }; + for (let i = 0; i < len; i++) { + const fiber = forkUnsafe(parent, effects[i], true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + onExit(exit, fiber, i); + }); + if (done) break; + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const raceAllFirst = (all, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => callback(resume => { + let done = false; + const fibers = new Set(); + const onExit = exit => { + done = true; + resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit)); + }; + let i = 0; + for (const effect of all) { + if (done) break; + const index = i++; + const fiber = forkUnsafe(parent, effect, true, true, false); + fibers.add(fiber); + fiber.addObserver(exit => { + fibers.delete(fiber); + const isWinner = !done; + onExit(exit); + if (isWinner && options?.onWinner) { + options.onWinner({ + fiber, + index, + parentFiber: parent + }); + } + }); + } + return fiberInterruptAll(fibers); +})); +/** @internal */ +const race = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAll([self, that], options)); +/** @internal */ +const raceFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => raceAllFirst([self, that], options)); +/** @internal */ +const flatMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onSuccess = Object.create(OnSuccessProto); + onSuccess[_core_js__rspack_import_0/* .args */.a2] = self; + onSuccess[_core_js__rspack_import_0/* .contA */.ee] = f.length !== 1 ? a => f(a) : f; + return onSuccess; +}); +const OnSuccessProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccess", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCauseEffectEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? options.onSuccess(self.value) : options.onFailure(self.cause); + } + return matchCauseEffect(self, options); +}); +/** @internal */ +const effectIsExit = effect => _core_js__rspack_import_0/* .ExitTypeId */.IH in effect; +/** @internal */ +const flatMapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + return self._tag === "Success" ? f(self.value) : self; + } + return flatMap(self, f); +}); +// ---------------------------------------------------------------------------- +// mapping & sequencing +// ---------------------------------------------------------------------------- +/** @internal */ +const flatten = self => flatMap(self, _Function_js__rspack_import_6/* .identity */.D_); +/** @internal */ +const map = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => flatMap(self, a => succeed((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a))))); +/** @internal */ +const mapEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMap(self, f) : map(self, f)); +/** @internal */ +const mapErrorEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => effectIsExit(self) ? exitMapError(self, f) : mapError(self, f)); +/** @internal */ +const mapBothEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => effectIsExit(self) ? exitMapBoth(self, options) : mapBoth(self, options)); +/** @internal */ +const catchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return f(error.success); + } + return catch_(self, f); +}); +// ---------------------------------------------------------------------------- +// Exit +// ---------------------------------------------------------------------------- +/** @internal */ +const exitInterrupt = fiberId => (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(causeInterrupt(fiberId)); +/** @internal */ +const exitIsSuccess = self => self._tag === "Success"; +/** @internal */ +const exitFilterSuccess = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterValue = self => self._tag === "Success" ? _Result_js__rspack_import_3/* .succeed */.Py(self.value) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitIsFailure = self => self._tag === "Failure"; +/** @internal */ +const exitFilterFailure = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFilterCause = self => self._tag === "Failure" ? _Result_js__rspack_import_3/* .succeed */.Py(self.cause) : _Result_js__rspack_import_3/* .fail */.fJ(self); +/** @internal */ +const exitFindError = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findError); +/** @internal */ +const exitFindDefect = /*#__PURE__*/_Filter_js__rspack_import_4/* .composePassthrough */.Bh(exitFilterCause, findDefect); +/** @internal */ +const exitHasInterrupts = self => self._tag === "Failure" && hasInterrupts(self.cause); +/** @internal */ +const exitHasDies = self => self._tag === "Failure" && hasDies(self.cause); +/** @internal */ +const exitHasFails = self => self._tag === "Failure" && hasFails(self.cause); +/** @internal */ +const exitVoid = /*#__PURE__*/(0,_core_js__rspack_import_0/* .exitSucceed */.xt)(void 0); +/** @internal */ +const exitMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => self._tag === "Success" ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(f(self.value)) : self); +/** @internal */ +const exitMapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + if (self._tag === "Success") return self; + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(f(error.success)); +}); +/** @internal */ +const exitMapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitFail */.Rk)(options.onFailure(error.success)); +}); +/** @internal */ +const exitAs = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, b) => exitIsSuccess(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(b) : self); +/** @internal */ +const exitZipRight = /*#__PURE__*/(/* unused pure expression or super */ null && (dual(2, (self, that) => exitIsSuccess(self) ? that : self))); +/** @internal */ +const exitMatch = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => exitIsSuccess(self) ? options.onSuccess(self.value) : options.onFailure(self.cause)); +/** @internal */ +const exitAsVoid = /*#__PURE__*/exitAs(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 : (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(failures)); +}; +/** @internal */ +const exitGetSuccess = self => exitIsSuccess(self) ? _Option_js__rspack_import_17.some(self.value) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitGetCause = self => exitIsFailure(self) ? _Option_js__rspack_import_17.some(self.cause) : _Option_js__rspack_import_17.none(); +/** @internal */ +const exitFindErrorOption = self => { + const error = exitFindError(self); + return _Result_js__rspack_import_3/* .isFailure */.N6(error) ? _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(error.success); +}; +// ---------------------------------------------------------------------------- +// environment +// ---------------------------------------------------------------------------- +/** @internal */ +const service = service => service; +/** @internal */ +const serviceOption = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const serviceOptional = service => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => fromOption(_Context_js__rspack_import_5/* .getOption */.om(fiber.context, service))); +/** @internal */ +const updateContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + return onExitPrimitive(self, () => { + fiber.setContext(prevContext); + return undefined; + }); +})); +/** @internal */ +const updateService = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, f) => updateContext(self, s => { + const prev = _Context_js__rspack_import_5/* .getUnsafe */.fp(s, service); + const next = f(prev); + if (prev === next) return s; + return _Context_js__rspack_import_5/* .add */.WQ(s, service, next); +})); +/** @internal */ +const updateServiceScoped = (service, update, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const original = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + const updated = update(original); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, updated)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, service); + let next; + if (options?.reset === undefined) { + if (current !== updated) return void_; + next = original; + } else { + next = options.reset(original, updated, current); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, service, next)); + return void_; + }); +})); +/** @internal */ +const context = () => getContext; +const getContext = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.context)); +/** @internal */ +const contextWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.context)); +/** @internal */ +const setContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => updateContext(self, (0,_Function_js__rspack_import_6/* .constant */.dY)(context))); +/** @internal */ +const provideContext = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, _Context_js__rspack_import_5/* .merge */.h1(context)); +}); +/** @internal */ +const provideService = function () { + if (arguments.length === 1) { + return (0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + } + return (0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, _Context_js__rspack_import_5/* .add */.WQ(service, implementation)); +/** @internal */ +const provideServiceEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, service, acquire) => flatMap(acquire, implementation => provideService(self, service, implementation))); +// ---------------------------------------------------------------------------- +// zipping +// ---------------------------------------------------------------------------- +/** @internal */ +const zip = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, options) => zipWith(self, that, (a, a2) => [a, a2], options)); +/** @internal */ +const zipWith = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[1]), (self, that, f, options) => options?.concurrent +// Use `all` exclusively for concurrent cases, as it introduces additional overhead due to the management of concurrency +? map(all([self, that], { + concurrency: 2 +}), ([a, a2]) => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))) : flatMap(self, a => map(that, a2 => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(a, a2))))); +// ---------------------------------------------------------------------------- +// filtering & conditionals +// ---------------------------------------------------------------------------- +/* @internal */ +const filterOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, orFailWith) => filterOrElse(self, predicate, orFailWith ? a => fail(orFailWith(a)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const when = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, condition) => flatMap(condition, pass => pass ? asSome(self) : succeedNone)); +// ---------------------------------------------------------------------------- +// repetition +// ---------------------------------------------------------------------------- +/** @internal */ +const replicate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, n) => Array.from({ + length: n +}, () => self)); +/** @internal */ +const replicateEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, n, options) => all(replicate(self, n), options)); +/** @internal */ +const forever = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => whileLoop({ + while: _Function_js__rspack_import_6/* .constTrue */.ue, + body: (0,_Function_js__rspack_import_6/* .constant */.dY)(options?.disableYield ? self : flatMap(self, _ => yieldNow)), + step: _Function_js__rspack_import_6/* .constVoid */.Yi +})); +// ---------------------------------------------------------------------------- +// error handling +// ---------------------------------------------------------------------------- +/** @internal */ +const catchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => { + const onFailure = Object.create(OnFailureProto); + onFailure[_core_js__rspack_import_0/* .args */.a2] = self; + onFailure[_core_js__rspack_import_0/* .contE */.Sc] = f.length !== 1 ? cause => f(cause) : f; + return onFailure; +}); +const OnFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const catchCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCause(self, cause => { + if (!predicate(cause)) { + return failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)); +})); +/** @internal */ +const catchCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const eb = filter(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(eb) ? failCause(eb.failure) : (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(eb.success, cause)); +})); +/** @internal */ +const catch_ = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findError, e => f(e))); +/** @internal */ +const catchNoSuchElement = self => matchEffect(self, { + onFailure: error => (0,_core_js__rspack_import_0/* .isNoSuchElementError */.PW)(error) ? succeedNone : fail(error), + onSuccess: succeedSome +}); +/** @internal */ +const catchDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCauseFilter(self, findDefect, f)); +/** @internal */ +const tapCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catchCause(self, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => catchCauseIf(self, predicate, cause => andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(cause)), failCause(cause)))); +/** @internal */ +const tapCauseFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => catchCause(self, cause => { + const result = filter(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return failCause(cause); + } + return andThen((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success, cause)), failCause(cause)); +})); +/** @internal */ +const tapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findError, e => f(e))); +/** @internal */ +const tapErrorTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, k, f) => { + const predicate = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return tapError(self, error => predicate(error) ? f(error) : void_); +}); +/** @internal */ +const tapDefect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => tapCauseFilter(self, findDefect, _ => f(_))); +/** @internal */ +const catchIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, predicate, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + if (!predicate(error.success)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(error.success)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(error.success)); +})); +/** @internal */ +const catchFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, f, orElse) => catchCause(self, cause => { + const error = findError(cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return failCause(error.failure); + const result = filter(error.success); + if (_Result_js__rspack_import_3/* .isFailure */.N6(result)) { + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(result.failure)) : failCause(cause); + } + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => f(result.success)); +})); +/** @internal */ +const catchTag = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, k, f, orElse) => { + const pred = Array.isArray(k) ? e => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && k.includes(e._tag) : (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(k); + return catchIf(self, pred, f, orElse); +}); +/** @internal */ +const catchTags = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, cases, orElse) => { + let keys; + return catchFilter(self, e => { + keys ??= Object.keys(cases); + return (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e["_tag"]) && keys.includes(e["_tag"]) ? _Result_js__rspack_import_3/* .succeed */.Py(e) : _Result_js__rspack_import_3/* .fail */.fJ(e); + }, e => (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[e["_tag"]](e)), orElse); +}); +/** @internal */ +const catchReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, reasonTag, f, orElse) => catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason"), e => { + const reason = e.reason; + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(reason, reasonTag)) return f(reason, e); + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); +})); +/** @internal */ +const catchReasons = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, errorTag, cases, orElse) => { + let keys; + return catchIf(self, e => (0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason") && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e.reason, "_tag") && (0,_Predicate_js__rspack_import_11/* .isString */.Kg)(e.reason._tag), e => { + const reason = e.reason; + keys ??= Object.keys(cases); + if (keys.includes(reason._tag)) { + return (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => cases[reason._tag](reason, e)); + } + return orElse ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => orElse(reason, e)) : fail(e); + }); +}); +/** @internal */ +const unwrapReason = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, errorTag) => catchFilter(self, e => { + if ((0,_Predicate_js__rspack_import_11/* .isTagged */.$J)(e, errorTag) && (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(e, "reason")) { + return _Result_js__rspack_import_3/* .succeed */.Py(e.reason); + } + return _Result_js__rspack_import_3/* .fail */.fJ(e); +}, fail)); +/** @internal */ +const mapError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, error => failSync(() => f(error)))); +/* @internal */ +const mapBoth = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: e => failSync(() => options.onFailure(e)), + onSuccess: a => sync(() => options.onSuccess(a)) +})); +/** @internal */ +const orDie = self => catch_(self, die); +/** @internal */ +const orElseSucceed = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => catch_(self, _ => sync(f))); +/** @internal */ +const firstSuccessOf = effects => suspend(() => { + const iterator = effects[Symbol.iterator](); + let state = iterator.next(); + if (state.done) { + return die(new Error("Received an empty collection of effects")); + } + function loop(current) { + const next = iterator.next(); + if (next.done) return current.value; + return catch_(current.value, _ => loop(next)); + } + return loop(state); +}); +/** @internal */ +const eventually = self => catch_(self, _ => flatMap(yieldNow, () => eventually(self))); +/** @internal */ +const ignore = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure(cause) { + const failure = findFail(cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(failure) ? failCause(failure.failure) : options.message === undefined ? logEffect(cause) : logEffect(options.message, cause); + }, + onSuccess: _ => void_ + }); +}); +/** @internal */ +const ignoreCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => { + if (!options?.log) { + return matchCauseEffect(self, { + onFailure: _ => void_, + onSuccess: _ => void_ + }); + } + const logEffect = logWithLevel(options.log === true ? undefined : options.log); + return matchCauseEffect(self, { + onFailure: cause => options.message === undefined ? logEffect(cause) : logEffect(options.message, cause), + onSuccess: _ => void_ + }); +}); +/** @internal */ +const option = self => match(self, { + onFailure: _Option_js__rspack_import_17.none, + onSuccess: _Option_js__rspack_import_17.some +}); +/** @internal */ +const result = self => matchEager(self, { + onFailure: _Result_js__rspack_import_3/* .fail */.fJ, + onSuccess: _Result_js__rspack_import_3/* .succeed */.Py +}); +// ---------------------------------------------------------------------------- +// pattern matching +// ---------------------------------------------------------------------------- +/** @internal */ +const matchCauseEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + const primitive = Object.create(OnSuccessAndFailureProto); + primitive[_core_js__rspack_import_0/* .args */.a2] = self; + primitive[_core_js__rspack_import_0/* .contA */.ee] = options.onSuccess.length !== 1 ? a => options.onSuccess(a) : options.onSuccess; + primitive[_core_js__rspack_import_0/* .contE */.Sc] = options.onFailure.length !== 1 ? cause => options.onFailure(cause) : options.onFailure; + return primitive; +}); +const OnSuccessAndFailureProto = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitiveProto */.yj)({ + op: "OnSuccessAndFailure", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + } +}); +/** @internal */ +const matchCause = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => sync(() => options.onFailure(cause)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchCauseEffect(self, { + onFailure: cause => { + const fail = cause.reasons.find(_core_js__rspack_import_0/* .isFailReason */.lC); + return fail ? (0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => options.onFailure(fail.error)) : failCause(cause); + }, + onSuccess: options.onSuccess +})); +/** @internal */ +const match = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => matchEffect(self, { + onFailure: error => sync(() => options.onFailure(error)), + onSuccess: value => sync(() => options.onSuccess(value)) +})); +/** @internal */ +const matchEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + const error = findError(self.cause); + if (_Result_js__rspack_import_3/* .isFailure */.N6(error)) return self; + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(error.success)); + } + return match(self, options); +}); +/** @internal */ +const matchCauseEager = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onSuccess(self.value)); + return (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(options.onFailure(self.cause)); + } + return matchCause(self, options); +}); +/** @internal */ +const exit = self => effectIsExit(self) ? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "Exit", + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2]; + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value)); + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + return succeed(exit ?? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause)); + } +}); +// ---------------------------------------------------------------------------- +// Condition checking +// ---------------------------------------------------------------------------- +/** @internal */ +const isFailure = /*#__PURE__*/matchEager({ + onFailure: () => true, + onSuccess: () => false +}); +/** @internal */ +const isSuccess = /*#__PURE__*/matchEager({ + onFailure: () => false, + onSuccess: () => true +}); +// ---------------------------------------------------------------------------- +// delays & timeouts +// ---------------------------------------------------------------------------- +/** @internal */ +const delay = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => andThen(sleep(duration), self)); +/** @internal */ +const timeoutOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, options) => raceFirst(self, flatMap(sleep(options.duration), options.orElse))); +/** @internal */ +const timeout = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => timeoutOrElse(self, { + duration, + orElse: () => fail(new TimeoutError()) +})); +/** @internal */ +const timeoutOption = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, duration) => raceFirst(asSome(self), as(sleep(duration), _Option_js__rspack_import_17.none()))); +/** @internal */ +const timed = self => clockWith(clock => { + const start = clock.monotonicTimeNanosUnsafe(); + return map(self, a => [_Duration_js__rspack_import_20/* .nanos */.cF(clock.monotonicTimeNanosUnsafe() - start), a]); +}); +// ---------------------------------------------------------------------------- +// resources & finalization +// ---------------------------------------------------------------------------- +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/_Context_js__rspack_import_5/* .Service */.kl("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => suspend(() => scopeCloseUnsafe(self, exit_) ?? void_); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + if (self.state._tag === "Closed") return; + const closed = { + _tag: "Closed", + exit: exit_ + }; + if (self.state._tag === "Empty") { + self.state = closed; + return; + } + const state = self.state; + self.state = closed; + if (state.finalizer !== undefined) { + return state.finalizer(exit_); + } + const finalizers = state.finalizers; + if (finalizers === undefined || finalizers.size === 0) { + return; + } else if (finalizers.size === 1) { + return finalizers.values().next().value(exit_); + } + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, cause => failCause(causeCombine(exit_.cause, cause))); +const scopeCloseFinalizers = /*#__PURE__*/fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers.values()); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const finalizer = arr[i]; + if (self.strategy === "sequential") { + exits.push(yield* exit(finalizer(exit_))); + } else { + fibers.push(forkUnsafe(parent, finalizer(exit_), true, true, "inherit")); + } + } + if (fibers.length > 0) { + exits = yield* fiberAwaitAll(fibers); + } + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeFork = (scope, finalizerStrategy) => sync(() => scopeForkUnsafe(scope, finalizerStrategy)); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const newScope = scopeMakeUnsafe(finalizerStrategy); + if (scope.state._tag === "Closed") { + newScope.state = scope.state; + return newScope; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, exit => scopeClose(newScope, exit)); + scopeAddFinalizerUnsafe(newScope, key, _ => sync(() => scopeRemoveFinalizerUnsafe(scope, key))); + return newScope; +}; +/** @internal */ +const scopeAddFinalizerExit = (scope, finalizer) => { + return suspend(() => { + if (scope.state._tag === "Closed") { + return finalizer(scope.state.exit); + } + scopeAddFinalizerUnsafe(scope, {}, finalizer); + return void_; + }); +}; +/** @internal */ +const scopeAddFinalizer = (scope, finalizer) => scopeAddFinalizerExit(scope, (0,_Function_js__rspack_import_6/* .constant */.dY)(finalizer)); +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") { + scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: undefined + }; + } else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== undefined) { + state.finalizers = new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = undefined; + state.finalizer = undefined; + state.finalizers.set(key, finalizer); + } else if (state.finalizers === undefined) { + state.finalizerKey = key; + state.finalizer = finalizer; + } else { + state.finalizers.set(key, finalizer); + } + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizerKey === key) { + state.finalizerKey = undefined; + state.finalizer = undefined; + } else if (state.finalizers !== undefined) { + state.finalizers.delete(key); + } + } +}; +/** @internal */ +const scopeFinalizerCountUnsafe = scope => scope.state._tag !== "Open" ? 0 : scope.state.finalizer !== undefined ? 1 : scope.state.finalizers?.size ?? 0; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy = "sequential") => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + state: constScopeEmpty +}); +const constScopeEmpty = { + _tag: "Empty" +}; +/** @internal */ +const scopeMake = finalizerStrategy => sync(() => scopeMakeUnsafe(finalizerStrategy)); +/** @internal */ +const scope = scopeTag; +/** @internal */ +const provideScope = /*#__PURE__*/provideService(scopeTag); +/** @internal */ +const scoped = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.context; + const scope = scopeMakeUnsafe(); + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, scopeTag, scope)); + return onExitPrimitive(self, exit => { + fiber.setContext(prev); + return scopeCloseUnsafe(scope, exit); + }); +}); +/** @internal */ +const scopeUse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => onExit(provideScope(self, scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_))); +/** @internal */ +const scopedWith = f => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), exit => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +/** @internal */ +const acquireRelease = (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)))))); +/** @internal */ +const addFinalizer = finalizer => flatMap(scope, scope => contextWith(context => scopeAddFinalizerExit(scope, exit => provideContext(finalizer(exit), context)))); +/** @internal */ +const onExitPrimitive = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "OnExit", + single: false, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2][0]; + }, + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + if (fiber.interruptible && this[_core_js__rspack_import_0/* .args */.a2][2] !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [_core_js__rspack_import_0/* .contA */.ee](value, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitSucceed */.xt)(value); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(eff, _ => exit) : exit; + }, + [_core_js__rspack_import_0/* .contE */.Sc](cause, _, exit) { + exit ??= (0,_core_js__rspack_import_0/* .exitFailCause */.cb)(cause); + const eff = this[_core_js__rspack_import_0/* .args */.a2][1](exit); + return eff ? flatMap(combineFinalizerCause(exit, eff), _ => exit) : exit; + } +}); +/** @internal */ +const onExit = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, onExitPrimitive); +/** @internal */ +const ensuring = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onExit(self, _ => finalizer)); +/** @internal */ +const onExitIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExit(self, exit => { + if (!predicate(exit)) { + return void_; + } + return f(exit); +})); +/** @internal */ +const onExitFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + const b = filter(exit); + return _Result_js__rspack_import_3/* .isFailure */.N6(b) ? void_ : f(b.success, exit); +})); +/** @internal */ +const onError = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, f) => onExitFilter(self, exitFilterCause, f)); +/** @internal */ +const onErrorIf = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, f) => onExitIf(self, exit => { + if (exit._tag !== "Failure") { + return false; + } + return predicate(exit.cause); +}, exit => f(exit.cause))); +/** @internal */ +const onErrorFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, f) => onExit(self, exit => { + if (exit._tag !== "Failure") { + return void_; + } + const result = filter(exit.cause); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? void_ : f(result.success, exit.cause); +})); +/** @internal */ +const onInterrupt = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, finalizer) => onErrorFilter(causeFilterInterruptors, finalizer)(self)); +/** @internal */ +const acquireUseRelease = (acquire, use, release) => uninterruptibleMask(restore => flatMap(acquire, a => onExitPrimitive(restore(use(a)), exit => release(a, exit), true))); +/** @internal */ +const acquireDisposable = acquire => acquireRelease(acquire, resource => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(resource, Symbol.asyncDispose) ? promise(() => resource[Symbol.asyncDispose]()) : sync(() => resource[Symbol.dispose]())); +// ---------------------------------------------------------------------------- +// Caching +// ---------------------------------------------------------------------------- +/** @internal */ +const cachedInvalidateWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, ttl) => sync(() => { + const ttlMillis = _Duration_js__rspack_import_20/* .toMillis */.kE(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(ttl)); + const isFinite = Number.isFinite(ttlMillis); + const latch = makeLatchUnsafe(false); + let expiresAt = 0; + let running = false; + let exit; + const wait = flatMap(latch.await, () => exit); + return [(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const clock = fiber.getRef(ClockRef); + const now = isFinite ? clock.currentTimeMillisUnsafe() : 0; + if (running || now < expiresAt) return exit ?? wait; + running = true; + latch.closeUnsafe(); + exit = undefined; + return onExit(self, exit_ => sync(() => { + running = false; + expiresAt = clock.currentTimeMillisUnsafe() + ttlMillis; + exit = exit_; + latch.openUnsafe(); + })); + }), sync(() => { + expiresAt = 0; + latch.closeUnsafe(); + exit = undefined; + })]; +})); +/** @internal */ +const cachedWithTTL = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, timeToLive) => map(cachedInvalidateWithTTL(self, timeToLive), tuple => tuple[0])); +/** @internal */ +const cached = self => cachedWithTTL(self, _Duration_js__rspack_import_20/* .infinity */.Tn); +// ---------------------------------------------------------------------------- +// interruption +// ---------------------------------------------------------------------------- +/** @internal */ +const interrupt = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => failCause(causeInterrupt(fiber.id))); +/** @internal */ +const uninterruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptible = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "SetInterruptible", + [_core_js__rspack_import_0/* .contAll */.u4](fiber) { + fiber.interruptible = this[_core_js__rspack_import_0/* .args */.a2]; + 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); +}; +/** @internal */ +const interruptible = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return self; + return setFiberInterruptible(fiber) ?? self; +}); +/** @internal */ +const uninterruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (!fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return f(interruptible); +}); +/** @internal */ +const interruptibleMask = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (fiber.interruptible) return f(_Function_js__rspack_import_6/* .identity */.D_); + const interrupted = setFiberInterruptible(fiber); + const effect = f(uninterruptible); + return interrupted ?? effect; +}); +/** @internal */ +const abortSignal = /*#__PURE__*/map(/*#__PURE__*/acquireRelease(/*#__PURE__*/sync(() => new AbortController()), controller => sync(() => controller.abort())), _ => _.signal); +// ======================================================================== +// collecting & elements +// ======================================================================== +/** @internal */ +const all = (arg, options) => { + if ((0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(arg)) { + return options?.mode === "result" ? forEach(arg, result, options) : forEach(arg, _Function_js__rspack_import_6/* .identity */.D_, options); + } else if (options?.discard) { + return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), _Function_js__rspack_import_6/* .identity */.D_, options); + } + return suspend(() => { + const out = {}; + return as(forEach(Object.entries(arg), ([key, effect]) => map(options?.mode === "result" ? result(effect) : effect, value => { + _record_js__rspack_import_21/* .assignProperty */.x(out, key, value); + }), { + discard: true, + concurrency: options?.concurrency + }), out); + }); +}; +/** @internal */ +const partition = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => map(forEach(elements, (a, i) => result(f(a, i)), options), results => _Array_js__rspack_import_7/* .partition */.jB(results, _Function_js__rspack_import_6/* .identity */.D_))); +/** @internal */ +const reduce = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (elements, zero, f) => { + const arr = _Array_js__rspack_import_7/* .fromIterable */.Ts(elements); + if (arr.length === 0) return sync(zero); + return suspend(() => { + let index = 0; + let state = zero(); + return map(whileLoop({ + while: () => index < arr.length, + body: () => f(state, arr[index], index), + step(next) { + state = next; + index++; + } + }), () => state); + }); +}); +/** @internal */ +const validate = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, f, options) => flatMap(partition(elements, f, { + concurrency: options?.concurrency +}), ([excluded, satisfying]) => { + if (_Array_js__rspack_import_7/* .isArrayNonEmpty */.CZ(excluded)) { + return fail(excluded); + } + return options?.discard ? void_ : succeed(satisfying); +})); +/** @internal */ +const findFirst = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, 0, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstLoop = (iterator, index, predicate, value) => flatMap(predicate(value, index), keep => { + if (keep) { + return succeed(_Option_js__rspack_import_17.some(value)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstLoop(iterator, index + 1, predicate, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const findFirstFilter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const iterator = elements[Symbol.iterator](); + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, 0, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +})); +const findFirstFilterLoop = (iterator, index, filter, value) => flatMap(filter(value, index), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + return succeed(_Option_js__rspack_import_17.some(result.success)); + } + const next = iterator.next(); + if (!next.done) { + return findFirstFilterLoop(iterator, index + 1, filter, next.value); + } + return succeed(_Option_js__rspack_import_17.none()); +}); +/** @internal */ +const whileLoop = /*#__PURE__*/(0,_core_js__rspack_import_0/* .makePrimitive */.Uf)({ + op: "While", + [_core_js__rspack_import_0/* .contA */.ee](value, fiber) { + this[_core_js__rspack_import_0/* .args */.a2].step(value); + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + }, + [_core_js__rspack_import_0/* .evaluate */._3](fiber) { + if (this[_core_js__rspack_import_0/* .args */.a2].while()) { + fiber._stack.push(this); + return this[_core_js__rspack_import_0/* .args */.a2].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrencyOption = options?.concurrency ?? 1; + const concurrency = concurrencyOption === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrencyOption); + if (concurrency === 1) { + return forEachSequential(iterable, f, options); + } + const items = _Array_js__rspack_import_7/* .fromIterable */.Ts(iterable); + let length = items.length; + if (length === 0) { + return options?.discard ? void_ : succeed([]); + } + const out = options?.discard ? undefined : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { + concurrency + }); + return eff ? as(eff, out) : succeed(out); +})); +/** @internal */ +const head = self => flatMap(self, elements => { + const result = elements[Symbol.iterator]().next(); + return result.done ? fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()) : succeed(result.value); +}); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? undefined : []; + 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); +}); +const iterateEagerImpl = options => { + const onItem = options.onItem; + const step = options.step; + const runSequential = (state, items, index, end) => { + for (; index < end; index++) { + const item = items[index]; + const effect = onItem(state, item, index); + if (!effectIsExit(effect)) { + return flatMap(exit(effect), itemExit => step(state, item, itemExit, index) ?? runSequential(state, items, index + 1, end) ?? void_); + } + const terminal = step(state, item, effect, index); + if (terminal) return terminal._tag === "Failure" ? terminal : undefined; + } + }; + return (state, items, opts) => { + let index = 0; + const end = opts?.end ?? items.length; + const concurrency = opts?.concurrency ?? 1; + if (concurrency === 1) { + return runSequential(state, items, 0, end); + } + const orderedStep = opts?.orderedStep === true; + let done = false; + let parentFiber; + let fibers; + let resume; + let interrupted = false; + let terminal; + let effect; + let nextIndex = index; + const exits = orderedStep ? new Array(end) : undefined; + const failDefect = error => { + const defect = (0,_core_js__rspack_import_0/* .exitDie */.V2)(error); + terminal = defect; + done = true; + interrupted = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => defect) : defect; + }; + const runStep = (item, exit, currentIndex) => { + if (!orderedStep) return step(state, item, exit, currentIndex); + if (terminal) return terminal; + exits[currentIndex] = exit; + while (nextIndex < end) { + const nextExit = exits[nextIndex]; + if (nextExit === undefined) return; + exits[nextIndex] = undefined; + const index = nextIndex++; + const result = step(state, items[index], nextExit, index); + if (result) return result; + } + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + // fast case (already an exit) + if (effectIsExit(eff)) { + terminal = runStep(item, eff, index); + if (terminal) break; + // We have an effect, so enter "async" mode + } else if (!parentFiber) { + return callback(cb => { + parentFiber = getCurrentFiber(); + fibers = 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; + interrupted = true; + return fibers ? fiberInterruptAll(fibers) : void_; + }); + }); + // Fork the effect with concurrency > 1 + } else { + // Clear the temporary effect from capturing the parentFiber + effect = undefined; + const fiber = forkUnsafe(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = runStep(item, fiber._exit, index); + if (terminal) break; + continue; + } + // Add the fiber to the Set + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver(exit => { + fibers.delete(fiber); + try { + if (terminal) { + if (!interrupted && exit._tag === "Failure") { + for (const reason of exit.cause.reasons) { + if (reason._tag === "Interrupt") continue;else if (terminal._tag === "Failure") { + ; + terminal.cause.reasons.push(reason); + } else { + terminal = (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)([reason])); + } + } + } + } else { + const result = runStep(item, exit, currentIndex); + if (result) { + terminal = result._tag === "Failure" ? (0,_core_js__rspack_import_0/* .exitFailCause */.cb)((0,_core_js__rspack_import_0/* .causeFromReasons */.b5)(result.cause.reasons.slice())) : 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)); + } + }); + // Check if we have reached the concurrency limit + 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(); + }; +}; +/** @internal */ +const iterateEager = () => iterateEagerImpl; +const forEachConcurrent = /*#__PURE__*/iterateEagerImpl({ + 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 filterOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, predicate, orElse) => flatMap(self, a => predicate(a) ? succeed(a) : orElse(a))); +/** @internal */ +const filterMapOrElse = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(3, (self, filter, orElse) => flatMap(self, a => { + const result = filter(a); + return _Result_js__rspack_import_3/* .isFailure */.N6(result) ? orElse(result.failure) : succeed(result.success); +})); +/* @internal */ +const filterMapOrFail = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, filter, orFailWith) => filterMapOrElse(self, filter, orFailWith ? x => fail(orFailWith(x)) : () => fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()))); +/** @internal */ +const filter = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, predicate, options) => suspend(() => { + const out = []; + return as(forEach(elements, (a, i) => { + const result = predicate(a, i); + if (typeof result === "boolean") { + if (result) out.push(a); + return void_; + } + return map(result, keep => { + if (keep) { + out.push(a); + } + }); + }, { + discard: true, + concurrency: options?.concurrency + }), out); +})); +/** @internal */ +const filterMap = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter) => suspend(() => { + const out = []; + for (const a of elements) { + const result = filter(a); + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + } + return succeed(out); +})); +/** @internal */ +const filterMapEffect = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_Predicate_js__rspack_import_11/* .isIterable */.xZ)(args[0]) && !(0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (elements, filter, options) => suspend(() => { + const out = []; + return as(forEach(elements, a => map(filter(a), result => { + if (_Result_js__rspack_import_3/* .isSuccess */.oJ(result)) { + out.push(result.success); + } + }), { + discard: true, + concurrency: options?.concurrency + }), out); +})); +// ---------------------------------------------------------------------------- +// do notation +// ---------------------------------------------------------------------------- +/** @internal */ +const Do = /*#__PURE__*/succeed({}); +/** @internal */ +const bindTo = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bindTo */.Jr(map); +/** @internal */ +const bind = /*#__PURE__*/_doNotation_js__rspack_import_22/* .bind */.oI(map, flatMap); +/** @internal */ +const let_ = /*#__PURE__*/_doNotation_js__rspack_import_22/* .let_ */.zM(map); +/** @internal */ + +// ---------------------------------------------------------------------------- +// fibers & forking +// ---------------------------------------------------------------------------- +/** @internal */ +const forkChild = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + interruptChildrenPatch(); + return succeed(forkUnsafe(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false)); +})); +/** @internal */ +const forkUnsafe = (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 (immediate) { + child.evaluate(effect); + } else { + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + if (!daemon && !child._exit) { + parentRuntime.children().add(child); + child.addObserver(() => parentRuntime._children.delete(child)); + } + return child; +}; +/** @internal */ +const forkDetach = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(forkUnsafe(fiber, self, options?.startImmediately, true, options?.uninterruptible)))); +/** @internal */ +const awaitAllChildren = self => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const initialChildren = fiber._children && new Set(fiber._children); + return onExit(self, _ => { + let children = fiber._children; + if (children === undefined || children.size === 0) { + return void_; + } else if (initialChildren) { + children = _Iterable_js__rspack_import_23/* .filter */.pb(children, child => !initialChildren.has(child)); + } + return asVoid(fiberAwaitAll(children)); + }); +}); +/** @internal */ +const forkIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, scope, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(parent => { + const fiber = forkUnsafe(parent, self, options?.startImmediately, true, options?.uninterruptible); + if (!fiber._exit) { + if (scope.state._tag !== "Closed") { + const key = {}; + const finalizer = () => withFiberId(interruptor => interruptor === fiber.id ? void_ : fiberInterrupt(fiber)); + scopeAddFinalizerUnsafe(scope, key, finalizer); + fiber.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + } else { + fiber.interruptUnsafe(parent.id, fiberStackAnnotations(parent)); + } + } + return succeed(fiber); +})); +/** @internal */ +const forkScoped = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, options) => flatMap(scope, scope => forkIn(self, scope, options))); +// ---------------------------------------------------------------------------- +// execution +// ---------------------------------------------------------------------------- +/** @internal */ +const runForkWith = context => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? _Context_js__rspack_import_5/* .add */.WQ(context, _Scheduler_js__rspack_import_13/* .Scheduler */._F, 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 fiberRunIn = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (self, scope) => { + if (self._exit) { + return self; + } else if (scope.state._tag === "Closed") { + self.interruptUnsafe(self.id); + return self; + } + const key = {}; + scopeAddFinalizerUnsafe(scope, key, () => fiberInterrupt(self)); + self.addObserver(() => scopeRemoveFinalizerUnsafe(scope, key)); + return self; +}); +/** @internal */ +const runFork = /*#__PURE__*/runForkWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runCallbackWith = context => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + if (options?.onExit) { + fiber.addObserver(options.onExit); + } + return interruptor => { + return fiber.interruptUnsafe(interruptor); + }; + }; +}; +/** @internal */ +const runCallback = /*#__PURE__*/runCallbackWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 runPromiseExit = /*#__PURE__*/runPromiseExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runPromiseWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @internal */ +const runSyncExitWith = context => { + const runFork = runForkWith(context); + return effect => { + if (effectIsExit(effect)) return effect; + const scheduler = new _Scheduler_js__rspack_import_13/* .MixedScheduler */.FG("sync"); + const fiber = runFork(effect, { + scheduler + }); + fiber._dispatcher?.flush(); + return fiber._exit ?? (0,_core_js__rspack_import_0/* .exitDie */.V2)(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncExit = /*#__PURE__*/runSyncExitWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +/** @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 = /*#__PURE__*/runSyncWith(/*#__PURE__*/_Context_js__rspack_import_5/* .empty */.Ie()); +const succeedTrue = /*#__PURE__*/succeed(true); +const succeedFalse = /*#__PURE__*/succeed(false); +class Latch { + waiters = []; + scheduled = undefined; + _isOpen; + constructor(isOpen) { + this._isOpen = isOpen; + } + scheduleUnsafe(fiber) { + if (this.waiters.length === 0) { + return succeedTrue; + } + if (this.scheduled === undefined) { + this.scheduled = this.waiters; + fiber.currentDispatcher.scheduleTask(this.flushScheduled, 0); + } else { + for (let i = 0; i < this.waiters.length; i++) { + this.scheduled.push(this.waiters[i]); + } + } + this.waiters = []; + return succeedTrue; + } + flushScheduled = () => { + if (this.scheduled === undefined) return; + const waiters = this.scheduled; + this.scheduled = undefined; + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + }; + flushWaiters() { + // swap both arrays out before any resume runs: a resumed waiter can + // reentrantly close the latch and register new waiters, which must not + // be drained by this flush + const waiters = this.waiters; + this.waiters = []; + this.flushScheduled(); + for (let i = 0; i < waiters.length; i++) { + waiters[i](exitVoid); + } + } + open = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + if (this._isOpen) return succeedFalse; + this._isOpen = true; + return this.scheduleUnsafe(fiber); + }); + release = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => this._isOpen ? succeedFalse : this.scheduleUnsafe(fiber)); + openUnsafe() { + if (this._isOpen) return false; + this._isOpen = true; + this.flushWaiters(); + return true; + } + await = /*#__PURE__*/callback(resume => { + if (this._isOpen) { + return resume(void_); + } + this.waiters.push(resume); + return sync(() => { + let index = this.waiters.indexOf(resume); + if (index !== -1) { + this.waiters.splice(index, 1); + } else if (this.scheduled !== undefined) { + index = this.scheduled.indexOf(resume); + if (index !== -1) { + this.scheduled.splice(index, 1); + } + } + }); + }); + closeUnsafe() { + if (!this._isOpen) return false; + this._isOpen = false; + return true; + } + close = /*#__PURE__*/sync(() => this.closeUnsafe()); + whenOpen = self => flatMap(this.await, () => self); + isOpen() { + return this._isOpen; + } +} +/** @internal */ +const makeLatchUnsafe = open => new Latch(open ?? false); +/** @internal */ +const makeLatch = open => sync(() => makeLatchUnsafe(open)); +// ---------------------------------------------------------------------------- +// Tracer +// ---------------------------------------------------------------------------- +/** @internal */ +const tracer = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh))); +/** @internal */ +const withTracer = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(2, (effect, tracer) => provideService(effect, _Tracer_js__rspack_import_14/* .Tracer */.sh, tracer)); +/** @internal */ +const withTracerEnabled = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerEnabled */.rf); +/** @internal */ +const withTracerTiming = /*#__PURE__*/provideService(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); +const bigint0 = /*#__PURE__*/BigInt(0); +const NoopSpanProto = { + _tag: "Span", + spanId: "noop", + traceId: "noop", + sampled: false, + status: { + _tag: "Ended", + startTime: bigint0, + endTime: bigint0, + exit: exitVoid + }, + attributes: /*#__PURE__*/new Map(), + links: [], + kind: "internal", + attribute() {}, + event() {}, + end() {}, + addLinks() {} +}; +/** @internal */ +const noopSpan = options => Object.assign(Object.create(NoopSpanProto), options); +const filterDisablePropagation = span => { + if (!span) return _Option_js__rspack_import_17.none(); + return _Context_js__rspack_import_5/* .get */.Jt(span.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW) ? span._tag === "Span" ? filterDisablePropagation(_Option_js__rspack_import_17.getOrUndefined(span.parent)) : _Option_js__rspack_import_17.none() : _Option_js__rspack_import_17.some(span); +}; +/** @internal */ +const makeSpanUnsafe = (fiber, name, options) => { + const disablePropagation = !fiber.getRef(_references_js__rspack_import_15/* .TracerEnabled */.rf) || options?.annotations && _Context_js__rspack_import_5/* .get */.Jt(options.annotations, _Tracer_js__rspack_import_14/* .DisablePropagation */.DW); + const parent = options?.parent !== undefined ? _Option_js__rspack_import_17.some(options.parent) : options?.root ? _Option_js__rspack_import_17.none() : filterDisablePropagation(fiber.currentSpan); + let span; + if (disablePropagation) { + span = noopSpan({ + name, + parent, + annotations: _Context_js__rspack_import_5/* .add */.WQ(options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), _Tracer_js__rspack_import_14/* .DisablePropagation */.DW, true) + }); + } else { + const tracer = fiber.getRef(_Tracer_js__rspack_import_14/* .Tracer */.sh); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + const annotationsFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanAnnotations */.ce); + const linksFromEnv = fiber.getRef(_references_js__rspack_import_15/* .TracerSpanLinks */.ls); + const level = options?.level ?? fiber.getRef(_Tracer_js__rspack_import_14/* .CurrentTraceLevel */.pX); + const links = options?.links !== undefined ? [...linksFromEnv, ...options.links] : linksFromEnv.length === 0 ? [] : linksFromEnv.slice(); + span = tracer.span({ + name, + parent, + annotations: options?.annotations ?? _Context_js__rspack_import_5/* .empty */.Ie(), + links, + startTime: timingEnabled ? clock.currentTimeNanosUnsafe() : BigInt(0), + kind: options?.kind ?? "internal", + root: options?.root ?? _Option_js__rspack_import_17.isNone(parent), + sampled: options?.sampled ?? (_Option_js__rspack_import_17.isSome(parent) && parent.value.sampled === false ? false : !isLogLevelGreaterThan(fiber.getRef(_Tracer_js__rspack_import_14/* .MinimumTraceLevel */.EW), level)) + }); + for (const key in annotationsFromEnv) { + span.attribute(key, annotationsFromEnv[key]); + } + if (options?.attributes !== undefined) { + for (const key in options.attributes) { + span.attribute(key, options.attributes[key]); + } + } + } + return span; +}; +/** @internal */ +const makeSpan = (name, options) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => succeed(makeSpanUnsafe(fiber, name, options))); +/** @internal */ +const makeSpanScoped = (name, options) => uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const scope = _Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag); + const span = makeSpanUnsafe(fiber, name, options ?? {}); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return as(scopeAddFinalizerExit(scope, exit => endSpan(span, exit, clock, timingEnabled)), span); +})); +/** @internal */ +const withSpanScoped = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(dataFirst ? arguments[2] : arguments[1]); + if (dataFirst) { + const self = arguments[0]; + return flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); + } + return self => flatMap(makeSpanScoped(name, options), span => withParentSpan(self, span, options)); +}; +const provideSpanStackFrame = (name, stack) => { + stack = typeof stack === "function" ? stack : _Function_js__rspack_import_6/* .constUndefined */.MN; + return updateService(_references_js__rspack_import_15/* .CurrentStackFrame */.vA, parent => ({ + name, + stack, + parent + })); +}; +/** @internal */ +const spanAnnotations = _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce; +/** @internal */ +const spanLinks = _references_js__rspack_import_15/* .TracerSpanLinks */.ls; +/** @internal */ +const linkSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (self, span, attributes = {}) => { + const spans = Array.isArray(span) ? span : [span]; + const links = spans.map(span => ({ + span, + attributes + })); + return updateService(self, _references_js__rspack_import_15/* .TracerSpanLinks */.ls, current => [...current, ...links]); +}); +/** @internal */ +const endSpan = (span, exit, clock, timingEnabled) => sync(() => { + if (span.status._tag === "Ended") return; + span.end(timingEnabled ? clock.currentTimeNanosUnsafe() : bigint0, exit); +}); +/** @internal */ +const useSpan = (name, ...args) => { + const options = args.length === 1 ? undefined : args[0]; + const evaluate = args[args.length - 1]; + return (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = makeSpanUnsafe(fiber, name, options); + const clock = fiber.getRef(ClockRef); + const timingEnabled = fiber.getRef(_references_js__rspack_import_15/* .TracerTimingEnabled */.nU); + return onExit((0,_Utils_js__rspack_import_18/* .internalCall */.s)(() => evaluate(span)), exit => endSpan(span, exit, clock, timingEnabled)); + }); +}; +const provideParentSpan = /*#__PURE__*/provideService(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +/** @internal */ +const withParentSpan = function () { + const dataFirst = (0,_core_js__rspack_import_0/* .isEffect */.yw)(arguments[0]); + const span = dataFirst ? arguments[1] : arguments[0]; + let options = dataFirst ? arguments[2] : arguments[1]; + let provideStackFrame = _Function_js__rspack_import_6/* .identity */.D_; + if (span._tag === "Span") { + options = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(options); + provideStackFrame = provideSpanStackFrame(span.name, options?.captureStackTrace); + } + if (dataFirst) { + return provideParentSpan(provideStackFrame(arguments[0]), span); + } + return self => provideParentSpan(provideStackFrame(self), span); +}; +/** @internal */ +const withSpan = function () { + const dataFirst = typeof arguments[0] !== "string"; + const name = dataFirst ? arguments[1] : arguments[0]; + const traceOptions = (0,_tracer_js__rspack_import_19/* .addSpanStackTrace */.Z)(arguments[2]); + if (dataFirst) { + const self = arguments[0]; + return useSpan(name, arguments[2], span => withParentSpan(self, span, traceOptions)); + } + const fnArg = typeof arguments[1] === "function" ? arguments[1] : undefined; + const options = fnArg ? undefined : arguments[1]; + return (self, ...args) => useSpan(name, fnArg ? fnArg(...args) : options, span => withParentSpan(self, span, traceOptions)); +}; +/** @internal */ +const annotateSpans = /*#__PURE__*/(0,_Function_js__rspack_import_6/* .dual */.XY)(args => (0,_core_js__rspack_import_0/* .isEffect */.yw)(args[0]), (effect, ...args) => updateService(effect, _references_js__rspack_import_15/* .TracerSpanAnnotations */.ce, annotations => { + const newAnnotations = args.length === 1 ? { + ...annotations, + ...args[0] + } : { + ...annotations + }; + if (args.length === 1) { + return newAnnotations; + } else { + _record_js__rspack_import_21/* .assignProperty */.x(newAnnotations, args[0], args[1]); + } + return newAnnotations; +})); +/** @internal */ +const annotateCurrentSpan = (...args) => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + if (span) { + if (args.length === 1) { + for (const [key, value] of Object.entries(args[0])) { + span.attribute(key, value); + } + } else { + span.attribute(args[0], args[1]); + } + } + return void_; +}); +/** @internal */ +const currentSpan = /*#__PURE__*/(0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const span = fiber.currentSpanLocal; + return span ? succeed(span) : fail(new _core_js__rspack_import_0/* .NoSuchElementError */.Xm()); +}); +/** @internal */ +const currentParentSpan = /*#__PURE__*/serviceOptional(_Tracer_js__rspack_import_14/* .ParentSpan */.Tv); +// ---------------------------------------------------------------------------- +// Clock +// ---------------------------------------------------------------------------- +/** @internal */ +const ClockRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Clock", { + defaultValue: () => new ClockImpl() +}); +const MAX_TIMER_MILLIS = 2 ** 31 - 1; +class ClockImpl { + currentTimeMillisUnsafe() { + return Date.now(); + } + currentTimeMillis = /*#__PURE__*/sync(() => this.currentTimeMillisUnsafe()); + currentTimeNanosUnsafe() { + return wallTimeNanos(); + } + currentTimeNanos = /*#__PURE__*/sync(() => this.currentTimeNanosUnsafe()); + monotonicTimeNanosUnsafe() { + return monotonicNowNanos(); + } + monotonicTimeNanos = /*#__PURE__*/sync(() => this.monotonicTimeNanosUnsafe()); + sleep(duration) { + return this.sleepMillis(_Duration_js__rspack_import_20/* .toMillis */.kE(duration)); + } + sleepMillis(millis) { + if (millis <= 0) return yieldNow;else if (!Number.isFinite(millis)) return never; + return callback(resume => { + const continuation = millis > MAX_TIMER_MILLIS ? this.sleepMillis(millis - MAX_TIMER_MILLIS) : void_; + const handle = setTimeout(() => resume(continuation), Math.min(millis, MAX_TIMER_MILLIS)); + return sync(() => clearTimeout(handle)); + }); + } +} +const nanosPerMilli = /*#__PURE__*/BigInt(1_000_000); +const monotonicNowNanos = /*#__PURE__*/function () { + const processHrtime = globalThis.process?.hrtime; + if (typeof processHrtime?.bigint === "function") { + return () => processHrtime.bigint(); + } + if (typeof performance !== "undefined" && typeof performance.now === "function") { + return () => BigInt(Math.round(performance.now() * 1_000_000)); + } + let previous = /*#__PURE__*/BigInt(0); + return () => { + const current = BigInt(Date.now()) * nanosPerMilli; + if (current > previous) { + previous = current; + } + return previous; + }; +}(); +const wallTimeNanos = /*#__PURE__*/function () { + const reanchorThresholdNanos = /*#__PURE__*/BigInt(1_000_000_000); + let origin; + return () => { + const monotonic = monotonicNowNanos(); + const wall = BigInt(Date.now()) * nanosPerMilli; + if (origin === undefined) { + origin = wall - monotonic; + } else { + const projected = origin + monotonic; + const skew = wall > projected ? wall - projected : projected - wall; + if (skew > reanchorThresholdNanos) { + origin = wall - monotonic; + } + } + return origin + monotonic; + }; +}(); +/** @internal */ +const clockWith = f => (0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => f(fiber.getRef(ClockRef))); +/** @internal */ +const sleep = duration => clockWith(clock => clock.sleep(_Duration_js__rspack_import_20/* .fromInputUnsafe */.bN(duration))); +/** @internal */ +const currentTimeMillis = /*#__PURE__*/(/* unused pure expression or super */ null && (clockWith(clock => clock.currentTimeMillis))); +/** @internal */ +const currentTimeNanos = /*#__PURE__*/(/* unused pure expression or super */ null && (clockWith(clock => clock.currentTimeNanos))); +/** @internal */ +const monotonicTimeNanos = /*#__PURE__*/(/* unused pure expression or super */ null && (clockWith(clock => clock.monotonicTimeNanos))); +// ---------------------------------------------------------------------------- +// Errors +// ---------------------------------------------------------------------------- +/** @internal */ +const TimeoutErrorTypeId = "~effect/Cause/TimeoutError"; +/** @internal */ +const isTimeoutError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, TimeoutErrorTypeId); +/** @internal */ +class TimeoutError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("TimeoutError") { + [TimeoutErrorTypeId] = TimeoutErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const IllegalArgumentErrorTypeId = "~effect/Cause/IllegalArgumentError"; +/** @internal */ +const isIllegalArgumentError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, IllegalArgumentErrorTypeId); +/** @internal */ +class IllegalArgumentError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("IllegalArgumentError") { + [IllegalArgumentErrorTypeId] = IllegalArgumentErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const ExceededCapacityErrorTypeId = "~effect/Cause/ExceededCapacityError"; +/** @internal */ +const isExceededCapacityError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, ExceededCapacityErrorTypeId); +/** @internal */ +class ExceededCapacityError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("ExceededCapacityError") { + [ExceededCapacityErrorTypeId] = ExceededCapacityErrorTypeId; + constructor(message) { + super({ + message + }); + } +} +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +const isAsyncFiberError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, AsyncFiberErrorTypeId); +/** @internal */ +class AsyncFiberError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("AsyncFiberError") { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +} +/** @internal */ +const UnknownErrorTypeId = "~effect/Cause/UnknownError"; +/** @internal */ +const isUnknownError = u => (0,_Predicate_js__rspack_import_11/* .hasProperty */.i5)(u, UnknownErrorTypeId); +/** @internal */ +class UnknownError extends /*#__PURE__*/(0,_core_js__rspack_import_0/* .TaggedError */.rN)("UnknownError") { + [UnknownErrorTypeId] = UnknownErrorTypeId; + constructor(cause, message) { + super({ + message, + cause + }); + } +} +// ---------------------------------------------------------------------------- +// Console +// ---------------------------------------------------------------------------- +/** @internal */ +const ConsoleRef = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Console/CurrentConsole", { + defaultValue: () => globalThis.console +}); +// ---------------------------------------------------------------------------- +// LogLevel +// ---------------------------------------------------------------------------- +/** @internal */ +const logLevelToOrder = level => { + switch (level) { + case "All": + return Number.MIN_SAFE_INTEGER; + case "Fatal": + return 50_000; + case "Error": + return 40_000; + case "Warn": + return 30_000; + case "Info": + return 20_000; + case "Debug": + return 10_000; + case "Trace": + return 0; + case "None": + return Number.MAX_SAFE_INTEGER; + } +}; +/** @internal */ +const LogLevelOrder = /*#__PURE__*/_Order_js__rspack_import_24/* .mapInput */.zQ(_Order_js__rspack_import_24/* .Number */.wN, logLevelToOrder); +/** @internal */ +const isLogLevelGreaterThan = /*#__PURE__*/_Order_js__rspack_import_24/* .isGreaterThan */.yJ(LogLevelOrder); +// ---------------------------------------------------------------------------- +// Logger +// ---------------------------------------------------------------------------- +/** @internal */ +const CurrentLoggers = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Loggers/CurrentLoggers", { + defaultValue: () => new Set([defaultLogger, tracerLogger]) +}); +/** @internal */ +const LogToStderr = /*#__PURE__*/_Context_js__rspack_import_5/* .Reference */.Or("effect/Logger/LogToStderr", { + defaultValue: _Function_js__rspack_import_6/* .constFalse */.f4 +}); +/** @internal */ +const annotateLogsScoped = function () { + const entries = typeof arguments[0] === "string" ? [[arguments[0], arguments[1]]] : Object.entries(arguments[0]); + return uninterruptible((0,_core_js__rspack_import_0/* .withFiber */.R6)(fiber => { + const prev = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...prev + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + _record_js__rspack_import_21/* .assignProperty */.x(next, key, value); + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return scopeAddFinalizerExit(_Context_js__rspack_import_5/* .getUnsafe */.fp(fiber.context, scopeTag), _ => { + const current = fiber.getRef(_references_js__rspack_import_15/* .CurrentLogAnnotations */.iL); + const next = { + ...current + }; + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + if (current[key] !== value) continue; + if (Object.hasOwn(prev, key)) { + _record_js__rspack_import_21/* .assignProperty */.x(next, key, prev[key]); + } else { + delete next[key]; + } + } + fiber.setContext(_Context_js__rspack_import_5/* .add */.WQ(fiber.context, _references_js__rspack_import_15/* .CurrentLogAnnotations */.iL, next)); + return void_; + }); + })); +}; +/** @internal */ +const LoggerTypeId = "~effect/Logger"; +const LoggerProto = { + [LoggerTypeId]: { + _Message: _Function_js__rspack_import_6/* .identity */.D_, + _Output: _Function_js__rspack_import_6/* .identity */.D_ + }, + pipe() { + return (0,_Pipeable_js__rspack_import_12/* .pipeArguments */.tT)(this, arguments); + } +}; +/** @internal */ +const loggerMake = log => { + const self = Object.create(LoggerProto); + self.log = log; + return self; +}; +/** + * Sanitize a given string by replacing spaces, equal signs, and double quotes + * with underscores. + * + * @internal + */ +const formatLabel = key => key.replace(/[\s="]/g, "_"); +/** + * Formats a log span into a `