A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
feat: Add power-automate plugin (#234)
Matt Townsendeec8eceb0888
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex f604543f1..493f81516 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -31,6 +31,10 @@{"name": "mobile-app","source": "./plugins/mobile-apps"+ },+ {+ "name": "power-automate",+ "source": "./plugins/power-automate"}]}diff --git a/README.md b/README.mdindex 87b784b48..8c8560dea 100644--- a/README.md+++ b/README.md@@ -50,6 +50,7 @@ If you prefer to install manually, run these commands inside a Claude Code or Gi/plugin install code-apps-preview@power-platform-skills/plugin install mobile-app@power-platform-skills/plugin install canvas-apps@power-platform-skills+ /plugin install power-automate@power-platform-skills```## Available Plugins@@ -90,6 +91,12 @@ Author Power Apps Canvas Apps using the Canvas Authoring MCP server.**Stack**: PA YAML (`.pa.yaml`) authored via `CanvasAuthoringMcpServer`, requires .NET 10 SDK+### [Power Automate](plugins/power-automate/README.md) (`plugins/power-automate`)++Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server.++**Stack**: Node.js 18+, Azure CLI (`az login`), self-contained MCP bundle+## Local DevelopmentTo develop and test plugins locally, follow these steps:@@ -104,6 +111,7 @@ To develop and test plugins locally, follow these steps:claude --plugin-dir /path/to/power-platform-skills/plugins/code-appsclaude --plugin-dir /path/to/power-platform-skills/plugins/mobile-appsclaude --plugin-dir /path/to/power-platform-skills/plugins/canvas-apps+ claude --plugin-dir /path/to/power-platform-skills/plugins/power-automate```## Running Without Interruptiondiff --git a/marketplace.json b/marketplace.jsonindex f604543f1..493f81516 100644--- a/marketplace.json+++ b/marketplace.json@@ -31,6 +31,10 @@{"name": "mobile-app","source": "./plugins/mobile-apps"+ },+ {+ "name": "power-automate",+ "source": "./plugins/power-automate"}]}diff --git a/plugins/power-automate/.claude-plugin/plugin.json b/plugins/power-automate/.claude-plugin/plugin.jsonnew file mode 100644index 000000000..9c37edf20--- /dev/null+++ b/plugins/power-automate/.claude-plugin/plugin.json@@ -0,0 +1,20 @@+{+ "name": "power-automate",+ "version": "2.0.0",+ "description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.",+ "author": {+ "name": "Microsoft",+ "url": "https://www.microsoft.com"+ },+ "homepage": "https://github.com/microsoft/power-platform-skills/",+ "repository": "https://github.com/microsoft/power-platform-skills/",+ "license": "MIT",+ "keywords": [+ "power-automate",+ "cloud-flows",+ "flows",+ "mcp",+ "power-platform",+ "flowagent"+ ]+}diff --git a/plugins/power-automate/.mcp.json b/plugins/power-automate/.mcp.jsonnew file mode 100644index 000000000..92fe3f12b--- /dev/null+++ b/plugins/power-automate/.mcp.json@@ -0,0 +1,11 @@+{+ "mcpServers": {+ "flowagent": {+ "command": "node",+ "args": [+ "-e",+ "const p=require('node:path');const r=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!r){console.error('Neither PLUGIN_ROOT nor CLAUDE_PLUGIN_ROOT is set');process.exit(1);}(async()=>{try{await import(require('node:url').pathToFileURL(p.resolve(r,'server','mcp.mjs')).href)}catch(e){console.error(e);process.exit(1)}})();"+ ]+ }+ }+}diff --git a/plugins/power-automate/.plugin/plugin.json b/plugins/power-automate/.plugin/plugin.jsonnew file mode 100644index 000000000..9c37edf20--- /dev/null+++ b/plugins/power-automate/.plugin/plugin.json@@ -0,0 +1,20 @@+{+ "name": "power-automate",+ "version": "2.0.0",+ "description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.",+ "author": {+ "name": "Microsoft",+ "url": "https://www.microsoft.com"+ },+ "homepage": "https://github.com/microsoft/power-platform-skills/",+ "repository": "https://github.com/microsoft/power-platform-skills/",+ "license": "MIT",+ "keywords": [+ "power-automate",+ "cloud-flows",+ "flows",+ "mcp",+ "power-platform",+ "flowagent"+ ]+}diff --git a/plugins/power-automate/AGENTS.md b/plugins/power-automate/AGENTS.mdnew file mode 100644index 000000000..93300edde--- /dev/null+++ b/plugins/power-automate/AGENTS.md@@ -0,0 +1,35 @@+# AGENTS.md — power-automate plugin++Guidance for AI agents (Copilot CLI, Claude Code, Cursor) operating inside this+plugin. The authoritative reference is the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md);+this file is the plugin-local routing rule.++## Tool routing (read first)++**If `flowagent-*` MCP tools are present in your tool surface, USE THEM** for any+flow/env/connection/run operation — list/get/create/update/**edit**/**copy**/+publish/run flows, environments, connections, connectors, run history + run+management (**cancel**, **cancel_all**, **resubmit**, **diagnose**, loop+repetitions), dynamic resolvers, templates, and `get_expression_help`.++The MCP server (`.mcp.json` → `flowagent`) is the supported integration path:+it handles auth (Azure CLI + MSAL), session-scoped current env/flow, structured+errors, and stays in-process. Shelling out re-pays auth cost and breaks session+state.++Shell (`node dist/cli.js …`) is reserved for users who have the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built, only for CLI-only commands the MCP does not wrap (connection lifecycle, sharing, solutions/admin), and not for plugin users when MCP tools are available.++If the `flowagent-*` tools are missing, the MCP isn't wired — point the user at+this plugin's `.mcp.json` / the install steps in `README.md`.++## Layout++- `skills/<skill>/SKILL.md` — user-invocable skills (verb-first names)+- `references/*.md` — shared reference docs (CLI commands, definition rules,+ connection patterns, error troubleshooting)+- `.claude-plugin/plugin.json` + `.plugin/plugin.json` — Claude / Copilot+ manifests+- `.mcp.json` — MCP server wiring++The flow-definition rules, auth model, error reference, and known issues live in+the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md) and apply whether you call via MCP or shell.diff --git a/plugins/power-automate/CLAUDE.md b/plugins/power-automate/CLAUDE.mdnew file mode 100644index 000000000..b8652196a--- /dev/null+++ b/plugins/power-automate/CLAUDE.md@@ -0,0 +1,27 @@+# CLAUDE.md — power-automate plugin++This is the marketplace plugin wrapper for **FlowAgent** (Power Automate cloud+flow tooling). The **authoritative reference is the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md)** —+flow-definition rules, the two-provider auth model (Azure CLI + MSAL), the full+CLI/MCP surface, the error reference, and known issues. Read it before building+or editing flows.++This file only covers plugin-local specifics; see `AGENTS.md` (this folder) for+the tool-routing rule.++## What's here++- `skills/` — verb-first user-invocable skills (`create-flow`, `build-flow`,+ `debug-flow`, `diagnose-flow`, `manage-flows`, `browse-flows`,+ `manage-desktop-flows`, `route-environments`, `setup`)+- `references/` — shared docs referenced by skills via `../../references/…`+- `.mcp.json` — launches the FlowAgent MCP server (`flowagent`)++## Engine vs plugin++The MCP **engine** (TypeScript monorepo: `packages/core`, `packages/cli`)+lives at the repo root and is built with `npm install &&+npm run build`. This `plugins/power-automate/` folder is the **plugin** — it is+designed to be lifted into the `microsoft/power-platform-skills` marketplace as+`plugins/power-automate/`. In this source repo, `.mcp.json` launches the bundled `server/mcp.mjs` via a+small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT`.diff --git a/plugins/power-automate/README.md b/plugins/power-automate/README.mdnew file mode 100644index 000000000..2f8b7fd06--- /dev/null+++ b/plugins/power-automate/README.md@@ -0,0 +1,69 @@+# Power Automate plugin++Build, edit, run, and debug **Power Automate cloud flows** from Claude Code or+GitHub Copilot CLI, powered by the **FlowAgent** MCP server.++This plugin is the marketplace-packaged surface of+[matow_microsoft/flow-agent](https://github.com/matow_microsoft/flow-agent). The+MCP server (the engine) lives in that repo's `packages/` monorepo; this folder+is the plugin (skills, MCP wiring).++## Install++From a Claude Code or GitHub Copilot CLI session:++```bash+/plugin marketplace add microsoft/power-platform-skills+/plugin install power-automate@power-platform-skills+```++> [!NOTE]+> **Self-contained — no npm install or remote host required.** The plugin ships a+> self-contained MCP engine at `server/mcp.mjs`, and `.mcp.json` launches it with+> a small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and+> dynamically imports `server/mcp.mjs`. (`@microsoft/power-automate-mcp` is not+> yet on npm; the plugin does not need it.) Auth still uses your local+> `az login` — see **MCP server** below.++## Capabilities++- **Flows**: list, get, create, **edit** (surgical action-level edits), **copy**+ (within/across environments), update, publish/disable, delete+- **Runs**: history, details, actions, **loop iteration drill-down**, **cancel**,+ **cancel all**, **resubmit**, **diagnose**+- **Connections**: lifecycle (CRUD, share, fix), auto-discovery, dynamic value+ resolution+- **Authoring**: templates/scaffolding, batch deploy, preflight + validation,+ **expression help**+- **Desktop flows**, environment routing++## Skills++| Skill | Purpose |+|-------|---------|+| `setup` | First-time prerequisite setup |+| `browse-flows` | Browse environments and flows interactively |+| `create-flow` | Guided flow creation |+| `build-flow` | Autonomously generate a complete flow from a description |+| `debug-flow` | Interactive debug of a failed run |+| `diagnose-flow` | Autonomous deep diagnosis of a failed run |+| `manage-flows` | Lifecycle ops: publish, test, batch, inventory |+| `manage-desktop-flows` | List/run desktop (RPA) flows |+| `route-environments` | Environment resolution/routing |++## MCP server++`.mcp.json` launches the FlowAgent MCP server from the bundled engine with a+small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and+dynamically imports `server/mcp.mjs`. That file is a single self-contained ESM+bundle (stdio transport, all 50+ tools, deps inlined), regenerated from+`packages/cli/src/bin/mcp-stdio.ts` by `npm run build` (`scripts/bundle-plugin-mcp.mjs`).+It needs only Node.js 18+ — no `npx`, no published npm package, no remote host.++> For local development against the monorepo you can point your client at the repo+> root shim instead: `node <repo>/dist/mcp.js` (run `npm install && npm run build`+> first). A publishable `@microsoft/power-automate-mcp` npm package may follow, but+> the plugin does not depend on it.++Auth uses Azure CLI (`az login`) plus MSAL for connectivity endpoints — see the+[FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md).diff --git a/plugins/power-automate/references/cli-reference.md b/plugins/power-automate/references/cli-reference.mdnew file mode 100644index 000000000..87365dfbd--- /dev/null+++ b/plugins/power-automate/references/cli-reference.md@@ -0,0 +1,91 @@+# Power Automate CLI Reference++> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.++All commands use `node dist/cli.js <command> [options]` from the project root.++## Global Flags+- `--quiet` — Suppress stderr progress messages (JSON-only output)+- `--env=<id>` — Target environment (or set `PA_DEFAULT_ENVIRONMENT`)+- `--format=json|ansi` — Output format for streaming commands++## File Arguments+Use `@path` syntax: `[email protected]`, `[email protected]`++## Environment Commands+| Command | Flags |+|---------|-------|+| `list-environments` | — |+| `resolve-environment` | `--env` |++## Cloud Flow Commands+| Command | Required | Optional |+|---------|----------|----------|+| `list-flows` | `--env` | `--top`, `--filter` |+| `get-flow` | `--env`, `--flow` | — |+| `create-flow` | `--env`, `--name`, `--definition=@f` | `--connection-refs=@f`, `--state`, `--validate` |+| `update-flow` | `--env`, `--flow` | `--name`, `--definition=@f`, `--connection-refs=@f`, `--state` |+| `delete-flow` | `--env`, `--flow` | — |+| `publish-flow` | `--env`, `--flow` | — |+| `disable-flow` | `--env`, `--flow` | — |+| `run-flow` | `--env`, `--flow` | `--body=@f`, `--no-callback` |+| `get-trigger-url` | `--env`, `--flow` | `--trigger` |+| `get-run-history` | `--env`, `--flow` | `--top`, `--filter` |+| `get-run-details` | `--env`, `--flow`, `--run` | — |+| `get-run-actions` | `--env`, `--flow`, `--run` | — |+| `set-flow-plan` | `--env`, `--flow`, `--plan` | — |+| `get-flow-sessions` | `--env`, `--flow` | `--top` |+| `set-connection-mode` | `--env`, `--flow`, `--connector`, `--mode` | — |+| `list-connection-modes` | `--env`, `--flow` | — |++## Connection Commands+| Command | Required | Optional |+|---------|----------|----------|+| `list-connections` | `--env` | `--connector` |+| `get-connections` | `--env` | `--connector` |+| `get-connection` | `--env`, `--connector`, `--connection` | — |+| `create-connection` | `--env`, `--connector` | `--no-browser` |+| `delete-connection` | `--env`, `--connector`, `--connection` | — |+| `get-connection-permissions` | `--env`, `--connector`, `--connection` | — |+| `share-connection` | `--env`, `--connector`, `--connection`, `--principal`, `--role` | `--principal-type` |+| `resolve-refs` | `--env`, `--connectors=a,b` | `--output`, `--auto-create`, `--verify` |+| `resolve-params` | `--env`, `--connector`, `--connection`, `--operation` | — |++## Connector Commands+| Command | Required | Optional |+|---------|----------|----------|+| `list-connectors` | `--env` | `--top` |+| `get-connector` | `--env`, `--connector` | — |+| `invoke-operation` | `--env`, `--connector`, `--connection`, `--operation` | `--params=@f` |+| `search-operations` | `--env` | `--query`, `--filter`, `--connector`, `--top` |+| `get-operation-schema` | `--env`, `--connector`, `--operation` | — |+| `get-dynamic-list` | `--env`, `--connector`, `--connection`, `--extension=@f` | `--params=@f` |+| `get-dynamic-tree` | `--env`, `--connector`, `--connection`, `--extension=@f` | `--params=@f`, `--selection=@f` |+| `get-dynamic-schema` | `--env`, `--connector`, `--connection`, `--extension=@f` | `--params=@f`, `--alias`, `--location` |++## Template & Testing Commands+| Command | Required | Optional |+|---------|----------|----------|+| `list-templates` | — | — |+| `scaffold-flow` | `--template` | `--output` |+| `batch-create` | `--env`, `--index=@f` | `--dry-run` |+| `validate-flow` | `--definition=@f` | `--connection-refs=@f` |+| `smoke-test` | `--env` | — |+| `run-and-wait` | `--env`, `--flow` | `--body=@f`, `--timeout`, `--poll-interval`, `--include-actions`, `--no-callback` |+| `watch-run` | `--env`, `--flow` | `--body=@f`, `--timeout`, `--poll-interval` |+| `test-suite` | `--env` | `--config=@f` |++## Desktop Flow Commands+| Command | Required | Optional |+|---------|----------|----------|+| `list-desktop-flows` | `--env` | `--top`, `--name` |+| `run-desktop-flow` | `--env`, `--flow` | `--body=@f`, `--timeout`, `--poll-interval`, `--machine-group`, `--format` |+| `get-desktop-flow-session` | `--env`, `--session` | — |+| `list-machine-groups` | `--env` | `--name` |+| `list-machines` | `--env` | `--group` |++## Other Commands+| Command | Required | Optional |+|---------|----------|----------|+| `search-users` | `--query` | `--top` |+| `help` | — | `[topic]` |diff --git a/plugins/power-automate/references/connection-patterns.md b/plugins/power-automate/references/connection-patterns.mdnew file mode 100644index 000000000..279d310a9--- /dev/null+++ b/plugins/power-automate/references/connection-patterns.md@@ -0,0 +1,82 @@+# Connection Resolution Patterns++> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.++## Discovering Connections++```bash+# List all connections for a connector (queries Dataverse)+node dist/cli.js list-connections --env=$ENV --connector=shared_teams++# List via PowerApps API (alternative, doesn't need Dataverse)+node dist/cli.js get-connections --env=$ENV --connector=shared_teams+```++## Auto-Resolving Connection References++```bash+# Auto-discover connections for multiple connectors+node dist/cli.js resolve-refs --env=$ENV --connectors=shared_teams,shared_office365++# With auto-create for missing connections+node dist/cli.js resolve-refs --env=$ENV --connectors=shared_teams --auto-create++# Verify connection health+node dist/cli.js resolve-refs --env=$ENV --connectors=shared_teams --verify+```++## Connection Reference Format++```json+{+ "shared_teams": {+ "connectionName": "shared-teams-xxxxxxxx",+ "source": "Embedded",+ "id": "/providers/Microsoft.PowerApps/apis/shared_teams",+ "tier": "NotSpecified"+ }+}+```++## Connection Modes++- **Embedded** — Flow uses its own stored credentials (default, recommended for API-triggered flows)+- **Invoker** — Flow uses the caller's credentials (requires X-MS-APIM-Tokens header)++```bash+# Check current modes+node dist/cli.js list-connection-modes --env=$ENV --flow=$FLOW++# Switch a connector to Embedded+node dist/cli.js set-connection-mode --env=$ENV --flow=$FLOW --connector=shared_teams --mode=Embedded+```++### Dataverse Special Case+When switching `shared_commondataserviceforapps` to Embedded, the CLI auto-adds:+```json+"connectionProperties": { "authentication": { "type": "ManagedServiceIdentity" } }+```++## Creating Connections++```bash+# Interactive (opens browser for OAuth consent)+node dist/cli.js create-connection --env=$ENV --connector=shared_teams++# Non-interactive (returns consent URL for manual auth)+node dist/cli.js create-connection --env=$ENV --connector=shared_teams --no-browser+```++## Sharing Connections++```bash+# Share with a user (CanUse or CanUseAndShare)+node dist/cli.js share-connection --env=$ENV --connector=shared_teams --connection=<name> \+ --principal=<user-object-id> --role=CanUse+```++## Critical Rules++1. **Always use `"source": "Embedded"`** for flows triggered via API/CLI. Invoker mode causes `InvokerConnectionOverrideFailed`.+2. **`list-connections` requires Dataverse** — if the environment lacks it, use `get-connections` instead (PowerApps API fallback).+3. **`resolve-refs` fallback chain**: Tries Dataverse first → PowerApps API on failure → reports `NO_CONNECTION_FOUND`.diff --git a/plugins/power-automate/references/definition-reference.md b/plugins/power-automate/references/definition-reference.mdnew file mode 100644index 000000000..88795f7ed--- /dev/null+++ b/plugins/power-automate/references/definition-reference.md@@ -0,0 +1,83 @@+# Flow Definition Reference++## Required Structure++```json+{+ "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",+ "contentVersion": "1.0.0.0",+ "parameters": {+ "$authentication": { "defaultValue": {}, "type": "SecureObject" },+ "$connections": { "defaultValue": {}, "type": "Object" }+ },+ "triggers": { ... },+ "actions": { ... }+}+```++## Common Triggers++**Manual (Button)**+```json+{ "type": "Request", "kind": "Button", "inputs": { "schema": { "type": "object" } } }+```++**Recurrence (Scheduled)**+```json+{ "type": "Recurrence", "recurrence": { "frequency": "Day", "interval": 1 } }+```++**HTTP Request**+```json+{ "type": "Request", "kind": "Http", "inputs": { "schema": { "type": "object", "properties": { ... } } } }+```++## Action Template (OpenApiConnection)++```json+{+ "type": "OpenApiConnection",+ "inputs": {+ "parameters": { "param1": "value1" },+ "host": {+ "apiId": "/providers/Microsoft.PowerApps/apis/shared_teams",+ "operationId": "PostMessageToConversation",+ "connectionName": "shared_teams"+ }+ },+ "runAfter": {}+}+```++## Other Action Types++- `Compose`: `{ "type": "Compose", "inputs": "<expression>" }`+- `Http`: `{ "type": "Http", "inputs": { "method": "GET", "uri": "..." } }`+- `If`: `{ "type": "If", "expression": { ... }, "actions": { ... }, "else": { "actions": { ... } } }`+- `Foreach`: `{ "type": "Foreach", "foreach": "@...", "actions": { ... } }`+- `Response`: `{ "type": "Response", "inputs": { "statusCode": 200, "body": "@..." } }`++## Expression Syntax++- String interpolation: `@{triggerBody()?['name']}`+- Functions: `concat()`, `formatDateTime()`, `utcNow()`, `body('<action>')`, `outputs('<action>')`+- Null handling: `coalesce()`, `if()`, `equals()`+- Connection ref: `@parameters('$connections')['shared_teams']['connectionId']`++## Validation Rules (checked by `validate-flow`)++1. Declare both `$authentication` and `$connections` in `parameters`+2. Use `"type": "OpenApiConnection"` (NOT `ApiConnection`)+3. Do NOT add `"authentication"` to action inputs (auto-injected by PA)+4. `host.connectionName` must match a key in connection references+5. `runAfter` must reference existing action names+6. No `@odata.bind` parameter suffixes++## Dynamic Parameters++Parameters may have annotations from the connector swagger:+- `dynamicValues` — valid values from calling another operation (dropdown)+- `dynamicTree` — tree browser with `open`/`browse` operations (file picker)+- `dynamicSchema` — schema determined dynamically (varies by selection)++Use `get-connector`, then `invoke-operation` or `resolve-params` to resolve these.diff --git a/plugins/power-automate/references/error-troubleshooting.md b/plugins/power-automate/references/error-troubleshooting.mdnew file mode 100644index 000000000..92f4ddee8--- /dev/null+++ b/plugins/power-automate/references/error-troubleshooting.md@@ -0,0 +1,37 @@+# Common API Errors & Fixes++> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.++| Error | Cause | Fix |+|-------|-------|-----|+| `500 NullReferenceException` | Missing `$authentication` parameter | Add `parameters` block with `$authentication` and `$connections` |+| `InvokerConnectionOverrideFailed` | Used `"source": "Invoker"` | Change to `"source": "Embedded"` in connection refs |+| `WorkflowRunActionInputsInvalidProperty` | Included `"authentication"` in action inputs | Remove it — PA auto-injects on save |+| `InvalidTemplate` / parameter not declared | Missing parameter declaration | Declare `$authentication` and `$connections` in definition |+| `DirectApiRequestHasMoreThanOneAuthorization` | Added auth header to SAS URL | Don't add `Authorization` header to SAS URLs |+| `ConnectionNotFound` / `AuthorizationFailed` | Expired or deleted connection | Re-authorize: `create-connection --env=$ENV --connector=<name>` |+| `ExpressionEvaluationFailed` | Bad expression or null reference | Check expression syntax, add `coalesce()` for nullable values |+| `ActionTimedOut` | Action exceeded timeout | Add retry policy or increase timeout |+| `triggerBody() returns null` | Used management API trigger (not callback) | Use `--body=@file` with `run-flow` (auto-uses callback URL) or explicit `--no-callback` |++## Diagnostic Steps++1. **Get recent failed run**:+ ```bash+ node dist/cli.js get-run-history --env=$ENV --flow=$FLOW --top=5+ ```++2. **Get action-level details**:+ ```bash+ node dist/cli.js get-run-actions --env=$ENV --flow=$FLOW --run=$RUN+ ```++3. **Check flow definition**:+ ```bash+ node dist/cli.js get-flow --env=$ENV --flow=$FLOW+ ```++4. **Validate before creating**:+ ```bash+ node dist/cli.js validate-flow [email protected] [email protected]+ ```diff --git a/plugins/power-automate/server/mcp.mjs b/plugins/power-automate/server/mcp.mjsnew file mode 100644index 000000000..823de0d76--- /dev/null+++ b/plugins/power-automate/server/mcp.mjs@@ -0,0 +1,42658 @@+#!/usr/bin/env node+// FlowAgent stdio MCP server — single-file ESM bundle for the power-automate plugin.+// Generated by scripts/bundle-plugin-mcp.mjs (npm run build:plugin). Do not edit.+// https://github.com/matow_microsoft/flow-agent+import { createRequire as __pa_createRequire } from 'node:module';+const require = __pa_createRequire(import.meta.url);+var __create = Object.create;+var __defProp = Object.defineProperty;+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;+var __getOwnPropNames = Object.getOwnPropertyNames;+var __getProtoOf = Object.getPrototypeOf;+var __hasOwnProp = Object.prototype.hasOwnProperty;+var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]+}) : x)(function(x) {+ if (typeof require !== "undefined") return require.apply(this, arguments);+ throw Error('Dynamic require of "' + x + '" is not supported');+});+var __esm = (fn, res) => function __init() {+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;+};+var __commonJS = (cb, mod) => function __require2() {+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;+};+var __export = (target, all) => {+ for (var name3 in all)+ __defProp(target, name3, { get: all[name3], enumerable: true });+};+var __copyProps = (to, from, except, desc) => {+ if (from && typeof from === "object" || typeof from === "function") {+ for (let key of __getOwnPropNames(from))+ if (!__hasOwnProp.call(to, key) && key !== except)+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });+ }+ return to;+};+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(+ // If the importer is in node compatibility mode or this is not an ESM+ // file that has been converted to a CommonJS file using a Babel-+ // compatible transform (i.e. "__esModule" has not been set), then set+ // "default" to the CommonJS "module.exports" for node compatibility.+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,+ mod+));++// packages/core/dist/utils/logger.js+var LOG_PREFIX, logger;+var init_logger = __esm({+ "packages/core/dist/utils/logger.js"() {+ "use strict";+ LOG_PREFIX = "[power-automate-mcp]";+ logger = {+ info(...args) {+ console.error(LOG_PREFIX, "INFO", ...args);+ },+ warn(...args) {+ console.error(LOG_PREFIX, "WARN", ...args);+ },+ error(...args) {+ console.error(LOG_PREFIX, "ERROR", ...args);+ },+ debug(...args) {+ if (process.env.PA_MCP_DEBUG === "true") {+ console.error(LOG_PREFIX, "DEBUG", ...args);+ }+ }+ };+ }+});++// packages/core/dist/api/backups.js+var backups_exports = {};+__export(backups_exports, {+ getBackupRoot: () => getBackupRoot,+ latestBackup: () => latestBackup,+ listBackups: () => listBackups,+ readBackup: () => readBackup,+ snapshot: () => snapshot,+ snapshotOrThrow: () => snapshotOrThrow+});+import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync, existsSync } from "fs";+import { join, resolve } from "path";+function getBackupRoot() {+ const base = process.env.FLOWAGENT_HOME ?? process.cwd();+ return resolve(base, ".flowagent", "backups");+}+function flowDir(envId, flowId) {+ return join(getBackupRoot(), envId, flowId);+}+function timestampSlug(d = /* @__PURE__ */ new Date()) {+ return d.toISOString().replace(/[:.]/g, "-");+}+function snapshot(opts) {+ try {+ return snapshotOrThrow(opts);+ } catch (err) {+ logger.warn(`Backup snapshot failed for ${opts.flowId}: ${err instanceof Error ? err.message : err}. Operation continues.`);+ return null;+ }+}+function snapshotOrThrow(opts) {+ const dir = flowDir(opts.envId, opts.flowId);+ mkdirSync(dir, { recursive: true });+ const capturedAt = (/* @__PURE__ */ new Date()).toISOString();+ const backup = {+ capturedAt,+ envId: opts.envId,+ flowId: opts.flowId,+ operation: opts.operation,+ flow: opts.flow,+ context: opts.context,+ note: opts.note,+ backupVersion: 1+ };+ const filename = `${timestampSlug(new Date(capturedAt))}.json`;+ const path3 = join(dir, filename);+ writeFileSync(path3, JSON.stringify(backup, null, 2), "utf-8");+ logger.debug(`Backup written: ${path3}`);+ pruneRetention(dir);+ return path3;+}+function pruneRetention(dir) {+ let entries;+ try {+ entries = readdirSync(dir).filter((f) => f.endsWith(".json"));+ } catch {+ return;+ }+ if (entries.length <= RETENTION)+ return;+ const sorted = entries.map((f) => ({ f, mtime: safeMtime(join(dir, f)) })).sort((a, b) => a.mtime - b.mtime);+ const drop = sorted.slice(0, sorted.length - RETENTION);+ for (const d of drop) {+ try {+ unlinkSync(join(dir, d.f));+ logger.debug(`Backup pruned (FIFO): ${d.f}`);+ } catch (err) {+ logger.warn(`Backup prune failed for ${d.f}: ${err instanceof Error ? err.message : err}`);+ }+ }+}+function safeMtime(p) {+ try {+ return statSync(p).mtimeMs;+ } catch {+ return 0;+ }+}+function listBackups(envId, flowId) {+ const dir = flowDir(envId, flowId);+ if (!existsSync(dir))+ return [];+ const files = readdirSync(dir).filter((f) => f.endsWith(".json"));+ return files.map((filename) => {+ const path3 = join(dir, filename);+ let capturedAt = "";+ let operation = "unknown";+ let sizeBytes = 0;+ try {+ sizeBytes = statSync(path3).size;+ const raw = readFileSync(path3, "utf-8");+ const parsed = JSON.parse(raw);+ capturedAt = parsed.capturedAt ?? "";+ operation = parsed.operation ?? "unknown";+ } catch (err) {+ logger.warn(`Could not read backup ${filename}: ${err instanceof Error ? err.message : err}`);+ }+ return { filename, capturedAt, operation, path: path3, sizeBytes };+ }).sort((a, b) => b.capturedAt > a.capturedAt ? 1 : -1);+}+function readBackup(envId, flowId, filename) {+ const path3 = join(flowDir(envId, flowId), filename);+ if (!existsSync(path3)) {+ throw new Error(`Backup not found: ${path3}`);+ }+ const raw = readFileSync(path3, "utf-8");+ return JSON.parse(raw);+}+function latestBackup(envId, flowId) {+ const list = listBackups(envId, flowId);+ return list[0] ?? null;+}+var RETENTION;+var init_backups = __esm({+ "packages/core/dist/api/backups.js"() {+ "use strict";+ init_logger();+ RETENTION = 10;+ }+});++// packages/core/dist/validation/flow-definition.js+var flow_definition_exports = {};+__export(flow_definition_exports, {+ validateDefinition: () => validateDefinition+});+function validateDefinition(definition, connectionReferences) {+ const errors = [];+ const params = definition.parameters;+ if (!params || !("$authentication" in params)) {+ errors.push({+ rule: "missing-authentication-param",+ message: "Definition must declare $authentication in parameters (type: SecureObject)"+ });+ }+ if (!params || !("$connections" in params)) {+ errors.push({+ rule: "missing-connections-param",+ message: "Definition must declare $connections in parameters (type: Object)"+ });+ }+ const VALID_TRIGGER_TYPES = /* @__PURE__ */ new Set([+ "Request",+ "Recurrence",+ "OpenApiConnection",+ "OpenApiConnectionWebhook",+ "OpenApiConnectionNotification",+ "ApiConnection",+ "ApiConnectionWebhook",+ "ApiConnectionNotification",+ "Http",+ "HttpWebhook"+ ]);+ const VALID_REQUEST_KINDS = /* @__PURE__ */ new Set([+ "Button",+ "Http",+ "PowerApp",+ "PowerAppV2",+ "VirtualAgent",+ "Skills",+ "ApiConnection",+ "PowerPages"+ ]);+ const triggers = definition.triggers ?? {};+ for (const [tName, trigger] of Object.entries(triggers)) {+ const triggerType = trigger.type;+ if (triggerType && !VALID_TRIGGER_TYPES.has(triggerType)) {+ errors.push({+ rule: "invalid-trigger-type",+ message: `Unknown trigger type "${triggerType}". Expected one of: ${[...VALID_TRIGGER_TYPES].join(", ")}`,+ path: `triggers.${tName}.type`+ });+ }+ if (triggerType === "Request") {+ const kind = trigger.kind;+ if (kind && !VALID_REQUEST_KINDS.has(kind)) {+ errors.push({+ rule: "invalid-trigger-kind",+ message: `Unknown Request trigger kind "${kind}". Expected one of: ${[...VALID_REQUEST_KINDS].join(", ")}`,+ path: `triggers.${tName}.kind`+ });+ }+ if (kind === "Http") {+ errors.push({+ rule: "premium-trigger-warning",+ message: `HTTP Request triggers require a Premium license. Use "Button" kind for free/seeded plans, or "PowerAppV2" for Power Apps context.`,+ path: `triggers.${tName}.kind`+ });+ }+ }+ const triggerInputs = trigger.inputs && typeof trigger.inputs === "object" && !Array.isArray(trigger.inputs) ? trigger.inputs : void 0;+ const triggerHost = triggerInputs?.host;+ if (triggerHost) {+ const api = triggerHost.api;+ if (api?.runtimeUrl) {+ errors.push({+ rule: "legacy-runtime-url",+ message: "Trigger host contains runtimeUrl (legacy ApiConnection pattern). Use apiId + operationId + connectionName instead.",+ path: `triggers.${tName}.inputs.host.api.runtimeUrl`+ });+ }+ }+ }+ const actions = definition.actions ?? {};+ const actionNames = new Set(Object.keys(actions));+ for (const [name3, action] of Object.entries(actions)) {+ const rawInputs = action.inputs;+ const inputs = rawInputs && typeof rawInputs === "object" && !Array.isArray(rawInputs) ? rawInputs : void 0;+ if (connectionReferences) {+ const host2 = inputs?.host;+ const connName = host2?.connectionName ?? host2?.connectionReferenceName;+ let refKey;+ if (connName) {+ if (connName in connectionReferences) {+ refKey = connName;+ } else {+ refKey = Object.keys(connectionReferences).find((k) => connectionReferences[k].connectionReferenceLogicalName === connName);+ }+ if (refKey) {+ const source = connectionReferences[refKey].source;+ if (source && source !== "Embedded") {+ errors.push({+ rule: "invoker-connection",+ message: `Connection source must be "Embedded", not "${source}". Invoker causes InvokerConnectionOverrideFailed errors.`,+ path: `connectionReferences.${refKey}`+ });+ }+ }+ }+ }+ if (action.type === "ApiConnection") {+ errors.push({+ rule: "legacy-action-type",+ message: `Use "OpenApiConnection" instead of "ApiConnection" (legacy format)`,+ path: `actions.${name3}`+ });+ }+ const KNOWN_WEBHOOK_OPERATIONS = /* @__PURE__ */ new Set([+ "StartAndWaitForAnApproval",+ "WaitForAnApproval",+ "SubscribeWebhook",+ "HttpWebhookTrigger"+ ]);+ if (action.type === "OpenApiConnection") {+ const host2 = inputs?.host;+ const operationId = host2?.operationId;+ if (operationId && KNOWN_WEBHOOK_OPERATIONS.has(operationId)) {+ errors.push({+ rule: "webhook-type-mismatch",+ message: `Operation "${operationId}" is a webhook operation and requires type "OpenApiConnectionWebhook", not "OpenApiConnection". Webhook operations include long-running polls like Approvals.`,+ path: `actions.${name3}.type`+ });+ }+ if (operationId && !KNOWN_WEBHOOK_OPERATIONS.has(operationId) && /^(StartAndWait|WaitFor|Subscribe)/i.test(operationId)) {+ errors.push({+ rule: "webhook-type-mismatch",+ message: `Operation "${operationId}" appears to be a webhook operation (name starts with StartAndWait/WaitFor/Subscribe). It likely requires type "OpenApiConnectionWebhook" instead of "OpenApiConnection". Verify with get_connector.`,+ path: `actions.${name3}.type`+ });+ }+ }+ if (inputs && "authentication" in inputs) {+ errors.push({+ rule: "extra-authentication",+ message: "Do not include authentication in action inputs \u2014 the Flow API auto-injects it",+ path: `actions.${name3}.inputs.authentication`+ });+ }+ const actionParams = inputs?.parameters;+ if (actionParams) {+ for (const paramKey of Object.keys(actionParams)) {+ if (paramKey.includes("@odata.bind")) {+ errors.push({+ rule: "odata-bind-param",+ message: `Parameter "${paramKey}" uses @odata.bind syntax which PA connectors don't support. Use the plain field name instead.`,+ path: `actions.${name3}.inputs.parameters.${paramKey}`+ });+ }+ }+ }+ if (connectionReferences) {+ const host2 = inputs?.host;+ const connName = host2?.connectionName;+ const connRefName = host2?.connectionReferenceName;+ if (connName && !(connName in connectionReferences)) {+ errors.push({+ rule: "unresolved-connection",+ message: `host.connectionName "${connName}" not found in connectionReferences`,+ path: `actions.${name3}.inputs.host.connectionName`+ });+ }+ if (connRefName && !connName) {+ const found = Object.values(connectionReferences).some((ref) => ref.connectionReferenceLogicalName === connRefName);+ if (!found) {+ errors.push({+ rule: "unresolved-connection",+ message: `host.connectionReferenceName "${connRefName}" not found in connectionReferences logical names`,+ path: `actions.${name3}.inputs.host.connectionReferenceName`+ });+ }+ }+ }+ const actionHost = inputs?.host;+ const actionOperationId = actionHost?.operationId;+ if (actionOperationId === "StartAndWaitForAnApproval" || actionOperationId === "approvalSubscribeV2" || actionOperationId === "approvalSubscribe") {+ if (actionOperationId === "approvalSubscribeV2" || actionOperationId === "approvalSubscribe") {+ errors.push({+ rule: "deprecated-approval-operation",+ message: `Operation "${actionOperationId}" is deprecated. Use "StartAndWaitForAnApproval" instead.`,+ path: `actions.${name3}.inputs.host.operationId`+ });+ }+ const VALID_APPROVAL_TYPES = /* @__PURE__ */ new Set([+ "Basic",+ "BasicAwaitAll",+ "CustomResponse",+ "CustomResponseAwaitAll",+ "Sequential"+ ]);+ if (actionParams) {+ const approvalType = actionParams.approvalType;+ if (approvalType && !VALID_APPROVAL_TYPES.has(approvalType)) {+ errors.push({+ rule: "invalid-approval-type",+ message: `Invalid approvalType "${approvalType}". Must be one of: ${[...VALID_APPROVAL_TYPES].join(", ")}. Common mistake: "BasicApproveReject" should be "Basic".`,+ path: `actions.${name3}.inputs.parameters.approvalType`+ });+ }+ if (actionOperationId === "StartAndWaitForAnApproval") {+ const bodyParamKeys = Object.keys(actionParams).filter((k) => k !== "approvalType");+ for (const key of bodyParamKeys) {+ if (key.startsWith("ApprovalCreationInput/")) {+ errors.push({+ rule: "approval-param-prefix",+ message: `Approval parameter "${key}" uses the deprecated "ApprovalCreationInput/" prefix. For StartAndWaitForAnApproval, use "WebhookApprovalCreationInput/" prefix: "WebhookApprovalCreationInput/${key.replace("ApprovalCreationInput/", "")}".`,+ path: `actions.${name3}.inputs.parameters.${key}`+ });+ } else if (!key.startsWith("WebhookApprovalCreationInput/")) {+ errors.push({+ rule: "approval-param-prefix",+ message: `Approval parameter "${key}" needs "WebhookApprovalCreationInput/" prefix: "WebhookApprovalCreationInput/${key}". Bare names cause designer schema errors.`,+ path: `actions.${name3}.inputs.parameters.${key}`+ });+ }+ }+ }+ }+ }+ const host = inputs?.host;+ if (host) {+ const api = host.api;+ if (api?.runtimeUrl) {+ errors.push({+ rule: "legacy-runtime-url",+ message: "Action host contains runtimeUrl (legacy ApiConnection pattern). Use apiId + operationId + connectionName instead.",+ path: `actions.${name3}.inputs.host.api.runtimeUrl`+ });+ }+ }+ const runAfter = action.runAfter;+ if (runAfter) {+ for (const dep of Object.keys(runAfter)) {+ if (!actionNames.has(dep)) {+ errors.push({+ rule: "invalid-runafter",+ message: `runAfter references "${dep}" which does not exist in actions`,+ path: `actions.${name3}.runAfter.${dep}`+ });+ }+ }+ }+ }+ return errors;+}+var init_flow_definition = __esm({+ "packages/core/dist/validation/flow-definition.js"() {+ "use strict";+ }+});++// node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs+var Serializer;+var init_Serializer = __esm({+ "node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs"() {+ "use strict";+ Serializer = class {+ /**+ * serialize the JSON blob+ * @param data - JSON blob cache+ */+ static serializeJSONBlob(data) {+ return JSON.stringify(data);+ }+ /**+ * Serialize Accounts+ * @param accCache - cache of accounts+ */+ static serializeAccounts(accCache) {+ const accounts = {};+ Object.keys(accCache).map(function(key) {+ const accountEntity = accCache[key];+ accounts[key] = {+ home_account_id: accountEntity.homeAccountId,+ environment: accountEntity.environment,+ realm: accountEntity.realm,+ local_account_id: accountEntity.localAccountId,+ username: accountEntity.username,+ authority_type: accountEntity.authorityType,+ name: accountEntity.name,+ client_info: accountEntity.clientInfo,+ last_modification_time: accountEntity.lastModificationTime,+ last_modification_app: accountEntity.lastModificationApp,+ tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => {+ return JSON.stringify(tenantProfile);+ })+ };+ });+ return accounts;+ }+ /**+ * Serialize IdTokens+ * @param idTCache - cache of ID tokens+ */+ static serializeIdTokens(idTCache) {+ const idTokens = {};+ Object.keys(idTCache).map(function(key) {+ const idTEntity = idTCache[key];+ idTokens[key] = {+ home_account_id: idTEntity.homeAccountId,+ environment: idTEntity.environment,+ credential_type: idTEntity.credentialType,+ client_id: idTEntity.clientId,+ secret: idTEntity.secret,+ realm: idTEntity.realm+ };+ });+ return idTokens;+ }+ /**+ * Serializes AccessTokens+ * @param atCache - cache of access tokens+ */+ static serializeAccessTokens(atCache) {+ const accessTokens = {};+ Object.keys(atCache).map(function(key) {+ const atEntity = atCache[key];+ accessTokens[key] = {+ home_account_id: atEntity.homeAccountId,+ environment: atEntity.environment,+ credential_type: atEntity.credentialType,+ client_id: atEntity.clientId,+ secret: atEntity.secret,+ realm: atEntity.realm,+ target: atEntity.target,+ cached_at: atEntity.cachedAt,+ expires_on: atEntity.expiresOn,+ extended_expires_on: atEntity.extendedExpiresOn,+ refresh_on: atEntity.refreshOn,+ key_id: atEntity.keyId,+ token_type: atEntity.tokenType,+ userAssertionHash: atEntity.userAssertionHash,+ resource: atEntity.resource,+ additionalCacheKeyComponents: atEntity.additionalCacheKeyComponents+ };+ });+ return accessTokens;+ }+ /**+ * Serialize refreshTokens+ * @param rtCache - cache of refresh tokens+ */+ static serializeRefreshTokens(rtCache) {+ const refreshTokens = {};+ Object.keys(rtCache).map(function(key) {+ const rtEntity = rtCache[key];+ refreshTokens[key] = {+ home_account_id: rtEntity.homeAccountId,+ environment: rtEntity.environment,+ credential_type: rtEntity.credentialType,+ client_id: rtEntity.clientId,+ secret: rtEntity.secret,+ family_id: rtEntity.familyId,+ target: rtEntity.target,+ realm: rtEntity.realm+ };+ });+ return refreshTokens;+ }+ /**+ * Serialize amdtCache+ * @param amdtCache - cache of app metadata+ */+ static serializeAppMetadata(amdtCache) {+ const appMetadata = {};+ Object.keys(amdtCache).map(function(key) {+ const amdtEntity = amdtCache[key];+ appMetadata[key] = {+ client_id: amdtEntity.clientId,+ environment: amdtEntity.environment,+ family_id: amdtEntity.familyId+ };+ });+ return appMetadata;+ }+ /**+ * Serialize the cache+ * @param inMemCache - itemised cache read from the JSON+ */+ static serializeAllCache(inMemCache) {+ return {+ Account: this.serializeAccounts(inMemCache.accounts),+ IdToken: this.serializeIdTokens(inMemCache.idTokens),+ AccessToken: this.serializeAccessTokens(inMemCache.accessTokens),+ RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens),+ AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata)+ };+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/Constants.mjs+var Constants_exports = {};+__export(Constants_exports, {+ AADAuthority: () => AADAuthority,+ AAD_INSTANCE_DISCOVERY_ENDPT: () => AAD_INSTANCE_DISCOVERY_ENDPT,+ AAD_TENANT_DOMAIN_SUFFIX: () => AAD_TENANT_DOMAIN_SUFFIX,+ ADFS: () => ADFS,+ APP_METADATA: () => APP_METADATA,+ AUTHORITY_METADATA_CACHE_KEY: () => AUTHORITY_METADATA_CACHE_KEY,+ AUTHORITY_METADATA_REFRESH_TIME_SECONDS: () => AUTHORITY_METADATA_REFRESH_TIME_SECONDS,+ AUTHORIZATION_PENDING: () => AUTHORIZATION_PENDING,+ AZURE_REGION_AUTO_DISCOVER_FLAG: () => AZURE_REGION_AUTO_DISCOVER_FLAG,+ AuthenticationScheme: () => AuthenticationScheme,+ AuthorityMetadataSource: () => AuthorityMetadataSource,+ CACHE_ACCOUNT_TYPE_ADFS: () => CACHE_ACCOUNT_TYPE_ADFS,+ CACHE_ACCOUNT_TYPE_GENERIC: () => CACHE_ACCOUNT_TYPE_GENERIC,+ CACHE_ACCOUNT_TYPE_MSAV1: () => CACHE_ACCOUNT_TYPE_MSAV1,+ CACHE_ACCOUNT_TYPE_MSSTS: () => CACHE_ACCOUNT_TYPE_MSSTS,+ CACHE_KEY_SEPARATOR: () => CACHE_KEY_SEPARATOR,+ CIAM_AUTH_URL: () => CIAM_AUTH_URL,+ CLIENT_INFO: () => CLIENT_INFO,+ CLIENT_INFO_SEPARATOR: () => CLIENT_INFO_SEPARATOR,+ CLIENT_MISMATCH_ERROR: () => CLIENT_MISMATCH_ERROR,+ CODE_GRANT_TYPE: () => CODE_GRANT_TYPE,+ CONSUMER_UTID: () => CONSUMER_UTID,+ CacheOutcome: () => CacheOutcome,+ CacheType: () => CacheType,+ ClaimsRequestKeys: () => ClaimsRequestKeys,+ CodeChallengeMethodValues: () => CodeChallengeMethodValues,+ CredentialType: () => CredentialType,+ DEFAULT_AUTHORITY: () => DEFAULT_AUTHORITY,+ DEFAULT_AUTHORITY_HOST: () => DEFAULT_AUTHORITY_HOST,+ DEFAULT_COMMON_TENANT: () => DEFAULT_COMMON_TENANT,+ DEFAULT_MAX_THROTTLE_TIME_SECONDS: () => DEFAULT_MAX_THROTTLE_TIME_SECONDS,+ DEFAULT_THROTTLE_TIME_SECONDS: () => DEFAULT_THROTTLE_TIME_SECONDS,+ DEFAULT_TOKEN_RENEWAL_OFFSET_SEC: () => DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,+ DSTS: () => DSTS,+ EMAIL_SCOPE: () => EMAIL_SCOPE,+ EncodingTypes: () => EncodingTypes,+ FORWARD_SLASH: () => FORWARD_SLASH,+ GrantType: () => GrantType,+ HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,+ HTTP_CLIENT_ERROR: () => HTTP_CLIENT_ERROR,+ HTTP_CLIENT_ERROR_RANGE_END: () => HTTP_CLIENT_ERROR_RANGE_END,+ HTTP_CLIENT_ERROR_RANGE_START: () => HTTP_CLIENT_ERROR_RANGE_START,+ HTTP_GATEWAY_TIMEOUT: () => HTTP_GATEWAY_TIMEOUT,+ HTTP_GONE: () => HTTP_GONE,+ HTTP_MULTI_SIDED_ERROR: () => HTTP_MULTI_SIDED_ERROR,+ HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,+ HTTP_REDIRECT: () => HTTP_REDIRECT,+ HTTP_REQUEST_TIMEOUT: () => HTTP_REQUEST_TIMEOUT,+ HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,+ HTTP_SERVER_ERROR_RANGE_END: () => HTTP_SERVER_ERROR_RANGE_END,+ HTTP_SERVER_ERROR_RANGE_START: () => HTTP_SERVER_ERROR_RANGE_START,+ HTTP_SERVICE_UNAVAILABLE: () => HTTP_SERVICE_UNAVAILABLE,+ HTTP_SUCCESS: () => HTTP_SUCCESS,+ HTTP_SUCCESS_RANGE_END: () => HTTP_SUCCESS_RANGE_END,+ HTTP_SUCCESS_RANGE_START: () => HTTP_SUCCESS_RANGE_START,+ HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,+ HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,+ HeaderNames: () => HeaderNames,+ HttpMethod: () => HttpMethod,+ IMDS_ENDPOINT: () => IMDS_ENDPOINT,+ IMDS_TIMEOUT: () => IMDS_TIMEOUT,+ IMDS_VERSION: () => IMDS_VERSION,+ INVALID_GRANT_ERROR: () => INVALID_GRANT_ERROR,+ INVALID_INSTANCE: () => INVALID_INSTANCE,+ JsonWebTokenTypes: () => JsonWebTokenTypes,+ KNOWN_PUBLIC_CLOUDS: () => KNOWN_PUBLIC_CLOUDS,+ NOT_APPLICABLE: () => NOT_APPLICABLE,+ NOT_AVAILABLE: () => NOT_AVAILABLE,+ OAuthResponseType: () => OAuthResponseType,+ OFFLINE_ACCESS_SCOPE: () => OFFLINE_ACCESS_SCOPE,+ OIDC_DEFAULT_SCOPES: () => OIDC_DEFAULT_SCOPES,+ OIDC_SCOPES: () => OIDC_SCOPES,+ ONE_DAY_IN_MS: () => ONE_DAY_IN_MS,+ OPENID_SCOPE: () => OPENID_SCOPE,+ PROFILE_SCOPE: () => PROFILE_SCOPE,+ PasswordGrantConstants: () => PasswordGrantConstants,+ PersistentCacheKeys: () => PersistentCacheKeys,+ PromptValue: () => PromptValue,+ REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: () => REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX,+ RESOURCE_DELIM: () => RESOURCE_DELIM,+ RegionDiscoveryOutcomes: () => RegionDiscoveryOutcomes,+ RegionDiscoverySources: () => RegionDiscoverySources,+ ResponseMode: () => ResponseMode,+ S256_CODE_CHALLENGE_METHOD: () => S256_CODE_CHALLENGE_METHOD,+ SERVER_TELEM_CACHE_KEY: () => SERVER_TELEM_CACHE_KEY,+ SERVER_TELEM_CATEGORY_SEPARATOR: () => SERVER_TELEM_CATEGORY_SEPARATOR,+ SERVER_TELEM_MAX_CACHED_ERRORS: () => SERVER_TELEM_MAX_CACHED_ERRORS,+ SERVER_TELEM_MAX_CUR_HEADER_BYTES: () => SERVER_TELEM_MAX_CUR_HEADER_BYTES,+ SERVER_TELEM_MAX_LAST_HEADER_BYTES: () => SERVER_TELEM_MAX_LAST_HEADER_BYTES,+ SERVER_TELEM_OVERFLOW_FALSE: () => SERVER_TELEM_OVERFLOW_FALSE,+ SERVER_TELEM_OVERFLOW_TRUE: () => SERVER_TELEM_OVERFLOW_TRUE,+ SERVER_TELEM_SCHEMA_VERSION: () => SERVER_TELEM_SCHEMA_VERSION,+ SERVER_TELEM_UNKNOWN_ERROR: () => SERVER_TELEM_UNKNOWN_ERROR,+ SERVER_TELEM_VALUE_SEPARATOR: () => SERVER_TELEM_VALUE_SEPARATOR,+ SHR_NONCE_VALIDITY: () => SHR_NONCE_VALIDITY,+ SKU: () => SKU,+ THE_FAMILY_ID: () => THE_FAMILY_ID,+ THROTTLING_PREFIX: () => THROTTLING_PREFIX,+ URL_FORM_CONTENT_TYPE: () => URL_FORM_CONTENT_TYPE,+ X_MS_LIB_CAPABILITY_VALUE: () => X_MS_LIB_CAPABILITY_VALUE+});+var SKU, DEFAULT_AUTHORITY, DEFAULT_AUTHORITY_HOST, DEFAULT_COMMON_TENANT, ADFS, DSTS, AAD_INSTANCE_DISCOVERY_ENDPT, CIAM_AUTH_URL, AAD_TENANT_DOMAIN_SUFFIX, RESOURCE_DELIM, CONSUMER_UTID, OPENID_SCOPE, PROFILE_SCOPE, OFFLINE_ACCESS_SCOPE, EMAIL_SCOPE, CODE_GRANT_TYPE, S256_CODE_CHALLENGE_METHOD, URL_FORM_CONTENT_TYPE, AUTHORIZATION_PENDING, NOT_APPLICABLE, NOT_AVAILABLE, FORWARD_SLASH, IMDS_ENDPOINT, IMDS_VERSION, IMDS_TIMEOUT, AZURE_REGION_AUTO_DISCOVER_FLAG, REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX, KNOWN_PUBLIC_CLOUDS, SHR_NONCE_VALIDITY, INVALID_INSTANCE, HTTP_SUCCESS, HTTP_SUCCESS_RANGE_START, HTTP_SUCCESS_RANGE_END, HTTP_REDIRECT, HTTP_CLIENT_ERROR, HTTP_CLIENT_ERROR_RANGE_START, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_NOT_FOUND, HTTP_REQUEST_TIMEOUT, HTTP_GONE, HTTP_TOO_MANY_REQUESTS, HTTP_CLIENT_ERROR_RANGE_END, HTTP_SERVER_ERROR, HTTP_SERVER_ERROR_RANGE_START, HTTP_SERVICE_UNAVAILABLE, HTTP_GATEWAY_TIMEOUT, HTTP_SERVER_ERROR_RANGE_END, HTTP_MULTI_SIDED_ERROR, HttpMethod, OIDC_DEFAULT_SCOPES, OIDC_SCOPES, HeaderNames, PersistentCacheKeys, AADAuthority, ClaimsRequestKeys, PromptValue, CodeChallengeMethodValues, OAuthResponseType, ResponseMode, GrantType, CACHE_ACCOUNT_TYPE_MSSTS, CACHE_ACCOUNT_TYPE_ADFS, CACHE_ACCOUNT_TYPE_MSAV1, CACHE_ACCOUNT_TYPE_GENERIC, CACHE_KEY_SEPARATOR, CLIENT_INFO_SEPARATOR, CredentialType, CacheType, APP_METADATA, CLIENT_INFO, THE_FAMILY_ID, AUTHORITY_METADATA_CACHE_KEY, AUTHORITY_METADATA_REFRESH_TIME_SECONDS, AuthorityMetadataSource, SERVER_TELEM_SCHEMA_VERSION, SERVER_TELEM_MAX_CUR_HEADER_BYTES, SERVER_TELEM_MAX_LAST_HEADER_BYTES, SERVER_TELEM_MAX_CACHED_ERRORS, SERVER_TELEM_CACHE_KEY, SERVER_TELEM_CATEGORY_SEPARATOR, SERVER_TELEM_VALUE_SEPARATOR, SERVER_TELEM_OVERFLOW_TRUE, SERVER_TELEM_OVERFLOW_FALSE, SERVER_TELEM_UNKNOWN_ERROR, AuthenticationScheme, DEFAULT_THROTTLE_TIME_SECONDS, DEFAULT_MAX_THROTTLE_TIME_SECONDS, THROTTLING_PREFIX, X_MS_LIB_CAPABILITY_VALUE, INVALID_GRANT_ERROR, CLIENT_MISMATCH_ERROR, PasswordGrantConstants, RegionDiscoverySources, RegionDiscoveryOutcomes, CacheOutcome, JsonWebTokenTypes, ONE_DAY_IN_MS, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes;+var init_Constants = __esm({+ "node_modules/@azure/msal-common/dist/utils/Constants.mjs"() {+ "use strict";+ SKU = "msal.js.common";+ DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/";+ DEFAULT_AUTHORITY_HOST = "login.microsoftonline.com";+ DEFAULT_COMMON_TENANT = "common";+ ADFS = "adfs";+ DSTS = "dstsv2";+ AAD_INSTANCE_DISCOVERY_ENDPT = `${DEFAULT_AUTHORITY}discovery/instance?api-version=1.1&authorization_endpoint=`;+ CIAM_AUTH_URL = ".ciamlogin.com";+ AAD_TENANT_DOMAIN_SUFFIX = ".onmicrosoft.com";+ RESOURCE_DELIM = "|";+ CONSUMER_UTID = "9188040d-6c67-4c5b-b112-36a304b66dad";+ OPENID_SCOPE = "openid";+ PROFILE_SCOPE = "profile";+ OFFLINE_ACCESS_SCOPE = "offline_access";+ EMAIL_SCOPE = "email";+ CODE_GRANT_TYPE = "authorization_code";+ S256_CODE_CHALLENGE_METHOD = "S256";+ URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";+ AUTHORIZATION_PENDING = "authorization_pending";+ NOT_APPLICABLE = "N/A";+ NOT_AVAILABLE = "Not Available";+ FORWARD_SLASH = "/";+ IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute";+ IMDS_VERSION = "2021-02-01";+ IMDS_TIMEOUT = 2e3;+ AZURE_REGION_AUTO_DISCOVER_FLAG = "TryAutoDetect";+ REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX = "login.microsoft.com";+ KNOWN_PUBLIC_CLOUDS = [+ "login.microsoftonline.com",+ "login.windows.net",+ "login.microsoft.com",+ "sts.windows.net"+ ];+ SHR_NONCE_VALIDITY = 240;+ INVALID_INSTANCE = "invalid_instance";+ HTTP_SUCCESS = 200;+ HTTP_SUCCESS_RANGE_START = 200;+ HTTP_SUCCESS_RANGE_END = 299;+ HTTP_REDIRECT = 302;+ HTTP_CLIENT_ERROR = 400;+ HTTP_CLIENT_ERROR_RANGE_START = 400;+ HTTP_BAD_REQUEST = 400;+ HTTP_UNAUTHORIZED = 401;+ HTTP_NOT_FOUND = 404;+ HTTP_REQUEST_TIMEOUT = 408;+ HTTP_GONE = 410;+ HTTP_TOO_MANY_REQUESTS = 429;+ HTTP_CLIENT_ERROR_RANGE_END = 499;+ HTTP_SERVER_ERROR = 500;+ HTTP_SERVER_ERROR_RANGE_START = 500;+ HTTP_SERVICE_UNAVAILABLE = 503;+ HTTP_GATEWAY_TIMEOUT = 504;+ HTTP_SERVER_ERROR_RANGE_END = 599;+ HTTP_MULTI_SIDED_ERROR = 600;+ HttpMethod = {+ GET: "GET",+ POST: "POST"+ };+ OIDC_DEFAULT_SCOPES = [+ OPENID_SCOPE,+ PROFILE_SCOPE,+ OFFLINE_ACCESS_SCOPE+ ];+ OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, EMAIL_SCOPE];+ HeaderNames = {+ CONTENT_TYPE: "Content-Type",+ CONTENT_LENGTH: "Content-Length",+ RETRY_AFTER: "Retry-After",+ CCS_HEADER: "X-AnchorMailbox",+ WWWAuthenticate: "WWW-Authenticate",+ AuthenticationInfo: "Authentication-Info",+ X_MS_REQUEST_ID: "x-ms-request-id",+ X_MS_HTTP_VERSION: "x-ms-httpver"+ };+ PersistentCacheKeys = {+ ACTIVE_ACCOUNT_FILTERS: "active-account-filters"+ // new cache entry for active_account for a more robust version for browser+ };+ AADAuthority = {+ COMMON: "common",+ ORGANIZATIONS: "organizations",+ CONSUMERS: "consumers"+ };+ ClaimsRequestKeys = {+ ACCESS_TOKEN: "access_token",+ XMS_CC: "xms_cc",+ ID_TOKEN: "id_token",+ SIGNIN_STATE: "signin_state",+ LOGIN_HINT: "login_hint"+ };+ PromptValue = {+ LOGIN: "login",+ SELECT_ACCOUNT: "select_account",+ CONSENT: "consent",+ NONE: "none",+ CREATE: "create",+ NO_SESSION: "no_session"+ };+ CodeChallengeMethodValues = {+ PLAIN: "plain",+ S256: "S256"+ };+ OAuthResponseType = {+ CODE: "code",+ IDTOKEN_TOKEN: "id_token token",+ IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token"+ };+ ResponseMode = {+ QUERY: "query",+ FRAGMENT: "fragment",+ FORM_POST: "form_post"+ };+ GrantType = {+ IMPLICIT_GRANT: "implicit",+ AUTHORIZATION_CODE_GRANT: "authorization_code",+ CLIENT_CREDENTIALS_GRANT: "client_credentials",+ RESOURCE_OWNER_PASSWORD_GRANT: "password",+ REFRESH_TOKEN_GRANT: "refresh_token",+ DEVICE_CODE_GRANT: "device_code",+ JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer",+ USER_FIC: "user_fic"+ };+ CACHE_ACCOUNT_TYPE_MSSTS = "MSSTS";+ CACHE_ACCOUNT_TYPE_ADFS = "ADFS";+ CACHE_ACCOUNT_TYPE_MSAV1 = "MSA";+ CACHE_ACCOUNT_TYPE_GENERIC = "Generic";+ CACHE_KEY_SEPARATOR = "-";+ CLIENT_INFO_SEPARATOR = ".";+ CredentialType = {+ ID_TOKEN: "IdToken",+ ACCESS_TOKEN: "AccessToken",+ ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme",+ REFRESH_TOKEN: "RefreshToken"+ };+ CacheType = {+ ADFS: 1001,+ MSA: 1002,+ MSSTS: 1003,+ GENERIC: 1004,+ ACCESS_TOKEN: 2001,+ REFRESH_TOKEN: 2002,+ ID_TOKEN: 2003,+ APP_METADATA: 3001,+ UNDEFINED: 9999+ };+ APP_METADATA = "appmetadata";+ CLIENT_INFO = "client_info";+ THE_FAMILY_ID = "1";+ AUTHORITY_METADATA_CACHE_KEY = "authority-metadata";+ AUTHORITY_METADATA_REFRESH_TIME_SECONDS = 3600 * 24;+ AuthorityMetadataSource = {+ CONFIG: "config",+ CACHE: "cache",+ NETWORK: "network",+ HARDCODED_VALUES: "hardcoded_values"+ };+ SERVER_TELEM_SCHEMA_VERSION = 5;+ SERVER_TELEM_MAX_CUR_HEADER_BYTES = 80;+ SERVER_TELEM_MAX_LAST_HEADER_BYTES = 330;+ SERVER_TELEM_MAX_CACHED_ERRORS = 50;+ SERVER_TELEM_CACHE_KEY = "server-telemetry";+ SERVER_TELEM_CATEGORY_SEPARATOR = "|";+ SERVER_TELEM_VALUE_SEPARATOR = ",";+ SERVER_TELEM_OVERFLOW_TRUE = "1";+ SERVER_TELEM_OVERFLOW_FALSE = "0";+ SERVER_TELEM_UNKNOWN_ERROR = "unknown_error";+ AuthenticationScheme = {+ BEARER: "Bearer",+ POP: "pop",+ SSH: "ssh-cert"+ };+ DEFAULT_THROTTLE_TIME_SECONDS = 60;+ DEFAULT_MAX_THROTTLE_TIME_SECONDS = 3600;+ THROTTLING_PREFIX = "throttling";+ X_MS_LIB_CAPABILITY_VALUE = "retry-after, h429";+ INVALID_GRANT_ERROR = "invalid_grant";+ CLIENT_MISMATCH_ERROR = "client_mismatch";+ PasswordGrantConstants = {+ username: "username",+ password: "password"+ };+ RegionDiscoverySources = {+ FAILED_AUTO_DETECTION: "1",+ INTERNAL_CACHE: "2",+ ENVIRONMENT_VARIABLE: "3",+ IMDS: "4"+ };+ RegionDiscoveryOutcomes = {+ CONFIGURED_MATCHES_DETECTED: "1",+ CONFIGURED_NO_AUTO_DETECTION: "2",+ CONFIGURED_NOT_DETECTED: "3",+ AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4",+ AUTO_DETECTION_REQUESTED_FAILED: "5"+ };+ CacheOutcome = {+ // When a token is found in the cache or the cache is not supposed to be hit when making the request+ NOT_APPLICABLE: "0",+ // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested+ FORCE_REFRESH_OR_CLAIMS: "1",+ // When the token request goes to the identity provider because no cached access token exists+ NO_CACHED_ACCESS_TOKEN: "2",+ // When the token request goes to the identity provider because cached access token expired+ CACHED_ACCESS_TOKEN_EXPIRED: "3",+ // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed+ PROACTIVELY_REFRESHED: "4"+ };+ JsonWebTokenTypes = {+ Jwt: "JWT",+ Jwk: "JWK",+ Pop: "pop"+ };+ ONE_DAY_IN_MS = 864e5;+ DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;+ EncodingTypes = {+ BASE64: "base64",+ HEX: "hex",+ UTF8: "utf-8"+ };+ }+});++// node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs+var AADServerParamKeys_exports = {};+__export(AADServerParamKeys_exports, {+ ACCESS_TOKEN: () => ACCESS_TOKEN,+ BROKER_CLIENT_ID: () => BROKER_CLIENT_ID,+ BROKER_REDIRECT_URI: () => BROKER_REDIRECT_URI,+ CCS_HEADER: () => CCS_HEADER,+ CLAIMS: () => CLAIMS,+ CLIENT_ASSERTION: () => CLIENT_ASSERTION,+ CLIENT_ASSERTION_TYPE: () => CLIENT_ASSERTION_TYPE,+ CLIENT_ID: () => CLIENT_ID,+ CLIENT_INFO: () => CLIENT_INFO2,+ CLIENT_REQUEST_ID: () => CLIENT_REQUEST_ID,+ CLIENT_SECRET: () => CLIENT_SECRET,+ CLI_DATA: () => CLI_DATA,+ CODE: () => CODE,+ CODE_CHALLENGE: () => CODE_CHALLENGE,+ CODE_CHALLENGE_METHOD: () => CODE_CHALLENGE_METHOD,+ CODE_VERIFIER: () => CODE_VERIFIER,+ DEVICE_CODE: () => DEVICE_CODE,+ DOMAIN_HINT: () => DOMAIN_HINT,+ EAR_JWE_CRYPTO: () => EAR_JWE_CRYPTO,+ EAR_JWK: () => EAR_JWK,+ ERROR: () => ERROR,+ ERROR_DESCRIPTION: () => ERROR_DESCRIPTION,+ EXPIRES_IN: () => EXPIRES_IN,+ FMI_PATH: () => FMI_PATH,+ FOCI: () => FOCI,+ GRANT_TYPE: () => GRANT_TYPE,+ ID_TOKEN: () => ID_TOKEN,+ ID_TOKEN_HINT: () => ID_TOKEN_HINT,+ INSTANCE_AWARE: () => INSTANCE_AWARE,+ LOGIN_HINT: () => LOGIN_HINT,+ LOGOUT_HINT: () => LOGOUT_HINT,+ NATIVE_BROKER: () => NATIVE_BROKER,+ NONCE: () => NONCE,+ OBO_ASSERTION: () => OBO_ASSERTION,+ ON_BEHALF_OF: () => ON_BEHALF_OF,+ POST_LOGOUT_URI: () => POST_LOGOUT_URI,+ PROMPT: () => PROMPT,+ REDIRECT_URI: () => REDIRECT_URI,+ REFRESH_TOKEN: () => REFRESH_TOKEN,+ REFRESH_TOKEN_EXPIRES_IN: () => REFRESH_TOKEN_EXPIRES_IN,+ REQUESTED_TOKEN_USE: () => REQUESTED_TOKEN_USE,+ REQ_CNF: () => REQ_CNF,+ RESOURCE: () => RESOURCE,+ RESPONSE_MODE: () => RESPONSE_MODE,+ RESPONSE_TYPE: () => RESPONSE_TYPE,+ RETURN_SPA_CODE: () => RETURN_SPA_CODE,+ SCOPE: () => SCOPE,+ SESSION_STATE: () => SESSION_STATE,+ SID: () => SID,+ STATE: () => STATE,+ TOKEN_TYPE: () => TOKEN_TYPE,+ USERNAME: () => USERNAME,+ USER_FEDERATED_IDENTITY_CREDENTIAL: () => USER_FEDERATED_IDENTITY_CREDENTIAL,+ USER_ID: () => USER_ID,+ X_APP_NAME: () => X_APP_NAME,+ X_APP_VER: () => X_APP_VER,+ X_CLIENT_CPU: () => X_CLIENT_CPU,+ X_CLIENT_CURR_TELEM: () => X_CLIENT_CURR_TELEM,+ X_CLIENT_EXTRA_SKU: () => X_CLIENT_EXTRA_SKU,+ X_CLIENT_LAST_TELEM: () => X_CLIENT_LAST_TELEM,+ X_CLIENT_OS: () => X_CLIENT_OS,+ X_CLIENT_SKU: () => X_CLIENT_SKU,+ X_CLIENT_VER: () => X_CLIENT_VER,+ X_MS_LIB_CAPABILITY: () => X_MS_LIB_CAPABILITY+});+var CLIENT_ID, REDIRECT_URI, RESPONSE_TYPE, RESPONSE_MODE, GRANT_TYPE, CLAIMS, SCOPE, ERROR, ERROR_DESCRIPTION, ACCESS_TOKEN, ID_TOKEN, REFRESH_TOKEN, EXPIRES_IN, REFRESH_TOKEN_EXPIRES_IN, STATE, NONCE, PROMPT, SESSION_STATE, CLIENT_INFO2, CODE, CODE_CHALLENGE, CODE_CHALLENGE_METHOD, CODE_VERIFIER, CLIENT_REQUEST_ID, X_CLIENT_SKU, X_CLIENT_VER, X_CLIENT_OS, X_CLIENT_CPU, X_CLIENT_CURR_TELEM, X_CLIENT_LAST_TELEM, X_MS_LIB_CAPABILITY, X_APP_NAME, X_APP_VER, POST_LOGOUT_URI, ID_TOKEN_HINT, DEVICE_CODE, CLIENT_SECRET, CLIENT_ASSERTION, CLIENT_ASSERTION_TYPE, TOKEN_TYPE, REQ_CNF, OBO_ASSERTION, REQUESTED_TOKEN_USE, ON_BEHALF_OF, FOCI, CCS_HEADER, RETURN_SPA_CODE, NATIVE_BROKER, LOGOUT_HINT, SID, LOGIN_HINT, DOMAIN_HINT, X_CLIENT_EXTRA_SKU, BROKER_CLIENT_ID, BROKER_REDIRECT_URI, INSTANCE_AWARE, EAR_JWK, EAR_JWE_CRYPTO, RESOURCE, CLI_DATA, USER_FEDERATED_IDENTITY_CREDENTIAL, USERNAME, USER_ID, FMI_PATH;+var init_AADServerParamKeys = __esm({+ "node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs"() {+ "use strict";+ CLIENT_ID = "client_id";+ REDIRECT_URI = "redirect_uri";+ RESPONSE_TYPE = "response_type";+ RESPONSE_MODE = "response_mode";+ GRANT_TYPE = "grant_type";+ CLAIMS = "claims";+ SCOPE = "scope";+ ERROR = "error";+ ERROR_DESCRIPTION = "error_description";+ ACCESS_TOKEN = "access_token";+ ID_TOKEN = "id_token";+ REFRESH_TOKEN = "refresh_token";+ EXPIRES_IN = "expires_in";+ REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in";+ STATE = "state";+ NONCE = "nonce";+ PROMPT = "prompt";+ SESSION_STATE = "session_state";+ CLIENT_INFO2 = "client_info";+ CODE = "code";+ CODE_CHALLENGE = "code_challenge";+ CODE_CHALLENGE_METHOD = "code_challenge_method";+ CODE_VERIFIER = "code_verifier";+ CLIENT_REQUEST_ID = "client-request-id";+ X_CLIENT_SKU = "x-client-SKU";+ X_CLIENT_VER = "x-client-VER";+ X_CLIENT_OS = "x-client-OS";+ X_CLIENT_CPU = "x-client-CPU";+ X_CLIENT_CURR_TELEM = "x-client-current-telemetry";+ X_CLIENT_LAST_TELEM = "x-client-last-telemetry";+ X_MS_LIB_CAPABILITY = "x-ms-lib-capability";+ X_APP_NAME = "x-app-name";+ X_APP_VER = "x-app-ver";+ POST_LOGOUT_URI = "post_logout_redirect_uri";+ ID_TOKEN_HINT = "id_token_hint";+ DEVICE_CODE = "device_code";+ CLIENT_SECRET = "client_secret";+ CLIENT_ASSERTION = "client_assertion";+ CLIENT_ASSERTION_TYPE = "client_assertion_type";+ TOKEN_TYPE = "token_type";+ REQ_CNF = "req_cnf";+ OBO_ASSERTION = "assertion";+ REQUESTED_TOKEN_USE = "requested_token_use";+ ON_BEHALF_OF = "on_behalf_of";+ FOCI = "foci";+ CCS_HEADER = "X-AnchorMailbox";+ RETURN_SPA_CODE = "return_spa_code";+ NATIVE_BROKER = "nativebroker";+ LOGOUT_HINT = "logout_hint";+ SID = "sid";+ LOGIN_HINT = "login_hint";+ DOMAIN_HINT = "domain_hint";+ X_CLIENT_EXTRA_SKU = "x-client-xtra-sku";+ BROKER_CLIENT_ID = "brk_client_id";+ BROKER_REDIRECT_URI = "brk_redirect_uri";+ INSTANCE_AWARE = "instance_aware";+ EAR_JWK = "ear_jwk";+ EAR_JWE_CRYPTO = "ear_jwe_crypto";+ RESOURCE = "resource";+ CLI_DATA = "clidata";+ USER_FEDERATED_IDENTITY_CREDENTIAL = "user_federated_identity_credential";+ USERNAME = "username";+ USER_ID = "user_id";+ FMI_PATH = "fmi_path";+ }+});++// node_modules/@azure/msal-common/dist/error/AuthError.mjs+function getDefaultErrorMessage(code) {+ return `See https://aka.ms/msal.js.errors#${code} for details`;+}+function createAuthError(code, correlationId, additionalMessage) {+ return new AuthError(code, correlationId, additionalMessage || getDefaultErrorMessage(code));+}+var AuthError;+var init_AuthError = __esm({+ "node_modules/@azure/msal-common/dist/error/AuthError.mjs"() {+ "use strict";+ AuthError = class _AuthError extends Error {+ constructor(errorCode, correlationId, errorMessage, suberror) {+ const message = errorMessage || (errorCode ? getDefaultErrorMessage(errorCode) : "");+ const errorString = message ? `${errorCode}: ${message}` : errorCode;+ super(errorString);+ Object.setPrototypeOf(this, _AuthError.prototype);+ this.errorCode = errorCode || "";+ this.errorMessage = message || "";+ this.subError = suberror || "";+ this.correlationId = correlationId;+ this.name = "AuthError";+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs+function createClientConfigurationError(errorCode, correlationId) {+ return new ClientConfigurationError(errorCode, correlationId);+}+var ClientConfigurationError;+var init_ClientConfigurationError = __esm({+ "node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs"() {+ "use strict";+ init_AuthError();+ ClientConfigurationError = class _ClientConfigurationError extends AuthError {+ constructor(errorCode, correlationId) {+ super(errorCode, correlationId);+ this.name = "ClientConfigurationError";+ Object.setPrototypeOf(this, _ClientConfigurationError.prototype);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/StringUtils.mjs+var StringUtils;+var init_StringUtils = __esm({+ "node_modules/@azure/msal-common/dist/utils/StringUtils.mjs"() {+ "use strict";+ StringUtils = class {+ /**+ * Check if stringified object is empty+ * @param strObj+ */+ static isEmptyObj(strObj) {+ if (strObj) {+ try {+ const obj = JSON.parse(strObj);+ return Object.keys(obj).length === 0;+ } catch (e) {+ }+ }+ return true;+ }+ static startsWith(str, search) {+ return str.indexOf(search) === 0;+ }+ static endsWith(str, search) {+ return str.length >= search.length && str.lastIndexOf(search) === str.length - search.length;+ }+ /**+ * Parses string into an object.+ *+ * @param query+ */+ static queryStringToObject(query) {+ const obj = {};+ const params = query.split("&");+ const decode = (s) => decodeURIComponent(s.replace(/\+/g, " "));+ params.forEach((pair) => {+ if (pair.trim()) {+ const [key, value] = pair.split(/=(.+)/g, 2);+ if (key && value) {+ obj[decode(key)] = decode(value);+ }+ }+ });+ return obj;+ }+ /**+ * Trims entries in an array.+ *+ * @param arr+ */+ static trimArrayEntries(arr) {+ return arr.map((entry) => entry.trim());+ }+ /**+ * Removes empty strings from array+ * @param arr+ */+ static removeEmptyStringsFromArray(arr) {+ return arr.filter((entry) => {+ return !!entry;+ });+ }+ /**+ * Attempts to parse a string into JSON+ * @param str+ */+ static jsonParseHelper(str) {+ try {+ return JSON.parse(str);+ } catch (e) {+ return null;+ }+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs+function createClientAuthError(errorCode, correlationId, additionalMessage) {+ return new ClientAuthError(errorCode, correlationId, additionalMessage);+}+var ClientAuthError;+var init_ClientAuthError = __esm({+ "node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs"() {+ "use strict";+ init_AuthError();+ ClientAuthError = class _ClientAuthError extends AuthError {+ constructor(errorCode, correlationId, additionalMessage) {+ super(errorCode, correlationId, additionalMessage);+ this.name = "ClientAuthError";+ Object.setPrototypeOf(this, _ClientAuthError.prototype);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs+var redirectUriEmpty, authorityUriInsecure, urlParseError, urlEmptyError, emptyInputScopesError, invalidClaims, tokenRequestEmpty, logoutRequestEmpty, pkceParamsMissing, invalidCloudDiscoveryMetadata, invalidAuthorityMetadata, untrustedAuthority, missingSshJwk, issuerValidationFailed;+var init_ClientConfigurationErrorCodes = __esm({+ "node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs"() {+ "use strict";+ redirectUriEmpty = "redirect_uri_empty";+ authorityUriInsecure = "authority_uri_insecure";+ urlParseError = "url_parse_error";+ urlEmptyError = "empty_url_error";+ emptyInputScopesError = "empty_input_scopes_error";+ invalidClaims = "invalid_claims";+ tokenRequestEmpty = "token_request_empty";+ logoutRequestEmpty = "logout_request_empty";+ pkceParamsMissing = "pkce_params_missing";+ invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata";+ invalidAuthorityMetadata = "invalid_authority_metadata";+ untrustedAuthority = "untrusted_authority";+ missingSshJwk = "missing_ssh_jwk";+ issuerValidationFailed = "issuer_validation_failed";+ }+});++// node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs+var ClientAuthErrorCodes_exports = {};+__export(ClientAuthErrorCodes_exports, {+ authorizationCodeMissingFromServerResponse: () => authorizationCodeMissingFromServerResponse,+ bindingKeyNotRemoved: () => bindingKeyNotRemoved,+ cannotAppendScopeSet: () => cannotAppendScopeSet,+ cannotRemoveEmptyScope: () => cannotRemoveEmptyScope,+ clientInfoDecodingError: () => clientInfoDecodingError,+ clientInfoEmptyError: () => clientInfoEmptyError,+ emptyInputScopeSet: () => emptyInputScopeSet,+ endSessionEndpointNotSupported: () => endSessionEndpointNotSupported,+ endpointResolutionError: () => endpointResolutionError,+ hashNotDeserialized: () => hashNotDeserialized,+ invalidCacheEnvironment: () => invalidCacheEnvironment,+ invalidCacheRecord: () => invalidCacheRecord,+ invalidState: () => invalidState,+ keyIdMissing: () => keyIdMissing,+ methodNotImplemented: () => methodNotImplemented,+ misplacedResourceParam: () => misplacedResourceParam,+ multipleMatchingAppMetadata: () => multipleMatchingAppMetadata,+ multipleMatchingTokens: () => multipleMatchingTokens,+ nestedAppAuthBridgeDisabled: () => nestedAppAuthBridgeDisabled,+ networkError: () => networkError,+ noAccountFound: () => noAccountFound,+ noAccountInSilentRequest: () => noAccountInSilentRequest,+ noCryptoObject: () => noCryptoObject,+ noNetworkConnectivity: () => noNetworkConnectivity,+ nonceMismatch: () => nonceMismatch,+ nullOrEmptyToken: () => nullOrEmptyToken,+ openIdConfigError: () => openIdConfigError,+ platformBrokerError: () => platformBrokerError,+ requestCannotBeMade: () => requestCannotBeMade,+ resourceParameterRequired: () => resourceParameterRequired,+ stateMismatch: () => stateMismatch,+ stateNotFound: () => stateNotFound,+ tokenClaimsCnfRequiredForSignedJwt: () => tokenClaimsCnfRequiredForSignedJwt,+ tokenParsingError: () => tokenParsingError,+ tokenRefreshRequired: () => tokenRefreshRequired,+ unexpectedCredentialType: () => unexpectedCredentialType,+ userCanceled: () => userCanceled+});+var clientInfoDecodingError, clientInfoEmptyError, tokenParsingError, nullOrEmptyToken, endpointResolutionError, networkError, openIdConfigError, hashNotDeserialized, invalidState, stateMismatch, stateNotFound, nonceMismatch, multipleMatchingTokens, multipleMatchingAppMetadata, requestCannotBeMade, cannotRemoveEmptyScope, cannotAppendScopeSet, emptyInputScopeSet, noAccountInSilentRequest, invalidCacheRecord, invalidCacheEnvironment, noAccountFound, noCryptoObject, unexpectedCredentialType, tokenRefreshRequired, tokenClaimsCnfRequiredForSignedJwt, authorizationCodeMissingFromServerResponse, bindingKeyNotRemoved, endSessionEndpointNotSupported, keyIdMissing, noNetworkConnectivity, userCanceled, methodNotImplemented, nestedAppAuthBridgeDisabled, platformBrokerError, resourceParameterRequired, misplacedResourceParam;+var init_ClientAuthErrorCodes = __esm({+ "node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs"() {+ "use strict";+ clientInfoDecodingError = "client_info_decoding_error";+ clientInfoEmptyError = "client_info_empty_error";+ tokenParsingError = "token_parsing_error";+ nullOrEmptyToken = "null_or_empty_token";+ endpointResolutionError = "endpoints_resolution_error";+ networkError = "network_error";+ openIdConfigError = "openid_config_error";+ hashNotDeserialized = "hash_not_deserialized";+ invalidState = "invalid_state";+ stateMismatch = "state_mismatch";+ stateNotFound = "state_not_found";+ nonceMismatch = "nonce_mismatch";+ multipleMatchingTokens = "multiple_matching_tokens";+ multipleMatchingAppMetadata = "multiple_matching_appMetadata";+ requestCannotBeMade = "request_cannot_be_made";+ cannotRemoveEmptyScope = "cannot_remove_empty_scope";+ cannotAppendScopeSet = "cannot_append_scopeset";+ emptyInputScopeSet = "empty_input_scopeset";+ noAccountInSilentRequest = "no_account_in_silent_request";+ invalidCacheRecord = "invalid_cache_record";+ invalidCacheEnvironment = "invalid_cache_environment";+ noAccountFound = "no_account_found";+ noCryptoObject = "no_crypto_object";+ unexpectedCredentialType = "unexpected_credential_type";+ tokenRefreshRequired = "token_refresh_required";+ tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt";+ authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response";+ bindingKeyNotRemoved = "binding_key_not_removed";+ endSessionEndpointNotSupported = "end_session_endpoint_not_supported";+ keyIdMissing = "key_id_missing";+ noNetworkConnectivity = "no_network_connectivity";+ userCanceled = "user_canceled";+ methodNotImplemented = "method_not_implemented";+ nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled";+ platformBrokerError = "platform_broker_error";+ resourceParameterRequired = "resource_parameter_required";+ misplacedResourceParam = "misplaced_resource_parameter";+ }+});++// node_modules/@azure/msal-common/dist/request/ScopeSet.mjs+var ScopeSet;+var init_ScopeSet = __esm({+ "node_modules/@azure/msal-common/dist/request/ScopeSet.mjs"() {+ "use strict";+ init_ClientConfigurationError();+ init_StringUtils();+ init_ClientAuthError();+ init_Constants();+ init_ClientConfigurationErrorCodes();+ init_ClientAuthErrorCodes();+ ScopeSet = class _ScopeSet {+ constructor(inputScopes, correlationId) {+ this.correlationId = correlationId;+ const scopeArr = inputScopes ? StringUtils.trimArrayEntries([...inputScopes]) : [];+ const filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : [];+ if (!filteredInput || !filteredInput.length) {+ throw createClientConfigurationError(emptyInputScopesError, correlationId);+ }+ this.scopes = /* @__PURE__ */ new Set();+ filteredInput.forEach((scope) => this.scopes.add(scope));+ }+ /**+ * Factory method to create ScopeSet from space-delimited string+ * @param inputScopeString+ * @param appClientId+ * @param scopesRequired+ */+ static fromString(inputScopeString, correlationId) {+ const scopeString = inputScopeString || "";+ const inputScopes = scopeString.split(" ");+ return new _ScopeSet(inputScopes, correlationId);+ }+ /**+ * Creates the set of scopes to search for in cache lookups+ * @param inputScopeString+ * @returns+ */+ static createSearchScopes(inputScopeString, correlationId) {+ const scopesToUse = inputScopeString && inputScopeString.length > 0 ? inputScopeString : [...OIDC_DEFAULT_SCOPES];+ const scopeSet = new _ScopeSet(scopesToUse, correlationId);+ if (!scopeSet.containsOnlyOIDCScopes()) {+ scopeSet.removeOIDCScopes();+ } else {+ scopeSet.removeScope(OFFLINE_ACCESS_SCOPE);+ }+ return scopeSet;+ }+ /**+ * Check if a given scope is present in this set of scopes.+ * @param scope+ */+ containsScope(scope) {+ const lowerCaseScopes = this.printScopesLowerCase().split(" ");+ const lowerCaseScopesSet = new _ScopeSet(lowerCaseScopes, this.correlationId);+ return scope ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false;+ }+ /**+ * Check if a set of scopes is present in this set of scopes.+ * @param scopeSet+ */+ containsScopeSet(scopeSet) {+ if (!scopeSet || scopeSet.scopes.size <= 0) {+ return false;+ }+ return this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every((scope) => this.containsScope(scope));+ }+ /**+ * Check if set of scopes contains only the defaults+ */+ containsOnlyOIDCScopes() {+ let defaultScopeCount = 0;+ OIDC_SCOPES.forEach((defaultScope) => {+ if (this.containsScope(defaultScope)) {+ defaultScopeCount += 1;+ }+ });+ return this.scopes.size === defaultScopeCount;+ }+ /**+ * Appends single scope if passed+ * @param newScope+ */+ appendScope(newScope) {+ if (newScope) {+ this.scopes.add(newScope.trim());+ }+ }+ /**+ * Appends multiple scopes if passed+ * @param newScopes+ */+ appendScopes(newScopes) {+ try {+ newScopes.forEach((newScope) => this.appendScope(newScope));+ } catch (e) {+ throw createClientAuthError(cannotAppendScopeSet, this.correlationId);+ }+ }+ /**+ * Removes element from set of scopes.+ * @param scope+ */+ removeScope(scope) {+ if (!scope) {+ throw createClientAuthError(cannotRemoveEmptyScope, this.correlationId);+ }+ this.scopes.delete(scope.trim());+ }+ /**+ * Removes default scopes from set of scopes+ * Primarily used to prevent cache misses if the default scopes are not returned from the server+ */+ removeOIDCScopes() {+ OIDC_SCOPES.forEach((defaultScope) => {+ this.scopes.delete(defaultScope);+ });+ }+ /**+ * Combines an array of scopes with the current set of scopes.+ * @param otherScopes+ */+ unionScopeSets(otherScopes) {+ if (!otherScopes) {+ throw createClientAuthError(emptyInputScopeSet, this.correlationId);+ }+ const unionScopes = /* @__PURE__ */ new Set();+ otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));+ this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));+ return unionScopes;+ }+ /**+ * Check if scopes intersect between this set and another.+ * @param otherScopes+ */+ intersectingScopeSets(otherScopes) {+ if (!otherScopes) {+ throw createClientAuthError(emptyInputScopeSet, this.correlationId);+ }+ if (!otherScopes.containsOnlyOIDCScopes()) {+ otherScopes.removeOIDCScopes();+ }+ const unionScopes = this.unionScopeSets(otherScopes);+ const sizeOtherScopes = otherScopes.getScopeCount();+ const sizeThisScopes = this.getScopeCount();+ const sizeUnionScopes = unionScopes.size;+ return sizeUnionScopes < sizeThisScopes + sizeOtherScopes;+ }+ /**+ * Returns size of set of scopes.+ */+ getScopeCount() {+ return this.scopes.size;+ }+ /**+ * Returns the scopes as an array of string values+ */+ asArray() {+ const array2 = [];+ this.scopes.forEach((val) => array2.push(val));+ return array2;+ }+ /**+ * Prints scopes into a space-delimited string+ */+ printScopes() {+ if (this.scopes) {+ const scopeArr = this.asArray();+ return scopeArr.join(" ");+ }+ return "";+ }+ /**+ * Prints scopes into a space-delimited lower-case string (used for caching)+ */+ printScopesLowerCase() {+ return this.printScopes().toLowerCase();+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs+var RequestParameterBuilder_exports = {};+__export(RequestParameterBuilder_exports, {+ addApplicationTelemetry: () => addApplicationTelemetry,+ addAuthorizationCode: () => addAuthorizationCode,+ addBrokerParameters: () => addBrokerParameters,+ addCcsOid: () => addCcsOid,+ addCcsUpn: () => addCcsUpn,+ addClaims: () => addClaims,+ addCliData: () => addCliData,+ addClientAssertion: () => addClientAssertion,+ addClientAssertionType: () => addClientAssertionType,+ addClientId: () => addClientId,+ addClientInfo: () => addClientInfo,+ addClientSecret: () => addClientSecret,+ addCodeChallengeParams: () => addCodeChallengeParams,+ addCodeVerifier: () => addCodeVerifier,+ addCorrelationId: () => addCorrelationId,+ addDeviceCode: () => addDeviceCode,+ addDomainHint: () => addDomainHint,+ addEARParameters: () => addEARParameters,+ addExtraParameters: () => addExtraParameters,+ addGrantType: () => addGrantType,+ addIdTokenHint: () => addIdTokenHint,+ addInstanceAware: () => addInstanceAware,+ addLibraryInfo: () => addLibraryInfo,+ addLoginHint: () => addLoginHint,+ addLogoutHint: () => addLogoutHint,+ addNativeBroker: () => addNativeBroker,+ addNonce: () => addNonce,+ addOboAssertion: () => addOboAssertion,+ addPassword: () => addPassword,+ addPopToken: () => addPopToken,+ addPostLogoutRedirectUri: () => addPostLogoutRedirectUri,+ addPrompt: () => addPrompt,+ addRedirectUri: () => addRedirectUri,+ addRefreshToken: () => addRefreshToken,+ addRequestTokenUse: () => addRequestTokenUse,+ addResource: () => addResource,+ addResponseMode: () => addResponseMode,+ addResponseType: () => addResponseType,+ addScopes: () => addScopes,+ addServerTelemetry: () => addServerTelemetry,+ addSid: () => addSid,+ addSshJwk: () => addSshJwk,+ addState: () => addState,+ addThrottling: () => addThrottling,+ addUsername: () => addUsername,+ buildMergedClaims: () => buildMergedClaims,+ instrumentBrokerParams: () => instrumentBrokerParams+});+function instrumentBrokerParams(parameters, correlationId, performanceClient) {+ if (!correlationId) {+ return;+ }+ const clientId = parameters.get(CLIENT_ID);+ if (clientId && parameters.has(BROKER_CLIENT_ID)) {+ performanceClient?.addFields({+ embeddedClientId: clientId,+ embeddedRedirectUri: parameters.get(REDIRECT_URI)+ }, correlationId);+ }+}+function addResponseType(parameters, responseType) {+ parameters.set(RESPONSE_TYPE, responseType);+}+function addResponseMode(parameters, responseMode) {+ parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode.QUERY);+}+function addNativeBroker(parameters) {+ parameters.set(NATIVE_BROKER, "1");+}+function addScopes(parameters, scopes, correlationId, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) {+ if (addOidcScopes && !defaultScopes.includes("openid") && !scopes.includes("openid")) {+ defaultScopes.push("openid");+ }+ const requestScopes = addOidcScopes ? [...scopes || [], ...defaultScopes] : scopes || [];+ const scopeSet = new ScopeSet(requestScopes, correlationId);+ parameters.set(SCOPE, scopeSet.printScopes());+}+function addClientId(parameters, clientId) {+ parameters.set(CLIENT_ID, clientId);+}+function addRedirectUri(parameters, redirectUri) {+ parameters.set(REDIRECT_URI, redirectUri);+}+function addPostLogoutRedirectUri(parameters, redirectUri) {+ parameters.set(POST_LOGOUT_URI, redirectUri);+}+function addIdTokenHint(parameters, idTokenHint) {+ parameters.set(ID_TOKEN_HINT, idTokenHint);+}+function addDomainHint(parameters, domainHint) {+ parameters.set(DOMAIN_HINT, domainHint);+}+function addLoginHint(parameters, loginHint) {+ parameters.set(LOGIN_HINT, loginHint);+}+function addCcsUpn(parameters, loginHint) {+ parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`);+}+function addCcsOid(parameters, clientInfo) {+ parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`);+}+function addSid(parameters, sid) {+ parameters.set(SID, sid);+}+function addClaims(parameters, correlationId, claims, clientCapabilities, skipBrokerClaims) {+ const configClaims = skipBrokerClaims && parameters.has(BROKER_CLIENT_ID) ? void 0 : clientCapabilities;+ const mergedClaims = buildMergedClaims(claims, configClaims, correlationId);+ parameters.set(CLAIMS, mergedClaims);+}+function addCorrelationId(parameters, correlationId) {+ parameters.set(CLIENT_REQUEST_ID, correlationId);+}+function addLibraryInfo(parameters, libraryInfo) {+ parameters.set(X_CLIENT_SKU, libraryInfo.sku);+ parameters.set(X_CLIENT_VER, libraryInfo.version);+ if (libraryInfo.os) {+ parameters.set(X_CLIENT_OS, libraryInfo.os);+ }+ if (libraryInfo.cpu) {+ parameters.set(X_CLIENT_CPU, libraryInfo.cpu);+ }+}+function addApplicationTelemetry(parameters, appTelemetry) {+ if (appTelemetry?.appName) {+ parameters.set(X_APP_NAME, appTelemetry.appName);+ }+ if (appTelemetry?.appVersion) {+ parameters.set(X_APP_VER, appTelemetry.appVersion);+ }+}+function addPrompt(parameters, prompt) {+ parameters.set(PROMPT, prompt);+}+function addState(parameters, state) {+ if (state) {+ parameters.set(STATE, state);+ }+}+function addNonce(parameters, nonce) {+ parameters.set(NONCE, nonce);+}+function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) {+ if (codeChallenge && codeChallengeMethod) {+ parameters.set(CODE_CHALLENGE, codeChallenge);+ parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod);+ } else {+ throw createClientConfigurationError(pkceParamsMissing, "");+ }+}+function addAuthorizationCode(parameters, code) {+ parameters.set(CODE, code);+}+function addDeviceCode(parameters, code) {+ parameters.set(DEVICE_CODE, code);+}+function addRefreshToken(parameters, refreshToken) {+ parameters.set(REFRESH_TOKEN, refreshToken);+}+function addCodeVerifier(parameters, codeVerifier) {+ parameters.set(CODE_VERIFIER, codeVerifier);+}+function addClientSecret(parameters, clientSecret) {+ parameters.set(CLIENT_SECRET, clientSecret);+}+function addClientAssertion(parameters, clientAssertion) {+ if (clientAssertion) {+ parameters.set(CLIENT_ASSERTION, clientAssertion);+ }+}+function addClientAssertionType(parameters, clientAssertionType) {+ if (clientAssertionType) {+ parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType);+ }+}+function addOboAssertion(parameters, oboAssertion) {+ parameters.set(OBO_ASSERTION, oboAssertion);+}+function addRequestTokenUse(parameters, tokenUse) {+ parameters.set(REQUESTED_TOKEN_USE, tokenUse);+}+function addGrantType(parameters, grantType) {+ parameters.set(GRANT_TYPE, grantType);+}+function addClientInfo(parameters) {+ parameters.set(CLIENT_INFO, "1");+}+function addCliData(parameters) {+ parameters.set(CLI_DATA, "1");+}+function addInstanceAware(parameters) {+ if (!parameters.has(INSTANCE_AWARE)) {+ parameters.set(INSTANCE_AWARE, "true");+ }+}+function addExtraParameters(parameters, extraParams) {+ Object.entries(extraParams).forEach(([key, value]) => {+ if (!parameters.has(key) && value) {+ parameters.set(key, value);+ }+ });+}+function buildMergedClaims(claims, clientCapabilities, correlationId = "") {+ let mergedClaims;+ if (!claims) {+ mergedClaims = {};+ } else {+ try {+ const parsed = JSON.parse(claims);+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {+ throw new Error("Claims must be a JSON object");+ }+ mergedClaims = parsed;+ } catch (e) {+ throw createClientConfigurationError(invalidClaims, correlationId);+ }+ }+ if (!Object.prototype.hasOwnProperty.call(mergedClaims, ClaimsRequestKeys.ID_TOKEN)) {+ mergedClaims[ClaimsRequestKeys.ID_TOKEN] = {};+ }+ const idTokenClaims = mergedClaims[ClaimsRequestKeys.ID_TOKEN];+ for (const [key, value] of Object.entries(DEFAULT_ID_TOKEN_CLAIMS)) {+ if (!(key in idTokenClaims)) {+ idTokenClaims[key] = value;+ }+ }+ if (clientCapabilities && clientCapabilities.length > 0) {+ if (!Object.prototype.hasOwnProperty.call(mergedClaims, ClaimsRequestKeys.ACCESS_TOKEN)) {+ mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {};+ }+ mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = {+ values: clientCapabilities+ };+ }+ return JSON.stringify(mergedClaims);+}+function addUsername(parameters, username) {+ parameters.set(PasswordGrantConstants.username, username);+}+function addPassword(parameters, password) {+ parameters.set(PasswordGrantConstants.password, password);+}+function addPopToken(parameters, cnfString) {+ if (cnfString) {+ parameters.set(TOKEN_TYPE, AuthenticationScheme.POP);+ parameters.set(REQ_CNF, cnfString);+ }+}+function addSshJwk(parameters, sshJwkString) {+ if (sshJwkString) {+ parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH);+ parameters.set(REQ_CNF, sshJwkString);+ }+}+function addServerTelemetry(parameters, serverTelemetryManager) {+ parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue());+ parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue());+}+function addThrottling(parameters) {+ parameters.set(X_MS_LIB_CAPABILITY, X_MS_LIB_CAPABILITY_VALUE);+}+function addLogoutHint(parameters, logoutHint) {+ parameters.set(LOGOUT_HINT, logoutHint);+}+function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) {+ if (!parameters.has(BROKER_CLIENT_ID)) {+ parameters.set(BROKER_CLIENT_ID, brokerClientId);+ }+ if (!parameters.has(BROKER_REDIRECT_URI)) {+ parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri);+ }+}+function addEARParameters(parameters, jwk) {+ parameters.set(EAR_JWK, encodeURIComponent(jwk));+ const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0";+ parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded);+}+function addResource(parameters, resource) {+ if (resource) {+ parameters.set(RESOURCE, resource);+ }+}+var DEFAULT_ID_TOKEN_CLAIMS;+var init_RequestParameterBuilder = __esm({+ "node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs"() {+ "use strict";+ init_Constants();+ init_AADServerParamKeys();+ init_ScopeSet();+ init_ClientConfigurationError();+ init_ClientConfigurationErrorCodes();+ DEFAULT_ID_TOKEN_CLAIMS = {+ [ClaimsRequestKeys.SIGNIN_STATE]: { essential: false },+ [ClaimsRequestKeys.LOGIN_HINT]: { essential: false }+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs+var UrlUtils_exports = {};+__export(UrlUtils_exports, {+ getDeserializedResponse: () => getDeserializedResponse,+ mapToQueryString: () => mapToQueryString,+ normalizeUrlForComparison: () => normalizeUrlForComparison,+ stripLeadingHashOrQuery: () => stripLeadingHashOrQuery,+ validateUrl: () => validateUrl+});+function stripLeadingHashOrQuery(responseString) {+ if (responseString.startsWith("#/")) {+ return responseString.substring(2);+ } else if (responseString.startsWith("#") || responseString.startsWith("?")) {+ return responseString.substring(1);+ }+ return responseString;+}+function getDeserializedResponse(responseString) {+ if (!responseString || responseString.indexOf("=") < 0) {+ return null;+ }+ try {+ const normalizedResponse = stripLeadingHashOrQuery(responseString);+ const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse));+ if (deserializedHash.code || deserializedHash.ear_jwe || deserializedHash.error || deserializedHash.error_description || deserializedHash.state) {+ return deserializedHash;+ }+ } catch (e) {+ throw createClientAuthError(hashNotDeserialized, "");+ }+ return null;+}+function mapToQueryString(parameters) {+ const queryParameterArray = new Array();+ parameters.forEach((value, key) => {+ queryParameterArray.push(`${key}=${encodeURIComponent(value)}`);+ });+ return queryParameterArray.join("&");+}+function normalizeUrlForComparison(url, logger2, correlationId) {+ if (!url) {+ return url;+ }+ const urlWithoutHash = url.split("#")[0];+ if (!urlWithoutHash) {+ return urlWithoutHash;+ }+ try {+ const urlObj = new URL(urlWithoutHash);+ if (!urlObj.search) {+ urlObj.search = "";+ }+ let pathname;+ try {+ pathname = decodeURIComponent(urlObj.pathname);+ } catch (e) {+ pathname = urlObj.pathname;+ }+ if (!pathname.endsWith("/")) {+ pathname += "/";+ }+ urlObj.pathname = pathname;+ return urlObj.href;+ } catch (e) {+ logger2?.error(`Failed to normalize URL for comparison: '${e}'`, correlationId || "");+ throw createClientConfigurationError(urlParseError, correlationId || "");+ }+}+function validateUrl(url, logger2, correlationId) {+ try {+ new URL(url);+ } catch (e) {+ logger2?.error(`Failed to validate URL: '${e}'`, correlationId || "");+ throw createClientConfigurationError(urlParseError, correlationId || "");+ }+}+var init_UrlUtils = __esm({+ "node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs"() {+ "use strict";+ init_ClientAuthError();+ init_ClientConfigurationError();+ init_ClientAuthErrorCodes();+ init_ClientConfigurationErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs+var DEFAULT_CRYPTO_IMPLEMENTATION;+var init_ICrypto = __esm({+ "node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs"() {+ "use strict";+ init_ClientAuthError();+ init_ClientAuthErrorCodes();+ DEFAULT_CRYPTO_IMPLEMENTATION = {+ createNewGuid: () => {+ throw createClientAuthError(methodNotImplemented, "");+ },+ base64Decode: () => {+ throw createClientAuthError(methodNotImplemented, "");+ },+ base64Encode: () => {+ throw createClientAuthError(methodNotImplemented, "");+ },+ base64UrlEncode: () => {+ throw createClientAuthError(methodNotImplemented, "");+ },+ encodeKid: () => {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async getPublicKeyThumbprint() {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async removeTokenBindingKey() {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async clearKeystore() {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async signJwt() {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async hashString() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/logger/Logger.mjs+function markAsRecentlyUsed(correlationId, data) {+ correlationCache.delete(correlationId);+ correlationCache.set(correlationId, data);+}+function addLogToCache(correlationId, loggedMessage) {+ const currentTime = Date.now();+ let data = correlationCache.get(correlationId);+ if (data) {+ markAsRecentlyUsed(correlationId, data);+ } else {+ data = { logs: [], firstEventTime: currentTime };+ correlationCache.set(correlationId, data);+ if (correlationCache.size > CACHE_CAPACITY) {+ const firstKey = correlationCache.keys().next().value;+ if (firstKey !== void 0) {+ correlationCache.delete(firstKey);+ }+ }+ }+ data.logs.push({+ ...loggedMessage,+ milliseconds: currentTime - data.firstEventTime+ });+ if (data.logs.length > MAX_LOGS_PER_CORRELATION) {+ data.logs.shift();+ }+}+function getMessageHash(str) {+ if (str.length < 6) {+ return null;+ }+ if (str.length > 6 && str[6] !== " ") {+ return null;+ }+ for (let i = 0; i < 6; i++) {+ const char = str[i];+ const isAlphaNumeric = char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char >= "0" && char <= "9";+ if (!isAlphaNumeric) {+ return null;+ }+ }+ return str.substring(0, 6);+}+var LogLevel, CACHE_CAPACITY, MAX_LOGS_PER_CORRELATION, correlationCache, Logger;+var init_Logger = __esm({+ "node_modules/@azure/msal-common/dist/logger/Logger.mjs"() {+ "use strict";+ (function(LogLevel2) {+ LogLevel2[LogLevel2["Error"] = 0] = "Error";+ LogLevel2[LogLevel2["Warning"] = 1] = "Warning";+ LogLevel2[LogLevel2["Info"] = 2] = "Info";+ LogLevel2[LogLevel2["Verbose"] = 3] = "Verbose";+ LogLevel2[LogLevel2["Trace"] = 4] = "Trace";+ })(LogLevel || (LogLevel = {}));+ CACHE_CAPACITY = 50;+ MAX_LOGS_PER_CORRELATION = 500;+ correlationCache = /* @__PURE__ */ new Map();+ Logger = class _Logger {+ constructor(loggerOptions, packageName, packageVersion) {+ this.level = LogLevel.Info;+ const defaultLoggerCallback = () => {+ return;+ };+ const setLoggerOptions = loggerOptions || _Logger.createDefaultLoggerOptions();+ this.localCallback = setLoggerOptions.loggerCallback || defaultLoggerCallback;+ this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;+ this.level = typeof setLoggerOptions.logLevel === "number" ? setLoggerOptions.logLevel : LogLevel.Info;+ this.packageName = packageName || "";+ this.packageVersion = packageVersion || "";+ }+ static createDefaultLoggerOptions() {+ return {+ loggerCallback: () => {+ },+ piiLoggingEnabled: false,+ logLevel: LogLevel.Info+ };+ }+ /**+ * Create new Logger with existing configurations.+ */+ clone(packageName, packageVersion) {+ return new _Logger({+ loggerCallback: this.localCallback,+ piiLoggingEnabled: this.piiLoggingEnabled,+ logLevel: this.level+ }, packageName, packageVersion);+ }+ /**+ * Log message with required options.+ */+ logMessage(logMessage, options) {+ const correlationId = options.correlationId;+ const messageHash = getMessageHash(logMessage);+ if (messageHash) {+ const loggedMessage = {+ hash: messageHash,+ level: options.logLevel,+ containsPii: options.containsPii || false,+ milliseconds: 0+ // Will be calculated in addLogToCache+ };+ addLogToCache(correlationId, loggedMessage);+ }+ if (options.logLevel > this.level || !this.piiLoggingEnabled && options.containsPii) {+ return;+ }+ const timestamp = (/* @__PURE__ */ new Date()).toUTCString();+ const logHeader = `[${timestamp}] : [${correlationId}]`;+ const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options.logLevel]} - ${logMessage}`;+ this.executeCallback(options.logLevel, log, options.containsPii || false);+ }+ /**+ * Execute callback with message.+ */+ executeCallback(level, message, containsPii) {+ if (this.localCallback) {+ this.localCallback(level, message, containsPii);+ }+ }+ /**+ * Logs error messages.+ */+ error(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Error,+ containsPii: false,+ correlationId+ });+ }+ /**+ * Logs error messages with PII.+ */+ errorPii(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Error,+ containsPii: true,+ correlationId+ });+ }+ /**+ * Logs warning messages.+ */+ warning(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Warning,+ containsPii: false,+ correlationId+ });+ }+ /**+ * Logs warning messages with PII.+ */+ warningPii(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Warning,+ containsPii: true,+ correlationId+ });+ }+ /**+ * Logs info messages.+ */+ info(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Info,+ containsPii: false,+ correlationId+ });+ }+ /**+ * Logs info messages with PII.+ */+ infoPii(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Info,+ containsPii: true,+ correlationId+ });+ }+ /**+ * Logs verbose messages.+ */+ verbose(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Verbose,+ containsPii: false,+ correlationId+ });+ }+ /**+ * Logs verbose messages with PII.+ */+ verbosePii(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Verbose,+ containsPii: true,+ correlationId+ });+ }+ /**+ * Logs trace messages.+ */+ trace(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Trace,+ containsPii: false,+ correlationId+ });+ }+ /**+ * Logs trace messages with PII.+ */+ tracePii(message, correlationId) {+ this.logMessage(message, {+ logLevel: LogLevel.Trace,+ containsPii: true,+ correlationId+ });+ }+ /**+ * Returns whether PII Logging is enabled or not.+ */+ isPiiLoggingEnabled() {+ return this.piiLoggingEnabled || false;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/packageMetadata.mjs+var name, version2;+var init_packageMetadata = __esm({+ "node_modules/@azure/msal-common/dist/packageMetadata.mjs"() {+ "use strict";+ name = "@azure/msal-common";+ version2 = "16.11.0";+ }+});++// node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs+var AzureCloudInstance;+var init_AuthorityOptions = __esm({+ "node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs"() {+ "use strict";+ AzureCloudInstance = {+ // AzureCloudInstance is not specified.+ None: "none",+ // Microsoft Azure public cloud+ AzurePublic: "https://login.microsoftonline.com",+ // Microsoft PPE+ AzurePpe: "https://login.windows-ppe.net",+ // Microsoft Chinese national/regional cloud+ AzureChina: "https://login.chinacloudapi.cn",+ // Microsoft German national/regional cloud ("Black Forest")+ AzureGermany: "https://login.microsoftonline.de",+ // US Government cloud+ AzureUsGovernment: "https://login.microsoftonline.us"+ };+ }+});++// node_modules/@azure/msal-common/dist/account/AuthToken.mjs+function extractTokenClaims(encodedToken, base64Decode, correlationId) {+ const jswPayload = getJWSPayload(encodedToken, correlationId);+ try {+ const base64Decoded = base64Decode(jswPayload);+ return JSON.parse(base64Decoded);+ } catch (err) {+ throw createClientAuthError(tokenParsingError, correlationId);+ }+}+function isKmsi(idTokenClaims) {+ if (!idTokenClaims.signin_state) {+ return false;+ }+ const kmsiClaims = ["kmsi", "dvc_dmjd"];+ return idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase()));+}+function getJWSPayload(authToken, correlationId) {+ if (!authToken) {+ throw createClientAuthError(nullOrEmptyToken, correlationId);+ }+ const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;+ const matches = tokenPartsRegex.exec(authToken);+ if (!matches || matches.length < 4) {+ throw createClientAuthError(tokenParsingError, correlationId);+ }+ return matches[2];+}+var init_AuthToken = __esm({+ "node_modules/@azure/msal-common/dist/account/AuthToken.mjs"() {+ "use strict";+ init_ClientAuthError();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/account/AccountInfo.mjs+function tenantIdMatchesHomeTenant(tenantId, homeAccountId) {+ return !!tenantId && !!homeAccountId && tenantId === homeAccountId.split(".")[1];+}+function buildTenantProfile(homeAccountId, localAccountId, tenantId, nativeAccountId, idTokenClaims) {+ if (idTokenClaims) {+ const { oid, sub, tid, name: name3, tfp, acr, preferred_username, upn, login_hint } = idTokenClaims;+ const tenantId2 = tid || tfp || acr || "";+ return {+ tenantId: tenantId2,+ localAccountId: oid || sub || "",+ name: name3,+ username: preferred_username || upn || "",+ loginHint: login_hint,+ isHomeTenant: tenantIdMatchesHomeTenant(tenantId2, homeAccountId),+ upn,+ ...nativeAccountId && { nativeAccountId }+ };+ } else {+ return {+ tenantId,+ localAccountId,+ username: "",+ isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),+ ...nativeAccountId && { nativeAccountId }+ };+ }+}+function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) {+ let updatedAccountInfo = baseAccountInfo;+ if (tenantProfile) {+ const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;+ updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride };+ }+ if (idTokenClaims) {+ const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, updatedAccountInfo.nativeAccountId, idTokenClaims);+ updatedAccountInfo = {+ ...updatedAccountInfo,+ ...claimsSourcedTenantProfile,+ idTokenClaims,+ idToken: idTokenSecret,+ kmsi: isKmsi(idTokenClaims)+ };+ return updatedAccountInfo;+ }+ return updatedAccountInfo;+}+var init_AccountInfo = __esm({+ "node_modules/@azure/msal-common/dist/account/AccountInfo.mjs"() {+ "use strict";+ init_AuthToken();+ }+});++// node_modules/@azure/msal-common/dist/url/UrlString.mjs+var UrlString;+var init_UrlString = __esm({+ "node_modules/@azure/msal-common/dist/url/UrlString.mjs"() {+ "use strict";+ init_ClientConfigurationError();+ init_StringUtils();+ init_Constants();+ init_ClientConfigurationErrorCodes();+ UrlString = class _UrlString {+ get urlString() {+ return this._urlString;+ }+ constructor(url, correlationId) {+ this._urlString = url;+ this.correlationId = correlationId;+ if (!this._urlString) {+ throw createClientConfigurationError(urlEmptyError, correlationId);+ }+ if (!url.includes("#")) {+ this._urlString = _UrlString.canonicalizeUri(url);+ }+ }+ /**+ * Ensure urls are lower case and end with a / character.+ * @param url+ */+ static canonicalizeUri(url) {+ if (url) {+ let lowerCaseUrl = url.toLowerCase();+ if (StringUtils.endsWith(lowerCaseUrl, "?")) {+ lowerCaseUrl = lowerCaseUrl.slice(0, -1);+ } else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {+ lowerCaseUrl = lowerCaseUrl.slice(0, -2);+ }+ if (!StringUtils.endsWith(lowerCaseUrl, "/")) {+ lowerCaseUrl += "/";+ }+ return lowerCaseUrl;+ }+ return url;+ }+ /**+ * Throws if urlString passed is not a valid authority URI string.+ */+ validateAsUri() {+ let components;+ try {+ components = this.getUrlComponents();+ } catch (e) {+ throw createClientConfigurationError(urlParseError, this.correlationId);+ }+ if (!components.HostNameAndPort || !components.PathSegments) {+ throw createClientConfigurationError(urlParseError, this.correlationId);+ }+ if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") {+ throw createClientConfigurationError(authorityUriInsecure, this.correlationId);+ }+ }+ /**+ * Given a url and a query string return the url with provided query string appended+ * @param url+ * @param queryString+ */+ static appendQueryString(url, queryString) {+ if (!queryString) {+ return url;+ }+ return url.indexOf("?") < 0 ? `${url}?${queryString}` : `${url}&${queryString}`;+ }+ /**+ * Returns a url with the hash removed+ * @param url+ */+ static removeHashFromUrl(url) {+ return _UrlString.canonicalizeUri(url.split("#")[0]);+ }+ /**+ * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d+ * @param href The url+ * @param tenantId The tenant id to replace+ */+ replaceTenantPath(tenantId) {+ const urlObject = this.getUrlComponents();+ const pathArray = urlObject.PathSegments;+ if (tenantId && pathArray.length !== 0 && (pathArray[0] === AADAuthority.COMMON || pathArray[0] === AADAuthority.ORGANIZATIONS)) {+ pathArray[0] = tenantId;+ }+ return _UrlString.constructAuthorityUriFromObject(urlObject, this.correlationId);+ }+ /**+ * Parses out the components from a url string.+ * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.+ */+ getUrlComponents() {+ const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");+ const match = this.urlString.match(regEx);+ if (!match) {+ throw createClientConfigurationError(urlParseError, this.correlationId);+ }+ const urlComponents = {+ Protocol: match[1],+ HostNameAndPort: match[4],+ AbsolutePath: match[5],+ QueryString: match[7]+ };+ let pathSegments = urlComponents.AbsolutePath.split("/");+ pathSegments = pathSegments.filter((val) => val && val.length > 0);+ urlComponents.PathSegments = pathSegments;+ if (urlComponents.QueryString && urlComponents.QueryString.endsWith("/")) {+ urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);+ }+ return urlComponents;+ }+ static getDomainFromUrl(url, correlationId) {+ const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");+ const match = url.match(regEx);+ if (!match) {+ throw createClientConfigurationError(urlParseError, correlationId);+ }+ return match[2];+ }+ static getAbsoluteUrl(relativeUrl, baseUrl, correlationId) {+ if (relativeUrl[0] === FORWARD_SLASH) {+ const url = new _UrlString(baseUrl, correlationId);+ const baseComponents = url.getUrlComponents();+ return baseComponents.Protocol + "//" + baseComponents.HostNameAndPort + relativeUrl;+ }+ return relativeUrl;+ }+ static constructAuthorityUriFromObject(urlObject, correlationId) {+ return new _UrlString(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + urlObject.PathSegments.join("/"), correlationId);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs+function buildOpenIdConfig(host, issuerHost) {+ return {+ token_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/token`,+ jwks_uri: `https://${host}/{tenantid}/discovery/v2.0/keys`,+ issuer: `https://${issuerHost}/{tenantid}/v2.0`,+ authorization_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/authorize`,+ end_session_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/logout`+ };+}+function getAliasesFromStaticSources(staticAuthorityOptions, logger2, correlationId) {+ let staticAliases;+ const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;+ if (canonicalAuthority) {+ const authorityHost = new UrlString(canonicalAuthority, correlationId).getUrlComponents().HostNameAndPort;+ staticAliases = getAliasesFromMetadata(logger2, correlationId, authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG) || getAliasesFromMetadata(logger2, correlationId, authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES) || staticAuthorityOptions.knownAuthorities;+ }+ return staticAliases || [];+}+function getAliasesFromMetadata(logger2, correlationId, authorityHost, cloudDiscoveryMetadata, source) {+ logger2.trace(`getAliasesFromMetadata called with source: '${source}'`, correlationId);+ if (authorityHost && cloudDiscoveryMetadata) {+ const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost);+ if (metadata) {+ logger2.trace(`getAliasesFromMetadata: found cloud discovery metadata in '${source}', returning aliases`, correlationId);+ return metadata.aliases;+ } else {+ logger2.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in '${source}'`, correlationId);+ }+ }+ return null;+}+function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) {+ const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost);+ return metadata;+}+function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) {+ for (let i = 0; i < response.length; i++) {+ const metadata = response[i];+ if (metadata.aliases.includes(authorityHost)) {+ return metadata;+ }+ }+ return null;+}+var endpointHosts, dynamicEndpointMetadata, rawMetdataJSON, EndpointMetadata, InstanceDiscoveryMetadata, InstanceDiscoveryMetadataAliases;+var init_AuthorityMetadata = __esm({+ "node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs"() {+ "use strict";+ init_UrlString();+ init_Constants();+ endpointHosts = [+ { host: "login.microsoftonline.com" },+ {+ host: "login.chinacloudapi.cn",+ issuerHost: "login.partner.microsoftonline.cn"+ // Issuer differs+ },+ { host: "login.microsoftonline.us" },+ { host: "login.sovcloud-identity.fr" },+ { host: "login.sovcloud-identity.de" },+ { host: "login.sovcloud-identity.sg" }+ ];+ dynamicEndpointMetadata = endpointHosts.reduce((acc, { host, issuerHost }) => {+ acc[host] = buildOpenIdConfig(host, issuerHost || host);+ return acc;+ }, {});+ rawMetdataJSON = {+ endpointMetadata: dynamicEndpointMetadata,+ instanceDiscoveryMetadata: {+ metadata: [+ {+ preferred_network: "login.microsoftonline.com",+ preferred_cache: "login.windows.net",+ aliases: [+ "login.microsoftonline.com",+ "login.windows.net",+ "login.microsoft.com",+ "sts.windows.net"+ ]+ },+ {+ preferred_network: "login.partner.microsoftonline.cn",+ preferred_cache: "login.partner.microsoftonline.cn",+ aliases: [+ "login.partner.microsoftonline.cn",+ "login.chinacloudapi.cn"+ ]+ },+ {+ preferred_network: "login.microsoftonline.de",+ preferred_cache: "login.microsoftonline.de",+ aliases: ["login.microsoftonline.de"]+ },+ {+ preferred_network: "login.microsoftonline.us",+ preferred_cache: "login.microsoftonline.us",+ aliases: [+ "login.microsoftonline.us",+ "login.usgovcloudapi.net"+ ]+ },+ {+ preferred_network: "login-us.microsoftonline.com",+ preferred_cache: "login-us.microsoftonline.com",+ aliases: ["login-us.microsoftonline.com"]+ },+ {+ preferred_network: "login.sovcloud-identity.fr",+ preferred_cache: "login.sovcloud-identity.fr",+ aliases: ["login.sovcloud-identity.fr"]+ },+ {+ preferred_network: "login.sovcloud-identity.de",+ preferred_cache: "login.sovcloud-identity.de",+ aliases: ["login.sovcloud-identity.de"]+ },+ {+ preferred_network: "login.sovcloud-identity.sg",+ preferred_cache: "login.sovcloud-identity.sg",+ aliases: ["login.sovcloud-identity.sg"]+ },+ {+ preferred_network: "login.windows-ppe.net",+ preferred_cache: "login.windows-ppe.net",+ aliases: [+ "login.windows-ppe.net",+ "sts.windows-ppe.net",+ "login.microsoft-ppe.com"+ ]+ }+ ]+ }+ };+ EndpointMetadata = rawMetdataJSON.endpointMetadata;+ InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;+ InstanceDiscoveryMetadataAliases = /* @__PURE__ */ new Set();+ InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => {+ metadataEntry.aliases.forEach((alias) => {+ InstanceDiscoveryMetadataAliases.add(alias);+ });+ });+ }+});++// node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs+var cacheQuotaExceeded, cacheErrorUnknown;+var init_CacheErrorCodes = __esm({+ "node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs"() {+ "use strict";+ cacheQuotaExceeded = "cache_quota_exceeded";+ cacheErrorUnknown = "cache_error_unknown";+ }+});++// node_modules/@azure/msal-common/dist/error/CacheError.mjs+function createCacheError(e) {+ if (!(e instanceof Error)) {+ return new CacheError(cacheErrorUnknown);+ }+ if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED" || e.message.includes("exceeded the quota")) {+ return new CacheError(cacheQuotaExceeded);+ } else {+ return new CacheError(e.name, e.message);+ }+}+var CacheError;+var init_CacheError = __esm({+ "node_modules/@azure/msal-common/dist/error/CacheError.mjs"() {+ "use strict";+ init_CacheErrorCodes();+ init_AuthError();+ CacheError = class _CacheError extends Error {+ constructor(errorCode, errorMessage) {+ const message = errorMessage || getDefaultErrorMessage(errorCode);+ super(message);+ Object.setPrototypeOf(this, _CacheError.prototype);+ this.name = "CacheError";+ this.errorCode = errorCode;+ this.errorMessage = message;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/account/ClientInfo.mjs+function buildClientInfo(rawClientInfo, base64Decode) {+ if (!rawClientInfo) {+ throw createClientAuthError(clientInfoEmptyError, "");+ }+ try {+ const decodedClientInfo = base64Decode(rawClientInfo);+ return JSON.parse(decodedClientInfo);+ } catch (e) {+ throw createClientAuthError(clientInfoDecodingError, "");+ }+}+function buildClientInfoFromHomeAccountId(homeAccountId) {+ if (!homeAccountId) {+ throw createClientAuthError(clientInfoDecodingError, "");+ }+ const clientInfoParts = homeAccountId.split(CLIENT_INFO_SEPARATOR, 2);+ return {+ uid: clientInfoParts[0],+ utid: clientInfoParts.length < 2 ? "" : clientInfoParts[1]+ };+}+var init_ClientInfo = __esm({+ "node_modules/@azure/msal-common/dist/account/ClientInfo.mjs"() {+ "use strict";+ init_ClientAuthError();+ init_Constants();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs+var AuthorityType;+var init_AuthorityType = __esm({+ "node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs"() {+ "use strict";+ AuthorityType = {+ Default: 0,+ Adfs: 1,+ Dsts: 2,+ Ciam: 3+ };+ }+});++// node_modules/@azure/msal-common/dist/account/TokenClaims.mjs+function getTenantIdFromIdTokenClaims(idTokenClaims) {+ if (idTokenClaims) {+ const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr;+ return tenantId || null;+ }+ return null;+}+var init_TokenClaims = __esm({+ "node_modules/@azure/msal-common/dist/account/TokenClaims.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs+var ProtocolMode;+var init_ProtocolMode = __esm({+ "node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs"() {+ "use strict";+ ProtocolMode = {+ /**+ * Auth Code + PKCE with Entra ID (formerly AAD) specific optimizations and features+ */+ AAD: "AAD",+ /**+ * Auth Code + PKCE without Entra ID specific optimizations and features. For use only with non-Microsoft owned authorities.+ * Support is limited for this mode.+ */+ OIDC: "OIDC",+ /**+ * Encrypted Authorize Response (EAR) with Entra ID specific optimizations and features+ */+ EAR: "EAR"+ };+ }+});++// node_modules/@azure/msal-common/dist/cache/utils/AccountEntityUtils.mjs+var AccountEntityUtils_exports = {};+__export(AccountEntityUtils_exports, {+ createAccountEntity: () => createAccountEntity,+ createAccountEntityFromAccountInfo: () => createAccountEntityFromAccountInfo,+ generateAccountId: () => generateAccountId,+ generateHomeAccountId: () => generateHomeAccountId,+ getAccountInfo: () => getAccountInfo,+ isAccountEntity: () => isAccountEntity,+ isSingleTenant: () => isSingleTenant+});+function generateAccountId(accountEntity) {+ const accountId = [+ accountEntity.homeAccountId,+ accountEntity.environment+ ];+ return accountId.join(CACHE_KEY_SEPARATOR).toLowerCase();+}+function getAccountInfo(accountEntity) {+ const tenantProfiles = accountEntity.tenantProfiles || [];+ if (tenantProfiles.length === 0 && accountEntity.realm && accountEntity.localAccountId) {+ tenantProfiles.push(buildTenantProfile(accountEntity.homeAccountId, accountEntity.localAccountId, accountEntity.realm, accountEntity.nativeAccountId));+ }+ const homeTenantProfile = tenantProfiles.find((tp) => tp.tenantId === accountEntity.realm);+ const nativeAccountId = homeTenantProfile?.nativeAccountId || accountEntity.nativeAccountId;+ return {+ homeAccountId: accountEntity.homeAccountId,+ environment: accountEntity.environment,+ tenantId: accountEntity.realm,+ username: accountEntity.username,+ localAccountId: accountEntity.localAccountId,+ loginHint: accountEntity.loginHint,+ name: accountEntity.name,+ nativeAccountId,+ authorityType: accountEntity.authorityType,+ // Deserialize tenant profiles array into a Map+ tenantProfiles: new Map(tenantProfiles.map((tenantProfile) => {+ return [tenantProfile.tenantId, tenantProfile];+ })),+ dataBoundary: accountEntity.dataBoundary+ };+}+function isSingleTenant(accountEntity) {+ return !accountEntity.tenantProfiles;+}+function createAccountEntity(accountDetails, authority, correlationId, base64Decode) {+ let authorityType;+ if (authority.authorityType === AuthorityType.Adfs) {+ authorityType = CACHE_ACCOUNT_TYPE_ADFS;+ } else if (authority.protocolMode === ProtocolMode.OIDC) {+ authorityType = CACHE_ACCOUNT_TYPE_GENERIC;+ } else {+ authorityType = CACHE_ACCOUNT_TYPE_MSSTS;+ }+ let clientInfo;+ let dataBoundary;+ if (accountDetails.clientInfo && base64Decode) {+ clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);+ if (clientInfo.xms_tdbr) {+ dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";+ }+ }+ const env = accountDetails.environment || authority && authority.getPreferredCache();+ if (!env) {+ throw createClientAuthError(invalidCacheEnvironment, correlationId);+ }+ const preferredUsername = accountDetails.idTokenClaims?.preferred_username || accountDetails.idTokenClaims?.upn;+ const email2 = accountDetails.idTokenClaims?.emails ? accountDetails.idTokenClaims.emails[0] : null;+ const username = preferredUsername || email2 || "";+ const loginHint = accountDetails.idTokenClaims?.login_hint;+ const realm = clientInfo?.utid || getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) || "";+ const localAccountId = clientInfo?.uid || accountDetails.idTokenClaims?.oid || accountDetails.idTokenClaims?.sub || "";+ let tenantProfiles;+ if (accountDetails.tenantProfiles) {+ tenantProfiles = accountDetails.tenantProfiles;+ } else {+ const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, localAccountId, realm, accountDetails.nativeAccountId, accountDetails.idTokenClaims);+ tenantProfiles = [tenantProfile];+ }+ return {+ homeAccountId: accountDetails.homeAccountId,+ environment: env,+ realm,+ localAccountId,+ username,+ authorityType,+ loginHint,+ clientInfo: accountDetails.clientInfo,+ name: accountDetails.idTokenClaims?.name || "",+ lastModificationTime: void 0,+ lastModificationApp: void 0,+ cloudGraphHostName: accountDetails.cloudGraphHostName,+ msGraphHost: accountDetails.msGraphHost,+ nativeAccountId: accountDetails.nativeAccountId,+ tenantProfiles,+ dataBoundary+ };+}+function createAccountEntityFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) {+ const tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []);+ if (tenantProfiles.length === 0 && accountInfo.tenantId && accountInfo.localAccountId) {+ tenantProfiles.push(buildTenantProfile(accountInfo.homeAccountId, accountInfo.localAccountId, accountInfo.tenantId, accountInfo.nativeAccountId, accountInfo.idTokenClaims));+ } else if (accountInfo.nativeAccountId) {+ const matchingProfile = tenantProfiles.find((tp) => tp.tenantId === accountInfo.tenantId);+ if (matchingProfile && !matchingProfile.nativeAccountId) {+ matchingProfile.nativeAccountId = accountInfo.nativeAccountId;+ }+ }+ return {+ authorityType: accountInfo.authorityType || CACHE_ACCOUNT_TYPE_GENERIC,+ homeAccountId: accountInfo.homeAccountId,+ localAccountId: accountInfo.localAccountId,+ nativeAccountId: accountInfo.nativeAccountId,+ realm: accountInfo.tenantId,+ environment: accountInfo.environment,+ username: accountInfo.username,+ loginHint: accountInfo.loginHint,+ name: accountInfo.name,+ cloudGraphHostName,+ msGraphHost,+ tenantProfiles,+ dataBoundary: accountInfo.dataBoundary+ };+}+function generateHomeAccountId(serverClientInfo, authType, logger2, cryptoObj, correlationId, idTokenClaims) {+ if (!(authType === AuthorityType.Adfs || authType === AuthorityType.Dsts)) {+ if (serverClientInfo) {+ try {+ const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode);+ if (clientInfo.uid && clientInfo.utid) {+ return `${clientInfo.uid}.${clientInfo.utid}`;+ }+ } catch (e) {+ }+ }+ logger2.warning("No client info in response", correlationId);+ }+ return idTokenClaims?.sub || "";+}+function isAccountEntity(entity) {+ if (!entity) {+ return false;+ }+ return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("realm") && entity.hasOwnProperty("localAccountId") && entity.hasOwnProperty("username") && entity.hasOwnProperty("authorityType");+}+var init_AccountEntityUtils = __esm({+ "node_modules/@azure/msal-common/dist/cache/utils/AccountEntityUtils.mjs"() {+ "use strict";+ init_Constants();+ init_ClientInfo();+ init_AccountInfo();+ init_ClientAuthError();+ init_AuthorityType();+ init_TokenClaims();+ init_ProtocolMode();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/cache/CacheManager.mjs+var CacheManager, DefaultStorageClass;+var init_CacheManager = __esm({+ "node_modules/@azure/msal-common/dist/cache/CacheManager.mjs"() {+ "use strict";+ init_AccountInfo();+ init_AuthToken();+ init_AuthorityMetadata();+ init_AuthError();+ init_CacheError();+ init_ClientAuthError();+ init_packageMetadata();+ init_ScopeSet();+ init_Constants();+ init_AccountEntityUtils();+ init_ClientAuthErrorCodes();+ CacheManager = class {+ constructor(clientId, cryptoImpl, logger2, performanceClient, staticAuthorityOptions) {+ this.clientId = clientId;+ this.cryptoImpl = cryptoImpl;+ this.commonLogger = logger2.clone(name, version2);+ this.staticAuthorityOptions = staticAuthorityOptions;+ this.performanceClient = performanceClient;+ }+ /**+ * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.+ * @param accountFilter - (Optional) filter to narrow down the accounts returned+ * @returns Array of AccountInfo objects in cache+ */+ getAllAccounts(accountFilter = {}, correlationId) {+ return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter);+ }+ /**+ * Gets first tenanted AccountInfo object found based on provided filters+ */+ getAccountInfoFilteredBy(accountFilter, correlationId) {+ if (Object.keys(accountFilter).length === 0 || Object.values(accountFilter).every((value) => value === null || value === void 0 || value === "")) {+ this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null", correlationId);+ return null;+ }+ const allAccounts = this.getAllAccounts(accountFilter, correlationId);+ if (allAccounts.length > 1) {+ const sortedAccounts = allAccounts.sort((a, b) => {+ const aHasClaims = a.idTokenClaims ? 1 : 0;+ const bHasClaims = b.idTokenClaims ? 1 : 0;+ return bHasClaims - aHasClaims;+ });+ return sortedAccounts[0];+ } else if (allAccounts.length === 1) {+ return allAccounts[0];+ } else {+ return null;+ }+ }+ /**+ * Returns a single matching+ * @param accountFilter+ * @returns+ */+ getBaseAccountInfo(accountFilter, correlationId) {+ const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId);+ if (accountEntities.length > 0) {+ return getAccountInfo(accountEntities[0]);+ } else {+ return null;+ }+ }+ /**+ * Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters+ * and builds the account info objects from the matching ID token's claims+ * @param cachedAccounts+ * @param accountFilter+ * @returns Array of AccountInfo objects that match account and tenant profile filters+ */+ buildTenantProfiles(cachedAccounts, correlationId, accountFilter) {+ return cachedAccounts.flatMap((accountEntity) => {+ return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter);+ });+ }+ getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) {+ let tenantedAccountInfo = null;+ let idTokenClaims;+ if (tenantProfileFilter) {+ if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) {+ return null;+ }+ }+ const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId);+ if (idToken) {+ idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode, correlationId);+ if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) {+ return null;+ }+ }+ tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret);+ return tenantedAccountInfo;+ }+ getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) {+ const accountInfo = getAccountInfo(accountEntity);+ let searchTenantProfiles = accountInfo.tenantProfiles || /* @__PURE__ */ new Map();+ const tokenKeys = this.getTokenKeys();+ if (targetTenantId) {+ const tenantProfile = searchTenantProfiles.get(targetTenantId);+ if (tenantProfile) {+ searchTenantProfiles = /* @__PURE__ */ new Map([+ [targetTenantId, tenantProfile]+ ]);+ } else {+ return [];+ }+ }+ const matchingTenantProfiles = [];+ searchTenantProfiles.forEach((tenantProfile) => {+ const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter);+ if (tenantedAccountInfo) {+ matchingTenantProfiles.push(tenantedAccountInfo);+ }+ });+ return matchingTenantProfiles;+ }+ tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) {+ if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) {+ return false;+ }+ if (!!tenantProfileFilter.name && !(tenantProfile.name === tenantProfileFilter.name)) {+ return false;+ }+ if (tenantProfileFilter.isHomeTenant !== void 0 && !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) {+ return false;+ }+ if (!!tenantProfileFilter.username && !this.matchUsername(tenantProfile.username, tenantProfileFilter.username) && !this.matchUsername(tenantProfile.upn, tenantProfileFilter.username)) {+ return false;+ }+ if (!!tenantProfileFilter.loginHint && !this.matchLoginHintWithTenantProfile(tenantProfile, tenantProfileFilter.loginHint)) {+ return false;+ }+ if (!!tenantProfileFilter.upn && !(tenantProfile.upn === tenantProfileFilter.upn)) {+ return false;+ }+ if (!!tenantProfileFilter.nativeAccountId && tenantProfile.nativeAccountId !== tenantProfileFilter.nativeAccountId) {+ return false;+ }+ return true;+ }+ idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) {+ if (tenantProfileFilter) {+ if (!!tenantProfileFilter.localAccountId && !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) {+ return false;+ }+ if (!!tenantProfileFilter.loginHint && !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) {+ return false;+ }+ if (!!tenantProfileFilter.username && !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username) && !this.matchUsername(idTokenClaims.upn, tenantProfileFilter.username)) {+ return false;+ }+ if (!!tenantProfileFilter.name && !this.matchName(idTokenClaims, tenantProfileFilter.name)) {+ return false;+ }+ if (!!tenantProfileFilter.sid && !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) {+ return false;+ }+ }+ return true;+ }+ /**+ * saves a cache record+ * @param cacheRecord {CacheRecord}+ * @param storeInCache {?StoreInCache}+ * @param correlationId {?string} correlation id+ */+ async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {+ if (!cacheRecord) {+ throw createClientAuthError(invalidCacheRecord, correlationId);+ }+ try {+ if (!!cacheRecord.account) {+ await this.setAccount(cacheRecord.account, correlationId, kmsi, apiId);+ }+ if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {+ await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi);+ }+ if (!!cacheRecord.accessToken && storeInCache?.accessToken !== false) {+ await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi);+ }+ if (!!cacheRecord.refreshToken && storeInCache?.refreshToken !== false) {+ await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi);+ }+ if (!!cacheRecord.appMetadata) {+ this.setAppMetadata(cacheRecord.appMetadata, correlationId);+ }+ } catch (e) {+ this.commonLogger?.error(`CacheManager.saveCacheRecord: failed`, correlationId);+ if (e instanceof AuthError) {+ throw e;+ } else {+ throw createCacheError(e);+ }+ }+ }+ /**+ * saves access token credential+ * @param credential+ */+ async saveAccessToken(credential, correlationId, kmsi) {+ const accessTokenFilter = {+ clientId: credential.clientId,+ credentialType: credential.credentialType,+ environment: credential.environment,+ homeAccountId: credential.homeAccountId,+ realm: credential.realm,+ tokenType: credential.tokenType+ };+ const tokenKeys = this.getTokenKeys();+ const currentScopes = ScopeSet.fromString(credential.target, correlationId);+ tokenKeys.accessToken.forEach((key) => {+ if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {+ return;+ }+ const tokenEntity = this.getAccessTokenCredential(key, correlationId);+ if (tokenEntity && this.credentialMatchesFilter(tokenEntity, accessTokenFilter, correlationId)) {+ const tokenScopeSet = ScopeSet.fromString(tokenEntity.target, correlationId);+ if (tokenScopeSet.intersectingScopeSets(currentScopes)) {+ this.removeAccessToken(key, correlationId);+ }+ }+ });+ await this.setAccessTokenCredential(credential, correlationId, kmsi);+ }+ /**+ * Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache+ * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared+ * @param accountFilter - An object containing Account properties to filter by+ */+ getAccountsFilteredBy(accountFilter, correlationId) {+ const allAccountKeys = this.getAccountKeys();+ const matchingAccounts = [];+ allAccountKeys.forEach((cacheKey) => {+ const entity = this.getAccount(cacheKey, correlationId);+ if (!entity) {+ return;+ }+ if (!!accountFilter.homeAccountId && !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {+ return;+ }+ if (!!accountFilter.environment && !this.matchEnvironment(entity, accountFilter.environment, correlationId)) {+ return;+ }+ if (!!accountFilter.realm && !this.matchRealm(entity, accountFilter.realm)) {+ return;+ }+ if (!!accountFilter.authorityType && !this.matchAuthorityType(entity, accountFilter.authorityType)) {+ return;+ }+ const tenantProfileFilter = {+ localAccountId: accountFilter?.localAccountId,+ name: accountFilter?.name,+ username: accountFilter?.username,+ loginHint: accountFilter?.loginHint,+ upn: accountFilter?.upn,+ nativeAccountId: accountFilter?.nativeAccountId+ };+ const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => {+ return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter);+ });+ if (matchingTenantProfiles && matchingTenantProfiles.length === 0) {+ return;+ }+ matchingAccounts.push(entity);+ });+ return matchingAccounts;+ }+ /**+ * Returns whether or not the given credential entity matches the filter+ * @param entity+ * @param filter+ * @param correlationId+ * @returns+ */+ credentialMatchesFilter(entity, filter, correlationId) {+ if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {+ return false;+ }+ if (!!filter.userAssertionHash && !this.matchUserAssertionHash(entity, filter.userAssertionHash)) {+ return false;+ }+ if (typeof filter.homeAccountId === "string" && !this.matchHomeAccountId(entity, filter.homeAccountId)) {+ return false;+ }+ if (!!filter.environment && !this.matchEnvironment(entity, filter.environment, correlationId)) {+ return false;+ }+ if (!!filter.realm && !this.matchRealm(entity, filter.realm)) {+ return false;+ }+ if (!!filter.credentialType && !this.matchCredentialType(entity, filter.credentialType)) {+ return false;+ }+ if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) {+ return false;+ }+ if (!!filter.target && !this.matchTarget(entity, filter.target, correlationId)) {+ return false;+ }+ if (entity.credentialType === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {+ if (!!filter.tokenType && !this.matchTokenType(entity, filter.tokenType)) {+ return false;+ }+ if (filter.tokenType === AuthenticationScheme.SSH) {+ if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) {+ return false;+ }+ }+ }+ const entityComponents = entity.additionalCacheKeyComponents;+ const filterComponents = filter.additionalCacheKeyComponents;+ const entityHasComponents = !!entityComponents && Object.keys(entityComponents).length > 0;+ const filterHasComponents = !!filterComponents && Object.keys(filterComponents).length > 0;+ if (entityHasComponents !== filterHasComponents) {+ return false;+ }+ if (entityHasComponents && filterHasComponents) {+ const entityKeys = Object.keys(entityComponents).sort();+ const filterKeys = Object.keys(filterComponents).sort();+ if (entityKeys.length !== filterKeys.length) {+ return false;+ }+ for (let i = 0; i < entityKeys.length; i++) {+ if (entityKeys[i] !== filterKeys[i] || entityComponents[entityKeys[i]] !== filterComponents[filterKeys[i]]) {+ return false;+ }+ }+ }+ return true;+ }+ /**+ * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata+ * @param filter+ * @param correlationId+ */+ getAppMetadataFilteredBy(filter, correlationId) {+ const allCacheKeys = this.getKeys();+ const matchingAppMetadata = {};+ allCacheKeys.forEach((cacheKey) => {+ if (!this.isAppMetadata(cacheKey)) {+ return;+ }+ const entity = this.getAppMetadata(cacheKey, correlationId);+ if (!entity) {+ return;+ }+ if (!!filter.environment && !this.matchEnvironment(entity, filter.environment, correlationId)) {+ return;+ }+ if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {+ return;+ }+ matchingAppMetadata[cacheKey] = entity;+ });+ return matchingAppMetadata;+ }+ /**+ * retrieve authorityMetadata that contains a matching alias+ * @param host+ * @param correlationId+ */+ getAuthorityMetadataByAlias(host, correlationId) {+ const allCacheKeys = this.getAuthorityMetadataKeys();+ let matchedEntity = null;+ allCacheKeys.forEach((cacheKey) => {+ if (!this.isAuthorityMetadata(cacheKey) || cacheKey.indexOf(this.clientId) === -1) {+ return;+ }+ const entity = this.getAuthorityMetadata(cacheKey, correlationId);+ if (!entity) {+ return;+ }+ if (entity.aliases.indexOf(host) === -1) {+ return;+ }+ matchedEntity = entity;+ });+ return matchedEntity;+ }+ /**+ * Removes all accounts and related tokens from cache.+ */+ removeAllAccounts(correlationId) {+ const accounts = this.getAllAccounts({}, correlationId);+ accounts.forEach((account) => {+ this.removeAccount(account, correlationId);+ });+ }+ /**+ * Removes the account and related tokens for a given account key+ * @param account+ */+ removeAccount(account, correlationId) {+ this.removeAccountContext(account, correlationId);+ const accountKeys = this.getAccountKeys();+ const keyFilter = (key) => {+ return key.includes(account.homeAccountId) && key.includes(account.environment);+ };+ accountKeys.filter(keyFilter).forEach((key) => {+ this.removeItem(key, correlationId);+ this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId);+ });+ }+ /**+ * Removes credentials associated with the provided account+ * @param account+ */+ removeAccountContext(account, correlationId) {+ const allTokenKeys = this.getTokenKeys();+ const keyFilter = (key) => {+ return key.includes(account.homeAccountId) && key.includes(account.environment);+ };+ allTokenKeys.idToken.filter(keyFilter).forEach((key) => {+ this.removeIdToken(key, correlationId);+ });+ allTokenKeys.accessToken.filter(keyFilter).forEach((key) => {+ this.removeAccessToken(key, correlationId);+ });+ allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => {+ this.removeRefreshToken(key, correlationId);+ });+ }+ /**+ * returns a boolean if the given credential is removed+ * @param key+ * @param correlationId+ */+ removeAccessToken(key, correlationId) {+ const credential = this.getAccessTokenCredential(key, correlationId);+ if (!credential) {+ return;+ }+ this.removeItem(key, correlationId);+ this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId);+ if (credential.credentialType.toLowerCase() === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {+ if (credential.tokenType === AuthenticationScheme.POP) {+ const accessTokenWithAuthSchemeEntity = credential;+ const kid = accessTokenWithAuthSchemeEntity.keyId;+ if (kid) {+ void this.cryptoImpl.removeTokenBindingKey(kid, correlationId).catch(() => {+ this.commonLogger.error(`Failed to remove token binding key '${kid}'`, correlationId);+ this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId);+ });+ }+ }+ }+ }+ /**+ * Removes all app metadata objects from cache.+ */+ removeAppMetadata(correlationId) {+ const allCacheKeys = this.getKeys();+ allCacheKeys.forEach((cacheKey) => {+ if (this.isAppMetadata(cacheKey)) {+ this.removeItem(cacheKey, correlationId);+ }+ });+ return true;+ }+ /**+ * Retrieve IdTokenEntity from cache+ * @param account {AccountInfo}+ * @param tokenKeys {?TokenKeys}+ * @param targetRealm {?string}+ * @param performanceClient {?IPerformanceClient}+ * @param correlationId {?string}+ */+ getIdToken(account, correlationId, tokenKeys, targetRealm) {+ this.commonLogger.trace("CacheManager - getIdToken called", correlationId);+ const idTokenFilter = {+ homeAccountId: account.homeAccountId,+ environment: account.environment,+ credentialType: CredentialType.ID_TOKEN,+ clientId: this.clientId,+ realm: targetRealm+ };+ const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys);+ const numIdTokens = idTokenMap.size;+ if (numIdTokens < 1) {+ this.commonLogger.info("CacheManager:getIdToken - No token found", correlationId);+ return null;+ } else if (numIdTokens > 1) {+ let tokensToBeRemoved = idTokenMap;+ if (!targetRealm) {+ const homeIdTokenMap = /* @__PURE__ */ new Map();+ idTokenMap.forEach((idToken, key) => {+ if (idToken.realm === account.tenantId) {+ homeIdTokenMap.set(key, idToken);+ }+ });+ const numHomeIdTokens = homeIdTokenMap.size;+ if (numHomeIdTokens < 1) {+ this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result", correlationId);+ return idTokenMap.values().next().value ?? null;+ } else if (numHomeIdTokens === 1) {+ this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile", correlationId);+ return homeIdTokenMap.values().next().value ?? null;+ } else {+ tokensToBeRemoved = homeIdTokenMap;+ }+ }+ this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them", correlationId);+ tokensToBeRemoved.forEach((idToken, key) => {+ this.removeIdToken(key, correlationId);+ });+ this.performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId);+ return null;+ }+ this.commonLogger.info("CacheManager:getIdToken - Returning ID token", correlationId);+ return idTokenMap.values().next().value ?? null;+ }+ /**+ * Gets all idTokens matching the given filter+ * @param filter+ * @returns+ */+ getIdTokensByFilter(filter, correlationId, tokenKeys) {+ const idTokenKeys = tokenKeys && tokenKeys.idToken || this.getTokenKeys().idToken;+ const idTokens = /* @__PURE__ */ new Map();+ idTokenKeys.forEach((key) => {+ if (!this.idTokenKeyMatchesFilter(key, {+ clientId: this.clientId,+ ...filter+ })) {+ return;+ }+ const idToken = this.getIdTokenCredential(key, correlationId);+ if (idToken && this.credentialMatchesFilter(idToken, filter, correlationId)) {+ idTokens.set(key, idToken);+ }+ });+ return idTokens;+ }+ /**+ * Validate the cache key against filter before retrieving and parsing cache value+ * @param key+ * @param filter+ * @returns+ */+ idTokenKeyMatchesFilter(inputKey, filter) {+ const key = inputKey.toLowerCase();+ if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {+ return false;+ }+ if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {+ return false;+ }+ return true;+ }+ /**+ * Removes idToken from the cache+ * @param key+ */+ removeIdToken(key, correlationId) {+ this.removeItem(key, correlationId);+ }+ /**+ * Removes refresh token from the cache+ * @param key+ */+ removeRefreshToken(key, correlationId) {+ this.removeItem(key, correlationId);+ }+ /**+ * Retrieve AccessTokenEntity from cache+ * @param account {AccountInfo}+ * @param request {BaseAuthRequest}+ * @param tokenKeys {?TokenKeys}+ * @param performanceClient {?IPerformanceClient}+ */+ getAccessToken(account, request, tokenKeys, targetRealm) {+ const correlationId = request.correlationId;+ this.commonLogger.trace("CacheManager - getAccessToken called", correlationId);+ const scopes = ScopeSet.createSearchScopes(request.scopes, correlationId);+ const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;+ const credentialType = authScheme && authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase() ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;+ const accessTokenFilter = {+ homeAccountId: account.homeAccountId,+ environment: account.environment,+ credentialType,+ clientId: this.clientId,+ realm: targetRealm || account.tenantId,+ target: scopes,+ tokenType: authScheme,+ keyId: request.sshKid+ };+ const accessTokenKeys = tokenKeys && tokenKeys.accessToken || this.getTokenKeys().accessToken;+ const accessTokens = [];+ accessTokenKeys.forEach((key) => {+ if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {+ const accessToken = this.getAccessTokenCredential(key, correlationId);+ if (accessToken && this.credentialMatchesFilter(accessToken, accessTokenFilter, correlationId)) {+ accessTokens.push(accessToken);+ }+ }+ });+ const numAccessTokens = accessTokens.length;+ if (numAccessTokens < 1) {+ this.commonLogger.info("CacheManager:getAccessToken - No token found", correlationId);+ return null;+ } else if (numAccessTokens > 1) {+ this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them", correlationId);+ accessTokens.forEach((accessToken) => {+ this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId);+ });+ this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId);+ return null;+ }+ this.commonLogger.info("CacheManager:getAccessToken - Returning access token", correlationId);+ return accessTokens[0];+ }+ /**+ * Validate the cache key against filter before retrieving and parsing cache value+ * @param key+ * @param filter+ * @param keyMustContainAllScopes+ * @returns+ */+ accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) {+ const key = inputKey.toLowerCase();+ if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {+ return false;+ }+ if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {+ return false;+ }+ if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) {+ return false;+ }+ if (filter.target) {+ const scopes = filter.target.asArray();+ for (let i = 0; i < scopes.length; i++) {+ if (keyMustContainAllScopes && !key.includes(scopes[i].toLowerCase())) {+ return false;+ } else if (!keyMustContainAllScopes && key.includes(scopes[i].toLowerCase())) {+ return true;+ }+ }+ }+ return true;+ }+ /**+ * Gets all access tokens matching the filter+ * @param filter+ * @returns+ */+ getAccessTokensByFilter(filter, correlationId) {+ const tokenKeys = this.getTokenKeys();+ const accessTokens = [];+ tokenKeys.accessToken.forEach((key) => {+ if (!this.accessTokenKeyMatchesFilter(key, filter, true)) {+ return;+ }+ const accessToken = this.getAccessTokenCredential(key, correlationId);+ if (accessToken && this.credentialMatchesFilter(accessToken, filter, correlationId)) {+ accessTokens.push(accessToken);+ }+ });+ return accessTokens;+ }+ /**+ * Helper to retrieve the appropriate refresh token from cache+ * @param account {AccountInfo}+ * @param familyRT {boolean}+ * @param tokenKeys {?TokenKeys}+ * @param performanceClient {?IPerformanceClient}+ * @param correlationId {?string}+ */+ getRefreshToken(account, familyRT, correlationId, tokenKeys) {+ this.commonLogger.trace("CacheManager - getRefreshToken called", correlationId);+ const id = familyRT ? THE_FAMILY_ID : void 0;+ const refreshTokenFilter = {+ homeAccountId: account.homeAccountId,+ environment: account.environment,+ credentialType: CredentialType.REFRESH_TOKEN,+ clientId: this.clientId,+ familyId: id+ };+ const refreshTokenKeys = tokenKeys && tokenKeys.refreshToken || this.getTokenKeys().refreshToken;+ const refreshTokens = [];+ refreshTokenKeys.forEach((key) => {+ if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {+ const refreshToken = this.getRefreshTokenCredential(key, correlationId);+ if (refreshToken && this.credentialMatchesFilter(refreshToken, refreshTokenFilter, correlationId)) {+ refreshTokens.push(refreshToken);+ }+ }+ });+ const numRefreshTokens = refreshTokens.length;+ if (numRefreshTokens < 1) {+ this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found.", correlationId);+ return null;+ }+ if (numRefreshTokens > 1) {+ this.performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId);+ }+ this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token", correlationId);+ return refreshTokens[0];+ }+ /**+ * Validate the cache key against filter before retrieving and parsing cache value+ * @param key+ * @param filter+ */+ refreshTokenKeyMatchesFilter(inputKey, filter) {+ const key = inputKey.toLowerCase();+ if (filter.familyId && key.indexOf(filter.familyId.toLowerCase()) === -1) {+ return false;+ }+ if (!filter.familyId && filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {+ return false;+ }+ if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {+ return false;+ }+ return true;+ }+ /**+ * Retrieve AppMetadataEntity from cache+ */+ readAppMetadataFromCache(environment, correlationId) {+ const appMetadataFilter = {+ environment,+ clientId: this.clientId+ };+ const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter, correlationId);+ const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);+ const numAppMetadata = appMetadataEntries.length;+ if (numAppMetadata < 1) {+ return null;+ } else if (numAppMetadata > 1) {+ throw createClientAuthError(multipleMatchingAppMetadata, correlationId);+ }+ return appMetadataEntries[0];+ }+ /**+ * Return the family_id value associated with FOCI+ * @param environment+ * @param clientId+ */+ isAppMetadataFOCI(environment, correlationId) {+ const appMetadata = this.readAppMetadataFromCache(environment, correlationId);+ return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);+ }+ /**+ * helper to match account ids+ * @param value+ * @param homeAccountId+ */+ matchHomeAccountId(entity, homeAccountId) {+ return !!(typeof entity.homeAccountId === "string" && homeAccountId === entity.homeAccountId);+ }+ /**+ * helper to match account ids+ * @param entity+ * @param localAccountId+ * @returns+ */+ matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) {+ const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub;+ return localAccountId === idTokenLocalAccountId;+ }+ matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) {+ return tenantProfile.localAccountId === localAccountId;+ }+ /**+ * helper to match names+ * @param entity+ * @param name+ * @returns true if the downcased name properties are present and match in the filter and the entity+ */+ matchName(claims, name3) {+ return !!(name3.toLowerCase() === claims.name?.toLowerCase());+ }+ /**+ * helper to match usernames+ * @param entity+ * @param username+ * @returns+ */+ matchUsername(cachedUsername, filterUsername) {+ return !!(cachedUsername && typeof cachedUsername === "string" && filterUsername?.toLowerCase() === cachedUsername.toLowerCase());+ }+ /**+ * helper to match loginhints+ * @param entity+ * @param loginHint+ * @returns+ */+ matchLoginHintWithTenantProfile(tenantProfile, loginHintFilter) {+ return tenantProfile.loginHint === loginHintFilter || tenantProfile.username === loginHintFilter || tenantProfile.upn === loginHintFilter;+ }+ /**+ * helper to match assertion+ * @param value+ * @param oboAssertion+ */+ matchUserAssertionHash(entity, userAssertionHash) {+ return !!(entity.userAssertionHash && userAssertionHash === entity.userAssertionHash);+ }+ /**+ * helper to match environment+ * @param value+ * @param environment+ */+ matchEnvironment(entity, environment, correlationId) {+ if (this.staticAuthorityOptions) {+ const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger, correlationId);+ if (staticAliases.includes(environment) && staticAliases.includes(entity.environment)) {+ return true;+ }+ }+ const cloudMetadata = this.getAuthorityMetadataByAlias(environment, correlationId);+ if (cloudMetadata && cloudMetadata.aliases.indexOf(entity.environment) > -1) {+ return true;+ }+ return false;+ }+ /**+ * helper to match credential type+ * @param entity+ * @param credentialType+ */+ matchCredentialType(entity, credentialType) {+ return entity.credentialType && credentialType.toLowerCase() === entity.credentialType.toLowerCase();+ }+ /**+ * helper to match client ids+ * @param entity+ * @param clientId+ */+ matchClientId(entity, clientId) {+ return !!(entity.clientId && clientId === entity.clientId);+ }+ /**+ * helper to match family ids+ * @param entity+ * @param familyId+ */+ matchFamilyId(entity, familyId) {+ return !!(entity.familyId && familyId === entity.familyId);+ }+ /**+ * helper to match realm+ * @param entity+ * @param realm+ */+ matchRealm(entity, realm) {+ return !!(entity.realm?.toLowerCase() === realm.toLowerCase());+ }+ /**+ * helper to match loginHint which can be either:+ * 1. login_hint ID token claim+ * 2. username in cached account object+ * 3. upn in ID token claims+ * @param entity+ * @param loginHint+ * @returns+ */+ matchLoginHintFromTokenClaims(tokenClaims, loginHint) {+ if (tokenClaims.login_hint === loginHint) {+ return true;+ }+ if (tokenClaims.preferred_username === loginHint) {+ return true;+ }+ if (tokenClaims.upn === loginHint) {+ return true;+ }+ if (tokenClaims.emails && tokenClaims.emails.includes(loginHint)) {+ return true;+ }+ return false;+ }+ /**+ * Helper to match sid+ * @param entity+ * @param sid+ * @returns true if the sid claim is present and matches the filter+ */+ matchSid(idTokenClaims, sid) {+ return idTokenClaims.sid === sid;+ }+ matchAuthorityType(entity, authorityType) {+ return !!(entity.authorityType && authorityType.toLowerCase() === entity.authorityType.toLowerCase());+ }+ /**+ * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.+ * @param entity+ * @param target+ */+ matchTarget(entity, target, correlationId) {+ const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN && entity.credentialType !== CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;+ if (isNotAccessTokenCredential || !entity.target) {+ return false;+ }+ const entityScopeSet = ScopeSet.fromString(entity.target, correlationId);+ return entityScopeSet.containsScopeSet(target);+ }+ /**+ * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise+ * @param entity+ * @param tokenType+ */+ matchTokenType(entity, tokenType) {+ return !!(entity.tokenType && entity.tokenType === tokenType);+ }+ /**+ * Returns true if the credential's keyId matches the one in the request, false otherwise+ * @param entity+ * @param keyId+ */+ matchKeyId(entity, keyId) {+ return !!(entity.keyId && entity.keyId === keyId);+ }+ /**+ * returns if a given cache entity is of the type appmetadata+ * @param key+ */+ isAppMetadata(key) {+ return key.indexOf(APP_METADATA) !== -1;+ }+ /**+ * returns if a given cache entity is of the type authoritymetadata+ * @param key+ */+ isAuthorityMetadata(key) {+ return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) !== -1;+ }+ /**+ * returns cache key used for cloud instance metadata+ */+ generateAuthorityMetadataCacheKey(authority) {+ return `${AUTHORITY_METADATA_CACHE_KEY}-${this.clientId}-${authority}`;+ }+ /**+ * Helper to convert serialized data to object+ * @param obj+ * @param json+ */+ static toObject(obj, json) {+ for (const propertyName in json) {+ obj[propertyName] = json[propertyName];+ }+ return obj;+ }+ };+ DefaultStorageClass = class extends CacheManager {+ async setAccount() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAccount() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ async setIdTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getIdTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ async setAccessTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAccessTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ async setRefreshTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getRefreshTokenCredential() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ setAppMetadata() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAppMetadata() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ setServerTelemetry() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getServerTelemetry() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ setAuthorityMetadata() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAuthorityMetadata() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAuthorityMetadataKeys() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ setThrottlingCache() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getThrottlingCache() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ removeItem() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getKeys() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getAccountKeys() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ getTokenKeys() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ generateCredentialKey() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ generateAccountKey() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs+var PerformanceEventStatus;+var init_PerformanceEvent = __esm({+ "node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs"() {+ "use strict";+ PerformanceEventStatus = {+ NotStarted: 0,+ InProgress: 1,+ Completed: 2+ };+ }+});++// node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs+var StubPerformanceClient;+var init_StubPerformanceClient = __esm({+ "node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs"() {+ "use strict";+ init_PerformanceEvent();+ StubPerformanceClient = class {+ generateId() {+ return "callback-id";+ }+ startMeasurement(measureName, correlationId) {+ return {+ end: () => null,+ discard: () => {+ },+ add: () => {+ },+ increment: () => {+ },+ event: {+ eventId: this.generateId(),+ status: PerformanceEventStatus.InProgress,+ authority: "",+ libraryName: "",+ libraryVersion: "",+ clientId: "",+ name: measureName,+ startTimeMs: Date.now(),+ correlationId: correlationId || ""+ }+ };+ }+ endMeasurement() {+ return null;+ }+ discardMeasurements() {+ return;+ }+ removePerformanceCallback() {+ return true;+ }+ addPerformanceCallback() {+ return "";+ }+ emitEvents() {+ return;+ }+ addFields() {+ return;+ }+ addGlobalFields() {+ return;+ }+ incrementFields() {+ return;+ }+ cacheEventByCorrelationId() {+ return;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs+function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials, libraryInfo, telemetry, serverTelemetryManager, persistencePlugin, serializableCache }) {+ const loggerOptions = {+ ...DEFAULT_LOGGER_IMPLEMENTATION,+ ...userLoggerOption+ };+ return {+ authOptions: buildAuthOptions(userAuthOptions),+ systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },+ loggerOptions,+ storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions, name, version2), new StubPerformanceClient()),+ networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,+ cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,+ clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,+ libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },+ telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },+ serverTelemetryManager: serverTelemetryManager || null,+ persistencePlugin: persistencePlugin || null,+ serializableCache: serializableCache || null+ };+}+function buildAuthOptions(authOptions) {+ return {+ clientCapabilities: [],+ azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,+ instanceAware: false,+ isMcp: false,+ ...authOptions+ };+}+function isOidcProtocolMode(config2) {+ return config2.authOptions.authority.options.protocolMode === ProtocolMode.OIDC;+}+var DEFAULT_SYSTEM_OPTIONS, DEFAULT_LOGGER_IMPLEMENTATION, DEFAULT_NETWORK_IMPLEMENTATION, DEFAULT_LIBRARY_INFO, DEFAULT_CLIENT_CREDENTIALS, DEFAULT_AZURE_CLOUD_OPTIONS, DEFAULT_TELEMETRY_OPTIONS;+var init_ClientConfiguration = __esm({+ "node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs"() {+ "use strict";+ init_ICrypto();+ init_Logger();+ init_Constants();+ init_packageMetadata();+ init_AuthorityOptions();+ init_CacheManager();+ init_ProtocolMode();+ init_ClientAuthError();+ init_StubPerformanceClient();+ init_ClientAuthErrorCodes();+ DEFAULT_SYSTEM_OPTIONS = {+ tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,+ preventCorsPreflight: false+ };+ DEFAULT_LOGGER_IMPLEMENTATION = {+ loggerCallback: () => {+ },+ piiLoggingEnabled: false,+ logLevel: LogLevel.Info,+ correlationId: ""+ };+ DEFAULT_NETWORK_IMPLEMENTATION = {+ async sendGetRequestAsync() {+ throw createClientAuthError(methodNotImplemented, "");+ },+ async sendPostRequestAsync() {+ throw createClientAuthError(methodNotImplemented, "");+ }+ };+ DEFAULT_LIBRARY_INFO = {+ sku: SKU,+ version: version2,+ cpu: "",+ os: ""+ };+ DEFAULT_CLIENT_CREDENTIALS = {+ clientSecret: "",+ clientAssertion: void 0+ };+ DEFAULT_AZURE_CLOUD_OPTIONS = {+ azureCloudInstance: AzureCloudInstance.None,+ tenant: `${DEFAULT_COMMON_TENANT}`+ };+ DEFAULT_TELEMETRY_OPTIONS = {+ application: {+ appName: "",+ appVersion: ""+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs+var TokenCacheContext;+var init_TokenCacheContext = __esm({+ "node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs"() {+ "use strict";+ TokenCacheContext = class {+ constructor(tokenCache, hasChanged) {+ this.cache = tokenCache;+ this.hasChanged = hasChanged;+ }+ /**+ * boolean which indicates the changes in cache+ */+ get cacheHasChanged() {+ return this.hasChanged;+ }+ /**+ * function to retrieve the token cache+ */+ get tokenCache() {+ return this.cache;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs+var TimeUtils_exports = {};+__export(TimeUtils_exports, {+ delay: () => delay,+ isCacheExpired: () => isCacheExpired,+ isTokenExpired: () => isTokenExpired,+ nowSeconds: () => nowSeconds,+ toDateFromSeconds: () => toDateFromSeconds,+ toSecondsFromDate: () => toSecondsFromDate,+ wasClockTurnedBack: () => wasClockTurnedBack+});+function nowSeconds() {+ return Math.round((/* @__PURE__ */ new Date()).getTime() / 1e3);+}+function toSecondsFromDate(date3) {+ return date3.getTime() / 1e3;+}+function toDateFromSeconds(seconds) {+ if (seconds) {+ return new Date(Number(seconds) * 1e3);+ }+ return /* @__PURE__ */ new Date();+}+function isTokenExpired(expiresOn, offset) {+ const expirationSec = Number(expiresOn) || 0;+ const offsetCurrentTimeSec = nowSeconds() + offset;+ return offsetCurrentTimeSec > expirationSec;+}+function isCacheExpired(lastUpdatedAt, cacheRetentionDays) {+ const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1e3;+ return Date.now() > cacheExpirationTimestamp;+}+function wasClockTurnedBack(cachedAt) {+ const cachedAtSec = Number(cachedAt);+ return cachedAtSec > nowSeconds();+}+function delay(t, value) {+ return new Promise((resolve2) => setTimeout(() => resolve2(value), t));+}+var init_TimeUtils = __esm({+ "node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs+var CacheHelpers_exports = {};+__export(CacheHelpers_exports, {+ createAccessTokenEntity: () => createAccessTokenEntity,+ createIdTokenEntity: () => createIdTokenEntity,+ createRefreshTokenEntity: () => createRefreshTokenEntity,+ generateAppMetadataKey: () => generateAppMetadataKey,+ generateAuthorityMetadataExpiresAt: () => generateAuthorityMetadataExpiresAt,+ isAccessTokenEntity: () => isAccessTokenEntity,+ isAppMetadataEntity: () => isAppMetadataEntity,+ isAuthorityMetadataEntity: () => isAuthorityMetadataEntity,+ isAuthorityMetadataExpired: () => isAuthorityMetadataExpired,+ isCredentialEntity: () => isCredentialEntity,+ isIdTokenEntity: () => isIdTokenEntity,+ isRefreshTokenEntity: () => isRefreshTokenEntity,+ isServerTelemetryEntity: () => isServerTelemetryEntity,+ isThrottlingEntity: () => isThrottlingEntity,+ updateAuthorityEndpointMetadata: () => updateAuthorityEndpointMetadata,+ updateCloudDiscoveryMetadata: () => updateCloudDiscoveryMetadata+});+function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {+ const idTokenEntity = {+ credentialType: CredentialType.ID_TOKEN,+ homeAccountId,+ environment,+ clientId,+ secret: idToken,+ realm: tenantId,+ lastUpdatedAt: Date.now().toString()+ // Set the last updated time to now+ };+ return idTokenEntity;+}+function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, correlationId, refreshOn, tokenType, userAssertionHash, keyId, additionalCacheKeyComponents) {+ const atEntity = {+ homeAccountId,+ credentialType: CredentialType.ACCESS_TOKEN,+ secret: accessToken,+ cachedAt: nowSeconds().toString(),+ expiresOn: expiresOn.toString(),+ extendedExpiresOn: extExpiresOn.toString(),+ environment,+ clientId,+ realm: tenantId,+ target: scopes,+ tokenType: tokenType || AuthenticationScheme.BEARER,+ lastUpdatedAt: Date.now().toString()+ // Set the last updated time to now+ };+ if (userAssertionHash) {+ atEntity.userAssertionHash = userAssertionHash;+ }+ if (refreshOn) {+ atEntity.refreshOn = refreshOn.toString();+ }+ if (atEntity.tokenType?.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) {+ atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;+ switch (atEntity.tokenType) {+ case AuthenticationScheme.POP:+ const tokenClaims = extractTokenClaims(accessToken, base64Decode, correlationId);+ if (!tokenClaims?.cnf?.kid) {+ throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt, correlationId);+ }+ atEntity.keyId = tokenClaims.cnf.kid;+ break;+ case AuthenticationScheme.SSH:+ atEntity.keyId = keyId;+ }+ }+ if (additionalCacheKeyComponents && Object.keys(additionalCacheKeyComponents).length > 0) {+ atEntity.additionalCacheKeyComponents = additionalCacheKeyComponents;+ }+ return atEntity;+}+function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) {+ const rtEntity = {+ credentialType: CredentialType.REFRESH_TOKEN,+ homeAccountId,+ environment,+ clientId,+ secret: refreshToken,+ lastUpdatedAt: Date.now().toString()+ };+ if (userAssertionHash) {+ rtEntity.userAssertionHash = userAssertionHash;+ }+ if (familyId) {+ rtEntity.familyId = familyId;+ }+ if (expiresOn) {+ rtEntity.expiresOn = expiresOn.toString();+ }+ return rtEntity;+}+function isCredentialEntity(entity) {+ return entity.hasOwnProperty("homeAccountId") && entity.hasOwnProperty("environment") && entity.hasOwnProperty("credentialType") && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("secret");+}+function isAccessTokenEntity(entity) {+ if (!entity) {+ return false;+ }+ return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity.hasOwnProperty("target") && (entity["credentialType"] === CredentialType.ACCESS_TOKEN || entity["credentialType"] === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME);+}+function isIdTokenEntity(entity) {+ if (!entity) {+ return false;+ }+ return isCredentialEntity(entity) && entity.hasOwnProperty("realm") && entity["credentialType"] === CredentialType.ID_TOKEN;+}+function isRefreshTokenEntity(entity) {+ if (!entity) {+ return false;+ }+ return isCredentialEntity(entity) && entity["credentialType"] === CredentialType.REFRESH_TOKEN;+}+function isServerTelemetryEntity(key, entity) {+ const validateKey = key.indexOf(SERVER_TELEM_CACHE_KEY) === 0;+ let validateEntity = true;+ if (entity) {+ validateEntity = entity.hasOwnProperty("failedRequests") && entity.hasOwnProperty("errors") && entity.hasOwnProperty("cacheHits");+ }+ return validateKey && validateEntity;+}+function isThrottlingEntity(key, entity) {+ let validateKey = false;+ if (key) {+ validateKey = key.indexOf(THROTTLING_PREFIX) === 0;+ }+ let validateEntity = true;+ if (entity) {+ validateEntity = entity.hasOwnProperty("throttleTime");+ }+ return validateKey && validateEntity;+}+function generateAppMetadataKey({ environment, clientId }) {+ const appMetaDataKeyArray = [+ APP_METADATA,+ environment,+ clientId+ ];+ return appMetaDataKeyArray.join(CACHE_KEY_SEPARATOR).toLowerCase();+}+function isAppMetadataEntity(key, entity) {+ if (!entity) {+ return false;+ }+ return key.indexOf(APP_METADATA) === 0 && entity.hasOwnProperty("clientId") && entity.hasOwnProperty("environment");+}+function isAuthorityMetadataEntity(key, entity) {+ if (!entity) {+ return false;+ }+ return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) === 0 && entity.hasOwnProperty("aliases") && entity.hasOwnProperty("preferred_cache") && entity.hasOwnProperty("preferred_network") && entity.hasOwnProperty("canonical_authority") && entity.hasOwnProperty("authorization_endpoint") && entity.hasOwnProperty("token_endpoint") && entity.hasOwnProperty("issuer") && entity.hasOwnProperty("aliasesFromNetwork") && entity.hasOwnProperty("endpointsFromNetwork") && entity.hasOwnProperty("expiresAt") && entity.hasOwnProperty("jwks_uri");+}+function generateAuthorityMetadataExpiresAt() {+ return nowSeconds() + AUTHORITY_METADATA_REFRESH_TIME_SECONDS;+}+function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) {+ authorityMetadata.authorization_endpoint = updatedValues.authorization_endpoint;+ authorityMetadata.token_endpoint = updatedValues.token_endpoint;+ authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;+ authorityMetadata.issuer = updatedValues.issuer;+ authorityMetadata.endpointsFromNetwork = fromNetwork;+ authorityMetadata.jwks_uri = updatedValues.jwks_uri;+}+function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) {+ authorityMetadata.aliases = updatedValues.aliases;+ authorityMetadata.preferred_cache = updatedValues.preferred_cache;+ authorityMetadata.preferred_network = updatedValues.preferred_network;+ authorityMetadata.aliasesFromNetwork = fromNetwork;+}+function isAuthorityMetadataExpired(metadata) {+ return metadata.expiresAt <= nowSeconds();+}+var init_CacheHelpers = __esm({+ "node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs"() {+ "use strict";+ init_AuthToken();+ init_ClientAuthError();+ init_Constants();+ init_TimeUtils();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvents.mjs+var NetworkClientSendPostRequestAsync, RefreshTokenClientExecutePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, RefreshTokenClientExecuteTokenRequest, RefreshTokenClientAcquireToken, RefreshTokenClientAcquireTokenWithCachedRefreshToken, RefreshTokenClientCreateTokenRequestBody, SilentFlowClientGenerateResultFromCacheRecord, AuthClientExecuteTokenRequest, AuthClientCreateTokenRequestBody, UpdateTokenEndpointAuthority, PopTokenGenerateCnf, HandleServerTokenResponse, AuthorityResolveEndpointsAsync, AuthorityGetCloudDiscoveryMetadataFromNetwork, AuthorityUpdateCloudDiscoveryMetadata, AuthorityGetEndpointMetadataFromNetwork, AuthorityUpdateEndpointMetadata, AuthorityUpdateMetadataWithRegionalInformation, RegionDiscoveryDetectRegion, RegionDiscoveryGetRegionFromIMDS, RegionDiscoveryGetCurrentVersion, CacheManagerGetRefreshToken;+var init_PerformanceEvents = __esm({+ "node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvents.mjs"() {+ "use strict";+ NetworkClientSendPostRequestAsync = "networkClientSendPostRequestAsync";+ RefreshTokenClientExecutePostToTokenEndpoint = "refreshTokenClientExecutePostToTokenEndpoint";+ AuthorizationCodeClientExecutePostToTokenEndpoint = "authorizationCodeClientExecutePostToTokenEndpoint";+ RefreshTokenClientExecuteTokenRequest = "refreshTokenClientExecuteTokenRequest";+ RefreshTokenClientAcquireToken = "refreshTokenClientAcquireToken";+ RefreshTokenClientAcquireTokenWithCachedRefreshToken = "refreshTokenClientAcquireTokenWithCachedRefreshToken";+ RefreshTokenClientCreateTokenRequestBody = "refreshTokenClientCreateTokenRequestBody";+ SilentFlowClientGenerateResultFromCacheRecord = "silentFlowClientGenerateResultFromCacheRecord";+ AuthClientExecuteTokenRequest = "authClientExecuteTokenRequest";+ AuthClientCreateTokenRequestBody = "authClientCreateTokenRequestBody";+ UpdateTokenEndpointAuthority = "updateTokenEndpointAuthority";+ PopTokenGenerateCnf = "popTokenGenerateCnf";+ HandleServerTokenResponse = "handleServerTokenResponse";+ AuthorityResolveEndpointsAsync = "authorityResolveEndpointsAsync";+ AuthorityGetCloudDiscoveryMetadataFromNetwork = "authorityGetCloudDiscoveryMetadataFromNetwork";+ AuthorityUpdateCloudDiscoveryMetadata = "authorityUpdateCloudDiscoveryMetadata";+ AuthorityGetEndpointMetadataFromNetwork = "authorityGetEndpointMetadataFromNetwork";+ AuthorityUpdateEndpointMetadata = "authorityUpdateEndpointMetadata";+ AuthorityUpdateMetadataWithRegionalInformation = "authorityUpdateMetadataWithRegionalInformation";+ RegionDiscoveryDetectRegion = "regionDiscoveryDetectRegion";+ RegionDiscoveryGetRegionFromIMDS = "regionDiscoveryGetRegionFromIMDS";+ RegionDiscoveryGetCurrentVersion = "regionDiscoveryGetCurrentVersion";+ CacheManagerGetRefreshToken = "cacheManagerGetRefreshToken";+ }+});++// node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs+var invoke, invokeAsync;+var init_FunctionWrappers = __esm({+ "node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs"() {+ "use strict";+ invoke = (callback, eventName, logger2, telemetryClient, correlationId) => {+ return (...args) => {+ logger2.trace(`Executing function '${eventName}'`, correlationId);+ const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);+ if (correlationId) {+ telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);+ }+ try {+ const result = callback(...args);+ inProgressEvent.end({+ success: true+ });+ logger2.trace(`Returning result from '${eventName}'`, correlationId);+ return result;+ } catch (e) {+ logger2.trace(`Error occurred in '${eventName}'`, correlationId);+ try {+ logger2.trace(JSON.stringify(e), correlationId);+ } catch (e2) {+ logger2.trace("Unable to print error message.", correlationId);+ }+ inProgressEvent.end({+ success: false+ }, e);+ throw e;+ }+ };+ };+ invokeAsync = (callback, eventName, logger2, telemetryClient, correlationId) => {+ return (...args) => {+ logger2.trace(`Executing function '${eventName}'`, correlationId);+ const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);+ if (correlationId) {+ telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);+ }+ return callback(...args).then((response) => {+ logger2.trace(`Returning result from '${eventName}'`, correlationId);+ inProgressEvent.end({+ success: true+ });+ return response;+ }).catch((e) => {+ logger2.trace(`Error occurred in '${eventName}'`, correlationId);+ try {+ logger2.trace(JSON.stringify(e), correlationId);+ } catch (e2) {+ logger2.trace("Unable to print error message.", correlationId);+ }+ inProgressEvent.end({+ success: false+ }, e);+ throw e;+ });+ };+ };+ }+});++// node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs+var KeyLocation, PopTokenGenerator;+var init_PopTokenGenerator = __esm({+ "node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs"() {+ "use strict";+ init_TimeUtils();+ init_UrlString();+ init_PerformanceEvents();+ init_FunctionWrappers();+ KeyLocation = {+ SW: "sw"+ };+ PopTokenGenerator = class {+ constructor(cryptoUtils, performanceClient) {+ this.cryptoUtils = cryptoUtils;+ this.performanceClient = performanceClient;+ }+ /**+ * Generates the req_cnf validated at the RP in the POP protocol for SHR parameters+ * and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash+ * @param request+ * @returns+ */+ async generateCnf(request, logger2) {+ const reqCnf = await invokeAsync(this.generateKid.bind(this), PopTokenGenerateCnf, logger2, this.performanceClient, request.correlationId)(request);+ const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf));+ return {+ kid: reqCnf.kid,+ reqCnfString+ };+ }+ /**+ * Generates key_id for a SHR token request+ * @param request+ * @returns+ */+ async generateKid(request) {+ const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request);+ return {+ kid: kidThumbprint,+ xms_ksl: KeyLocation.SW+ };+ }+ /**+ * Signs the POP access_token with the local generated key-pair+ * @param accessToken+ * @param request+ * @returns+ */+ async signPopToken(accessToken, keyId, request) {+ return this.signPayload(accessToken, keyId, request);+ }+ /**+ * Utility function to generate the signed JWT for an access_token+ * @param payload+ * @param kid+ * @param request+ * @param claims+ * @returns+ */+ async signPayload(payload, keyId, request, claims) {+ const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions } = request;+ const resourceUrlString = resourceRequestUri ? new UrlString(resourceRequestUri, request.correlationId) : void 0;+ const resourceUrlComponents = resourceUrlString?.getUrlComponents();+ return this.cryptoUtils.signJwt({+ at: payload,+ ts: nowSeconds(),+ m: resourceRequestMethod?.toUpperCase(),+ u: resourceUrlComponents?.HostNameAndPort,+ nonce: shrNonce || this.cryptoUtils.createNewGuid(),+ p: resourceUrlComponents?.AbsolutePath,+ q: resourceUrlComponents?.QueryString ? [[], resourceUrlComponents.QueryString] : void 0,+ client_claims: shrClaims || void 0,+ ...claims+ }, keyId, shrOptions, request.correlationId);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs+var noTokensFound, refreshTokenExpired, uiNotAllowed, interactionRequired, consentRequired, loginRequired, badToken, interruptedUser;+var init_InteractionRequiredAuthErrorCodes = __esm({+ "node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs"() {+ "use strict";+ noTokensFound = "no_tokens_found";+ refreshTokenExpired = "refresh_token_expired";+ uiNotAllowed = "ui_not_allowed";+ interactionRequired = "interaction_required";+ consentRequired = "consent_required";+ loginRequired = "login_required";+ badToken = "bad_token";+ interruptedUser = "interrupted_user";+ }+});++// node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs+function isInteractionRequiredError(errorCode, errorString, subError) {+ const isInteractionRequiredErrorCode = !!errorCode && InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;+ const isInteractionRequiredSubError = !!subError && InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;+ const isInteractionRequiredErrorDesc = !!errorString && InteractionRequiredServerErrorMessage.some((irErrorCode) => {+ return errorString.indexOf(irErrorCode) > -1;+ });+ return isInteractionRequiredErrorCode || isInteractionRequiredErrorDesc || isInteractionRequiredSubError;+}+function createInteractionRequiredAuthError(errorCode, correlationId, errorMessage) {+ return new InteractionRequiredAuthError(errorCode, correlationId, errorMessage);+}+var InteractionRequiredServerErrorMessage, InteractionRequiredAuthSubErrorMessage, InteractionRequiredAuthError;+var init_InteractionRequiredAuthError = __esm({+ "node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs"() {+ "use strict";+ init_AuthError();+ init_InteractionRequiredAuthErrorCodes();+ InteractionRequiredServerErrorMessage = [+ interactionRequired,+ consentRequired,+ loginRequired,+ badToken,+ uiNotAllowed,+ interruptedUser+ ];+ InteractionRequiredAuthSubErrorMessage = [+ "message_only",+ "additional_action",+ "basic_action",+ "user_password_expired",+ "consent_required",+ "bad_token",+ "ui_not_allowed",+ "interrupted_user"+ ];+ InteractionRequiredAuthError = class _InteractionRequiredAuthError extends AuthError {+ constructor(errorCode, correlationId, errorMessage, subError, timestamp, traceId, claims, errorNo) {+ super(errorCode, correlationId, errorMessage, subError);+ Object.setPrototypeOf(this, _InteractionRequiredAuthError.prototype);+ this.timestamp = timestamp || "";+ this.traceId = traceId || "";+ this.claims = claims || "";+ this.name = "InteractionRequiredAuthError";+ this.errorNo = errorNo;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/ServerError.mjs+var ServerError;+var init_ServerError = __esm({+ "node_modules/@azure/msal-common/dist/error/ServerError.mjs"() {+ "use strict";+ init_AuthError();+ ServerError = class _ServerError extends AuthError {+ constructor(errorCode, correlationId, errorMessage, subError, errorNo, status) {+ super(errorCode, correlationId, errorMessage, subError);+ this.name = "ServerError";+ this.errorNo = errorNo;+ this.status = status;+ Object.setPrototypeOf(this, _ServerError.prototype);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs+function parseRequestState(base64Decode, state, correlationId) {+ if (!base64Decode) {+ throw createClientAuthError(noCryptoObject, correlationId);+ }+ if (!state) {+ throw createClientAuthError(invalidState, correlationId);+ }+ try {+ const splitState = state.split(RESOURCE_DELIM);+ const libraryState = splitState[0];+ const userState = splitState.length > 1 ? splitState.slice(1).join(RESOURCE_DELIM) : "";+ const libraryStateString = base64Decode(libraryState);+ const libraryStateObj = JSON.parse(libraryStateString);+ return {+ userRequestState: userState || "",+ libraryState: libraryStateObj+ };+ } catch (e) {+ throw createClientAuthError(invalidState, correlationId);+ }+}+var init_ProtocolUtils = __esm({+ "node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs"() {+ "use strict";+ init_Constants();+ init_ClientAuthError();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs+function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger2, performanceClient) {+ logger2?.verbose("setCachedAccount called", correlationId);+ const accountEnvironment = environment || authority.getPreferredCache();+ const matchedAccounts = cacheStorage.getAccountsFilteredBy({ homeAccountId, environment: accountEnvironment }, correlationId);+ performanceClient?.addFields({ cacheMatchedAccounts: matchedAccounts.length }, correlationId);+ if (matchedAccounts.length > 1) {+ logger2?.warning("Multiple base accounts matched homeAccountId. Ignoring cached account and creating a new base account.", correlationId);+ }+ const cachedAccount = matchedAccounts.length === 1 ? matchedAccounts[0] : null;+ const baseAccount = cachedAccount || createAccountEntity({+ homeAccountId,+ idTokenClaims,+ clientInfo,+ environment,+ cloudGraphHostName: authCodePayload?.cloud_graph_host_name,+ msGraphHost: authCodePayload?.msgraph_host,+ nativeAccountId+ }, authority, correlationId, base64Decode);+ const tenantProfiles = baseAccount.tenantProfiles || [];+ const tenantId = claimsTenantId || baseAccount.realm;+ if (tenantId && !tenantProfiles.find((tenantProfile) => {+ return tenantProfile.tenantId === tenantId;+ })) {+ const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, nativeAccountId, idTokenClaims);+ tenantProfiles.push(newTenantProfile);+ }+ baseAccount.tenantProfiles = tenantProfiles;+ return baseAccount;+}+var ResponseHandler;+var init_ResponseHandler = __esm({+ "node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs"() {+ "use strict";+ init_AccountInfo();+ init_AuthToken();+ init_TokenClaims();+ init_TokenCacheContext();+ init_AccountEntityUtils();+ init_CacheHelpers();+ init_PopTokenGenerator();+ init_ClientAuthError();+ init_InteractionRequiredAuthError();+ init_ServerError();+ init_ScopeSet();+ init_Constants();+ init_ProtocolUtils();+ init_TimeUtils();+ init_ClientAuthErrorCodes();+ ResponseHandler = class _ResponseHandler {+ constructor(clientId, cacheStorage, cryptoObj, logger2, performanceClient, serializableCache, persistencePlugin) {+ this.clientId = clientId;+ this.cacheStorage = cacheStorage;+ this.cryptoObj = cryptoObj;+ this.logger = logger2;+ this.performanceClient = performanceClient;+ this.serializableCache = serializableCache;+ this.persistencePlugin = persistencePlugin;+ }+ /**+ * Function which validates server authorization token response.+ * @param serverResponse+ * @param correlationId+ * @param refreshAccessToken+ */+ validateTokenResponse(serverResponse, correlationId, refreshAccessToken) {+ if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {+ const errString = `Error(s): ${serverResponse.error_codes || NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || NOT_AVAILABLE} - Description: ${serverResponse.error_description || NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || NOT_AVAILABLE}`;+ const serverErrorNo = serverResponse.error_codes?.length ? serverResponse.error_codes[0] : void 0;+ const serverError = new ServerError(serverResponse.error || "", serverResponse.correlation_id || "", errString, serverResponse.suberror, serverErrorNo, serverResponse.status);+ if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_SERVER_ERROR_RANGE_START && serverResponse.status <= HTTP_SERVER_ERROR_RANGE_END) {+ this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.+${serverError}`, correlationId);+ return;+ } else if (refreshAccessToken && serverResponse.status && serverResponse.status >= HTTP_CLIENT_ERROR_RANGE_START && serverResponse.status <= HTTP_CLIENT_ERROR_RANGE_END) {+ this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.+${serverError}`, correlationId);+ return;+ }+ if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {+ throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.correlation_id || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.claims || "", serverErrorNo);+ }+ throw serverError;+ }+ }+ /**+ * Returns a constructed token response based on given string. Also manages the cache updates and cleanups.+ * @param serverTokenResponse+ * @param authority+ */+ async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, apiId, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId, additionalCacheKeyComponents) {+ let idTokenClaims;+ if (serverTokenResponse.id_token) {+ idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || "", this.cryptoObj.base64Decode, request.correlationId);+ if (authCodePayload && authCodePayload.nonce) {+ if (idTokenClaims.nonce !== authCodePayload.nonce) {+ throw createClientAuthError(nonceMismatch, request.correlationId);+ }+ }+ }+ this.homeAccountIdentifier = generateHomeAccountId(serverTokenResponse.client_info || "", authority.authorityType, this.logger, this.cryptoObj, request.correlationId, idTokenClaims);+ let requestStateObj;+ if (!!authCodePayload && !!authCodePayload.state) {+ requestStateObj = parseRequestState(this.cryptoObj.base64Decode, authCodePayload.state, request.correlationId);+ }+ serverTokenResponse.key_id = serverTokenResponse.key_id || request.sshKid || void 0;+ const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload, additionalCacheKeyComponents);+ let cacheContext;+ try {+ if (this.persistencePlugin && this.serializableCache) {+ this.logger.verbose("Persistence enabled, calling beforeCacheAccess", request.correlationId);+ cacheContext = new TokenCacheContext(this.serializableCache, true);+ await this.persistencePlugin.beforeCacheAccess(cacheContext);+ }+ if (handlingRefreshTokenResponse && !forceCacheRefreshTokenResponse && cacheRecord.account) {+ const cachedAccounts = this.cacheStorage.getAllAccounts({+ homeAccountId: cacheRecord.account.homeAccountId,+ environment: cacheRecord.account.environment+ }, request.correlationId);+ if (cachedAccounts.length < 1) {+ this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache", request.correlationId);+ this.performanceClient?.addFields({+ acntLoggedOut: true+ }, request.correlationId);+ return await _ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, void 0, serverRequestId);+ }+ }+ await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), apiId, request.storeInCache);+ } finally {+ if (this.persistencePlugin && this.serializableCache && cacheContext) {+ this.logger.verbose("Persistence enabled, calling afterCacheAccess", request.correlationId);+ await this.persistencePlugin.afterCacheAccess(cacheContext);+ }+ }+ return _ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId);+ }+ /**+ * Generates CacheRecord+ * @param serverTokenResponse+ * @param idTokenObj+ * @param authority+ */+ generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload, additionalCacheKeyComponents) {+ const env = authority.getPreferredCache();+ if (!env) {+ throw createClientAuthError(invalidCacheEnvironment, request.correlationId);+ }+ const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);+ let cachedIdToken;+ let cachedAccount;+ if (serverTokenResponse.id_token && !!idTokenClaims) {+ cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || "");+ cachedAccount = buildAccountToCache(+ this.cacheStorage,+ authority,+ this.homeAccountIdentifier,+ this.cryptoObj.base64Decode,+ request.correlationId,+ idTokenClaims,+ serverTokenResponse.client_info,+ env,+ claimsTenantId,+ authCodePayload,+ void 0,+ // nativeAccountId+ this.logger,+ this.performanceClient+ );+ }+ let cachedAccessToken = null;+ if (serverTokenResponse.access_token) {+ const responseScopes = serverTokenResponse.scope ? ScopeSet.fromString(serverTokenResponse.scope, request.correlationId) : new ScopeSet(request.scopes || [], request.correlationId);+ const expiresIn = (typeof serverTokenResponse.expires_in === "string" ? parseInt(serverTokenResponse.expires_in, 10) : serverTokenResponse.expires_in) || 0;+ const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" ? parseInt(serverTokenResponse.ext_expires_in, 10) : serverTokenResponse.ext_expires_in) || 0;+ const refreshIn = (typeof serverTokenResponse.refresh_in === "string" ? parseInt(serverTokenResponse.refresh_in, 10) : serverTokenResponse.refresh_in) || void 0;+ const tokenExpirationSeconds = reqTimestamp + expiresIn;+ const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;+ const refreshOnSeconds = refreshIn && refreshIn > 0 ? reqTimestamp + refreshIn : void 0;+ cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, request.correlationId, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, additionalCacheKeyComponents);+ const resource = request.resource || null;+ if (resource) {+ cachedAccessToken.resource = resource;+ }+ }+ let cachedRefreshToken = null;+ if (serverTokenResponse.refresh_token) {+ let rtExpiresOn;+ if (serverTokenResponse.refresh_token_expires_in) {+ const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in === "string" ? parseInt(serverTokenResponse.refresh_token_expires_in, 10) : serverTokenResponse.refresh_token_expires_in;+ rtExpiresOn = reqTimestamp + rtExpiresIn;+ this.performanceClient?.addFields({ ntwkRtExpiresOnSeconds: rtExpiresOn }, request.correlationId);+ }+ cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn);+ }+ let cachedAppMetadata = null;+ if (serverTokenResponse.foci) {+ cachedAppMetadata = {+ clientId: this.clientId,+ environment: env,+ familyId: serverTokenResponse.foci+ };+ }+ return {+ account: cachedAccount,+ idToken: cachedIdToken,+ accessToken: cachedAccessToken,+ refreshToken: cachedRefreshToken,+ appMetadata: cachedAppMetadata+ };+ }+ /**+ * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.+ *+ * Optionally takes a state string that is set as-is in the response.+ *+ * @param cacheRecord+ * @param idTokenObj+ * @param fromTokenCache+ * @param stateString+ */+ static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, performanceClient, idTokenClaims, requestState, serverTokenResponse, requestId) {+ let accessToken = "";+ let responseScopes = [];+ let expiresOn = null;+ let extExpiresOn;+ let refreshOn;+ let familyId = "";+ if (cacheRecord.accessToken) {+ if (cacheRecord.accessToken.tokenType === AuthenticationScheme.POP && !request.popKid) {+ const popTokenGenerator = new PopTokenGenerator(cryptoObj, performanceClient);+ const { secret, keyId } = cacheRecord.accessToken;+ if (!keyId) {+ throw createClientAuthError(keyIdMissing, request.correlationId);+ }+ accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);+ } else {+ accessToken = cacheRecord.accessToken.secret;+ }+ responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target, request.correlationId).asArray();+ expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);+ extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);+ if (cacheRecord.accessToken.refreshOn) {+ refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn);+ }+ }+ if (cacheRecord.appMetadata) {+ familyId = cacheRecord.appMetadata.familyId === THE_FAMILY_ID ? THE_FAMILY_ID : "";+ }+ const uid = idTokenClaims?.oid || idTokenClaims?.sub || "";+ const tid = idTokenClaims?.tid || "";+ if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {+ cacheRecord.account.nativeAccountId = serverTokenResponse?.spa_accountid;+ const targetTenantId = tid || cacheRecord.account.realm;+ if (cacheRecord.account.tenantProfiles) {+ const matchingProfile = cacheRecord.account.tenantProfiles.find((tp) => tp.tenantId === targetTenantId);+ if (matchingProfile) {+ matchingProfile.nativeAccountId = serverTokenResponse.spa_accountid;+ }+ }+ }+ const accountInfo = cacheRecord.account ? updateAccountTenantProfileData(+ getAccountInfo(cacheRecord.account),+ void 0,+ // tenantProfile optional+ idTokenClaims,+ cacheRecord.idToken?.secret+ ) : null;+ return {+ authority: authority.canonicalAuthority,+ uniqueId: uid,+ tenantId: tid,+ scopes: responseScopes,+ account: accountInfo,+ idToken: cacheRecord?.idToken?.secret || "",+ idTokenClaims: idTokenClaims || {},+ accessToken,+ fromCache: fromTokenCache,+ expiresOn,+ extExpiresOn,+ refreshOn,+ correlationId: request.correlationId,+ requestId: requestId || "",+ familyId,+ tokenType: cacheRecord.accessToken?.tokenType || "",+ state: requestState ? requestState.userRequestState : "",+ cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || "",+ msGraphHost: cacheRecord.account?.msGraphHost || "",+ code: serverTokenResponse?.spa_code,+ fromPlatformBroker: false+ };+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/account/CcsCredential.mjs+var CcsCredentialType;+var init_CcsCredential = __esm({+ "node_modules/@azure/msal-common/dist/account/CcsCredential.mjs"() {+ "use strict";+ CcsCredentialType = {+ HOME_ACCOUNT_ID: "home_account_id",+ UPN: "UPN"+ };+ }+});++// node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs+async function getClientAssertion(clientAssertion, clientId, tokenEndpoint, fmiPath) {+ if (typeof clientAssertion === "string") {+ return clientAssertion;+ } else {+ const config2 = {+ clientId,+ tokenEndpoint,+ fmiPath+ };+ return clientAssertion(config2);+ }+}+var init_ClientAssertionUtils = __esm({+ "node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs+function getRequestThumbprint(clientId, request, homeAccountId) {+ return {+ clientId,+ authority: request.authority,+ scopes: request.scopes,+ homeAccountIdentifier: homeAccountId,+ claims: request.claims,+ authenticationScheme: request.authenticationScheme,+ resourceRequestMethod: request.resourceRequestMethod,+ resourceRequestUri: request.resourceRequestUri,+ shrClaims: request.shrClaims,+ sshKid: request.sshKid,+ embeddedClientId: request.embeddedClientId || request.extraParameters?.clientId,+ resource: request.resource+ };+}+var init_RequestThumbprint = __esm({+ "node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs+var ThrottlingUtils;+var init_ThrottlingUtils = __esm({+ "node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs"() {+ "use strict";+ init_Constants();+ init_ServerError();+ init_RequestThumbprint();+ ThrottlingUtils = class _ThrottlingUtils {+ /**+ * Prepares a RequestThumbprint to be stored as a key.+ * @param thumbprint+ */+ static generateThrottlingStorageKey(thumbprint) {+ return `${THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;+ }+ /**+ * Performs necessary throttling checks before a network request.+ * @param cacheManager+ * @param thumbprint+ */+ static preProcess(cacheManager, thumbprint, correlationId) {+ const key = _ThrottlingUtils.generateThrottlingStorageKey(thumbprint);+ const value = cacheManager.getThrottlingCache(key, correlationId);+ if (value) {+ if (value.throttleTime < Date.now()) {+ cacheManager.removeItem(key, correlationId);+ return;+ }+ throw new ServerError(value.errorCodes?.join(" ") || "", correlationId, value.errorMessage, value.subError);+ }+ }+ /**+ * Performs necessary throttling checks after a network request.+ * @param cacheManager+ * @param thumbprint+ * @param response+ */+ static postProcess(cacheManager, thumbprint, response, correlationId) {+ if (_ThrottlingUtils.checkResponseStatus(response) || _ThrottlingUtils.checkResponseForRetryAfter(response)) {+ const thumbprintValue = {+ throttleTime: _ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),+ error: response.body.error,+ errorCodes: response.body.error_codes,+ errorMessage: response.body.error_description,+ subError: response.body.suberror+ };+ cacheManager.setThrottlingCache(_ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId);+ }+ }+ /**+ * Checks a NetworkResponse object's status codes against 429 or 5xx+ * @param response+ */+ static checkResponseStatus(response) {+ return response.status === 429 || response.status >= 500 && response.status < 600;+ }+ /**+ * Checks a NetworkResponse object's RetryAfter header+ * @param response+ */+ static checkResponseForRetryAfter(response) {+ if (response.headers) {+ return response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && (response.status < 200 || response.status >= 300);+ }+ return false;+ }+ /**+ * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.+ * @param throttleTime+ */+ static calculateThrottleTime(throttleTime) {+ const time3 = throttleTime <= 0 ? 0 : throttleTime;+ const currentSeconds = Date.now() / 1e3;+ return Math.floor(Math.min(currentSeconds + (time3 || DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1e3);+ }+ static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) {+ const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier);+ const key = this.generateThrottlingStorageKey(thumbprint);+ cacheManager.removeItem(key, request.correlationId);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/error/NetworkError.mjs+function createNetworkError(error2, httpStatus, responseHeaders, additionalError) {+ error2.errorMessage = `${error2.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`;+ return new NetworkError(error2, httpStatus, responseHeaders);+}+var NetworkError;+var init_NetworkError = __esm({+ "node_modules/@azure/msal-common/dist/error/NetworkError.mjs"() {+ "use strict";+ init_AuthError();+ NetworkError = class _NetworkError extends AuthError {+ constructor(error2, httpStatus, responseHeaders) {+ super(error2.errorCode, error2.correlationId, error2.errorMessage, error2.subError);+ Object.setPrototypeOf(this, _NetworkError.prototype);+ this.name = "NetworkError";+ this.error = error2;+ this.httpStatus = httpStatus;+ this.responseHeaders = responseHeaders;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/protocol/Token.mjs+var Token_exports = {};+__export(Token_exports, {+ createTokenQueryParameters: () => createTokenQueryParameters,+ createTokenRequestHeaders: () => createTokenRequestHeaders,+ executePostToTokenEndpoint: () => executePostToTokenEndpoint,+ sendPostRequest: () => sendPostRequest+});+function createTokenRequestHeaders(logger2, preventCorsPreflight, ccsCred) {+ const headers = {};+ headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;+ if (!preventCorsPreflight && ccsCred) {+ switch (ccsCred.type) {+ case CcsCredentialType.HOME_ACCOUNT_ID:+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);+ headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;+ } catch (e) {+ logger2.verbose(`Could not parse home account ID for CCS Header: '${e}'`, "");+ }+ break;+ case CcsCredentialType.UPN:+ headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;+ break;+ }+ }+ return headers;+}+function createTokenQueryParameters(request, clientId, redirectUri, performanceClient) {+ const parameters = /* @__PURE__ */ new Map();+ if (request.embeddedClientId) {+ addBrokerParameters(parameters, clientId, redirectUri);+ }+ if (request.extraQueryParameters) {+ addExtraParameters(parameters, request.extraQueryParameters);+ }+ addCorrelationId(parameters, request.correlationId);+ instrumentBrokerParams(parameters, request.correlationId, performanceClient);+ return mapToQueryString(parameters);+}+async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger2, performanceClient, serverTelemetryManager) {+ const response = await sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers }, correlationId, cacheManager, networkClient, logger2, performanceClient);+ if (serverTelemetryManager && response.status < 500 && response.status !== 429) {+ serverTelemetryManager.clearTelemetryCache();+ }+ return response;+}+async function sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, cacheManager, networkClient, logger2, performanceClient) {+ ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);+ let response;+ try {+ response = await invokeAsync(networkClient.sendPostRequestAsync.bind(networkClient), NetworkClientSendPostRequestAsync, logger2, performanceClient, correlationId)(tokenEndpoint, options);+ const responseHeaders = response.headers || {};+ performanceClient?.addFields({+ refreshTokenSize: response.body.refresh_token?.length || 0,+ httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",+ requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || ""+ }, correlationId);+ } catch (e) {+ if (e instanceof NetworkError) {+ const responseHeaders = e.responseHeaders;+ if (responseHeaders) {+ performanceClient?.addFields({+ httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",+ requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",+ contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] || void 0,+ contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] || void 0,+ httpStatus: e.httpStatus+ }, correlationId);+ }+ throw e.error;+ }+ if (e instanceof AuthError) {+ throw e;+ } else {+ throw createClientAuthError(networkError, correlationId);+ }+ }+ ThrottlingUtils.postProcess(cacheManager, thumbprint, response, correlationId);+ return response;+}+var init_Token = __esm({+ "node_modules/@azure/msal-common/dist/protocol/Token.mjs"() {+ "use strict";+ init_CcsCredential();+ init_ClientInfo();+ init_Constants();+ init_RequestParameterBuilder();+ init_UrlUtils();+ init_ThrottlingUtils();+ init_NetworkError();+ init_AuthError();+ init_ClientAuthError();+ init_FunctionWrappers();+ init_PerformanceEvents();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs+function isOpenIdConfigResponse(response) {+ return response.hasOwnProperty("authorization_endpoint") && response.hasOwnProperty("token_endpoint") && response.hasOwnProperty("issuer") && response.hasOwnProperty("jwks_uri");+}+var init_OpenIdConfigResponse = __esm({+ "node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs+function isCloudInstanceDiscoveryResponse(response) {+ return response.hasOwnProperty("tenant_discovery_endpoint") && response.hasOwnProperty("metadata");+}+var init_CloudInstanceDiscoveryResponse = __esm({+ "node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs+function isCloudInstanceDiscoveryErrorResponse(response) {+ return response.hasOwnProperty("error") && response.hasOwnProperty("error_description");+}+var init_CloudInstanceDiscoveryErrorResponse = __esm({+ "node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs+var RegionDiscovery;+var init_RegionDiscovery = __esm({+ "node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs"() {+ "use strict";+ init_Constants();+ init_PerformanceEvents();+ init_FunctionWrappers();+ RegionDiscovery = class _RegionDiscovery {+ constructor(networkInterface, logger2, performanceClient, correlationId) {+ this.networkInterface = networkInterface;+ this.logger = logger2;+ this.performanceClient = performanceClient;+ this.correlationId = correlationId;+ }+ /**+ * Detect the region from the application's environment.+ *+ * @returns Promise<string | null>+ */+ async detectRegion(environmentRegion, regionDiscoveryMetadata) {+ let autodetectedRegionName = environmentRegion;+ if (!autodetectedRegionName) {+ const options = _RegionDiscovery.IMDS_OPTIONS;+ try {+ const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(IMDS_VERSION, options);+ if (localIMDSVersionResponse.status === HTTP_SUCCESS) {+ autodetectedRegionName = localIMDSVersionResponse.body?.location;+ if (autodetectedRegionName) {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;+ }+ }+ if (localIMDSVersionResponse.status === HTTP_BAD_REQUEST) {+ const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options);+ if (!currentIMDSVersion) {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;+ return null;+ }+ const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options);+ if (currentIMDSVersionResponse.status === HTTP_SUCCESS) {+ autodetectedRegionName = currentIMDSVersionResponse.body?.location;+ if (autodetectedRegionName) {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;+ }+ }+ }+ } catch (e) {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;+ return null;+ }+ } else {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.ENVIRONMENT_VARIABLE;+ }+ if (!autodetectedRegionName) {+ regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;+ }+ return autodetectedRegionName || null;+ }+ /**+ * Make the call to the IMDS endpoint+ *+ * @param version+ * @param options+ * @returns Promise<NetworkResponse<ImdsComputeResponse>>+ */+ async getRegionFromIMDS(version4, options) {+ return this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?api-version=${version4}`, options, IMDS_TIMEOUT);+ }+ /**+ * Get the most recent version of the IMDS endpoint available+ *+ * @returns Promise<string | null>+ */+ async getCurrentVersion(options) {+ try {+ const response = await this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?format=json`, options);+ if (response.status === HTTP_BAD_REQUEST && response.body && response.body["newest-versions"] && response.body["newest-versions"].length > 0) {+ return response.body["newest-versions"][0];+ }+ return null;+ } catch (e) {+ return null;+ }+ }+ };+ RegionDiscovery.IMDS_OPTIONS = {+ headers: {+ Metadata: "true"+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/authority/Authority.mjs+function getTenantFromAuthorityString(authority, correlationId) {+ const authorityUrl = new UrlString(authority, correlationId);+ const authorityUrlComponents = authorityUrl.getUrlComponents();+ const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase();+ switch (tenantId) {+ case AADAuthority.COMMON:+ case AADAuthority.ORGANIZATIONS:+ case AADAuthority.CONSUMERS:+ return void 0;+ default:+ return tenantId;+ }+}+function formatAuthorityUri(authorityUri) {+ return authorityUri.endsWith(FORWARD_SLASH) ? authorityUri : `${authorityUri}${FORWARD_SLASH}`;+}+function buildStaticAuthorityOptions(authOptions) {+ const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;+ let cloudDiscoveryMetadata = void 0;+ if (rawCloudDiscoveryMetadata) {+ try {+ cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);+ } catch (e) {+ throw createClientConfigurationError(invalidCloudDiscoveryMetadata, "");+ }+ }+ return {+ canonicalAuthority: authOptions.authority ? formatAuthorityUri(authOptions.authority) : void 0,+ knownAuthorities: authOptions.knownAuthorities,+ cloudDiscoveryMetadata+ };+}+var Authority;+var init_Authority = __esm({+ "node_modules/@azure/msal-common/dist/authority/Authority.mjs"() {+ "use strict";+ init_AuthorityType();+ init_OpenIdConfigResponse();+ init_UrlString();+ init_ClientAuthError();+ init_Constants();+ init_AuthorityMetadata();+ init_ClientConfigurationError();+ init_ProtocolMode();+ init_AuthorityOptions();+ init_CloudInstanceDiscoveryResponse();+ init_CloudInstanceDiscoveryErrorResponse();+ init_RegionDiscovery();+ init_AuthError();+ init_PerformanceEvents();+ init_FunctionWrappers();+ init_CacheHelpers();+ init_ClientAuthErrorCodes();+ init_ClientConfigurationErrorCodes();+ Authority = class _Authority {+ constructor(authority, networkInterface, cacheManager, authorityOptions, logger2, correlationId, performanceClient, managedIdentity) {+ this.canonicalAuthority = authority;+ this._canonicalAuthority.validateAsUri();+ this.networkInterface = networkInterface;+ this.cacheManager = cacheManager;+ this.authorityOptions = authorityOptions;+ this.regionDiscoveryMetadata = {+ region_used: void 0,+ region_source: void 0,+ region_outcome: void 0+ };+ this.logger = logger2;+ this.performanceClient = performanceClient;+ this.correlationId = correlationId;+ this.managedIdentity = managedIdentity || false;+ this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);+ }+ /**+ * Get {@link AuthorityType:type}+ * @param authorityUri {@link IUri}+ * @private+ */+ getAuthorityType(authorityUri) {+ if (authorityUri.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {+ return AuthorityType.Ciam;+ }+ const pathSegments = authorityUri.PathSegments;+ if (pathSegments.length) {+ switch (pathSegments[0].toLowerCase()) {+ case ADFS:+ return AuthorityType.Adfs;+ case DSTS:+ return AuthorityType.Dsts;+ }+ }+ return AuthorityType.Default;+ }+ // See above for AuthorityType+ get authorityType() {+ return this.getAuthorityType(this.canonicalAuthorityUrlComponents);+ }+ /**+ * ProtocolMode enum representing the way endpoints are constructed.+ */+ get protocolMode() {+ return this.authorityOptions.protocolMode;+ }+ /**+ * Returns authorityOptions which can be used to reinstantiate a new authority instance+ */+ get options() {+ return this.authorityOptions;+ }+ /**+ * A URL that is the authority set by the developer+ */+ get canonicalAuthority() {+ return this._canonicalAuthority.urlString;+ }+ /**+ * Sets canonical authority.+ */+ set canonicalAuthority(url) {+ this._canonicalAuthority = new UrlString(url, this.correlationId);+ this._canonicalAuthority.validateAsUri();+ this._canonicalAuthorityUrlComponents = null;+ }+ /**+ * Get authority components.+ */+ get canonicalAuthorityUrlComponents() {+ if (!this._canonicalAuthorityUrlComponents) {+ this._canonicalAuthorityUrlComponents = this._canonicalAuthority.getUrlComponents();+ }+ return this._canonicalAuthorityUrlComponents;+ }+ /**+ * Get hostname and port i.e. login.microsoftonline.com+ */+ get hostnameAndPort() {+ return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();+ }+ /**+ * Get tenant for authority.+ */+ get tenant() {+ return this.canonicalAuthorityUrlComponents.PathSegments[0];+ }+ /**+ * OAuth /authorize endpoint for requests+ */+ get authorizationEndpoint() {+ if (this.discoveryComplete()) {+ return this.replacePath(this.metadata.authorization_endpoint);+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * OAuth /token endpoint for requests+ */+ get tokenEndpoint() {+ if (this.discoveryComplete()) {+ return this.replacePath(this.metadata.token_endpoint);+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ get deviceCodeEndpoint() {+ if (this.discoveryComplete()) {+ return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * OAuth logout endpoint for requests+ */+ get endSessionEndpoint() {+ if (this.discoveryComplete()) {+ if (!this.metadata.end_session_endpoint) {+ throw createClientAuthError(endSessionEndpointNotSupported, this.correlationId);+ }+ return this.replacePath(this.metadata.end_session_endpoint);+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * OAuth issuer for requests+ */+ get selfSignedJwtAudience() {+ if (this.discoveryComplete()) {+ return this.replacePath(this.metadata.issuer);+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * Jwks_uri for token signing keys+ */+ get jwksUri() {+ if (this.discoveryComplete()) {+ return this.replacePath(this.metadata.jwks_uri);+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * Returns a flag indicating that tenant name can be replaced in authority {@link IUri}+ * @param authorityUri {@link IUri}+ * @private+ */+ canReplaceTenant(authorityUri) {+ return authorityUri.PathSegments.length === 1 && !_Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) && this.getAuthorityType(authorityUri) === AuthorityType.Default && this.protocolMode !== ProtocolMode.OIDC;+ }+ /**+ * Replaces tenant in url path with current tenant. Defaults to common.+ * @param urlString+ */+ replaceTenant(urlString) {+ return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);+ }+ /**+ * Replaces path such as tenant or policy with the current tenant or policy.+ * @param urlString+ */+ replacePath(urlString) {+ let endpoint = urlString;+ const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority, this.correlationId);+ const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();+ const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;+ const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;+ currentAuthorityParts.forEach((currentPart, index) => {+ let cachedPart = cachedAuthorityParts[index];+ if (index === 0 && this.canReplaceTenant(cachedAuthorityUrlComponents)) {+ const tenantId = new UrlString(this.metadata.authorization_endpoint, this.correlationId).getUrlComponents().PathSegments[0];+ if (cachedPart !== tenantId) {+ this.logger.verbose(`Replacing tenant domain name '${cachedPart}' with id '${tenantId}'`, this.correlationId);+ cachedPart = tenantId;+ }+ }+ if (currentPart !== cachedPart) {+ endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);+ }+ });+ return this.replaceTenant(endpoint);+ }+ /**+ * The default open id configuration endpoint for any canonical authority.+ */+ get defaultOpenIdConfigurationEndpoint() {+ const canonicalAuthorityHost = this.hostnameAndPort;+ if (this.canonicalAuthority.endsWith("v2.0/") || this.authorityType === AuthorityType.Adfs || this.protocolMode === ProtocolMode.OIDC && !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost)) {+ return `${this.canonicalAuthority}.well-known/openid-configuration`;+ }+ return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;+ }+ /**+ * Boolean that returns whether or not tenant discovery has been completed.+ */+ discoveryComplete() {+ return !!this.metadata;+ }+ /**+ * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network+ * and the /authorize, /token and logout endpoints.+ */+ async resolveEndpointsAsync() {+ const metadataEntity = this.getCurrentMetadataEntity();+ const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);+ this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);+ const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);+ this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {+ source: endpointSource+ });+ this.performanceClient?.addFields({+ cloudDiscoverySource,+ authorityEndpointSource: endpointSource+ }, this.correlationId);+ }+ /**+ * Returns metadata entity from cache if it exists, otherwise returns a new metadata entity built+ * from the configured canonical authority+ * @returns+ */+ getCurrentMetadataEntity() {+ let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort, this.correlationId);+ if (!metadataEntity) {+ metadataEntity = {+ aliases: [],+ preferred_cache: this.hostnameAndPort,+ preferred_network: this.hostnameAndPort,+ canonical_authority: this.canonicalAuthority,+ authorization_endpoint: "",+ token_endpoint: "",+ end_session_endpoint: "",+ issuer: "",+ aliasesFromNetwork: false,+ endpointsFromNetwork: false,+ expiresAt: generateAuthorityMetadataExpiresAt(),+ jwks_uri: ""+ };+ }+ return metadataEntity;+ }+ /**+ * Updates cached metadata based on metadata source and sets the instance's metadata+ * property to the same value+ * @param metadataEntity+ * @param cloudDiscoverySource+ * @param endpointMetadataResult+ */+ updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {+ if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) {+ metadataEntity.expiresAt = generateAuthorityMetadataExpiresAt();+ metadataEntity.canonical_authority = this.canonicalAuthority;+ }+ const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);+ this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);+ this.metadata = metadataEntity;+ }+ /**+ * Update AuthorityMetadataEntity with new endpoints and return where the information came from+ * @param metadataEntity+ */+ async updateEndpointMetadata(metadataEntity) {+ const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);+ if (localMetadata) {+ if (localMetadata.source === AuthorityMetadataSource.HARDCODED_VALUES) {+ if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {+ if (localMetadata.metadata) {+ const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata);+ updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);+ metadataEntity.canonical_authority = this.canonicalAuthority;+ }+ }+ }+ return localMetadata.source;+ }+ let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();+ if (metadata) {+ this.validateIssuer(metadata.issuer);+ if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {+ metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);+ }+ updateAuthorityEndpointMetadata(metadataEntity, metadata, true);+ return AuthorityMetadataSource.NETWORK;+ } else {+ throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint, this.correlationId);+ }+ }+ /**+ * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config+ * response if the source is hardcoded metadata+ * @param metadataEntity+ * @returns+ */+ updateEndpointMetadataFromLocalSources(metadataEntity) {+ this.logger.verbose("Attempting to get endpoint metadata from authority configuration", this.correlationId);+ const configMetadata = this.getEndpointMetadataFromConfig();+ if (configMetadata) {+ this.logger.verbose("Found endpoint metadata in authority configuration", this.correlationId);+ updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false);+ return {+ source: AuthorityMetadataSource.CONFIG+ };+ }+ this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.", this.correlationId);+ const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();+ if (hardcodedMetadata) {+ updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);+ return {+ source: AuthorityMetadataSource.HARDCODED_VALUES,+ metadata: hardcodedMetadata+ };+ } else {+ this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.", this.correlationId);+ }+ const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);+ if (this.isAuthoritySameType(metadataEntity) && metadataEntity.endpointsFromNetwork && !metadataEntityExpired) {+ this.logger.verbose("Found endpoint metadata in the cache.", "");+ return { source: AuthorityMetadataSource.CACHE };+ } else if (metadataEntityExpired) {+ this.logger.verbose("The metadata entity is expired.", "");+ }+ return null;+ }+ /**+ * Compares the number of url components after the domain to determine if the cached+ * authority metadata can be used for the requested authority. Protects against same domain different+ * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy+ * @param metadataEntity+ */+ isAuthoritySameType(metadataEntity) {+ const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority, this.correlationId);+ const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;+ return cachedParts.length === this.canonicalAuthorityUrlComponents.PathSegments.length;+ }+ /**+ * Parse authorityMetadata config option+ */+ getEndpointMetadataFromConfig() {+ if (this.authorityOptions.authorityMetadata) {+ try {+ return JSON.parse(this.authorityOptions.authorityMetadata);+ } catch (e) {+ throw createClientConfigurationError(invalidAuthorityMetadata, this.correlationId);+ }+ }+ return null;+ }+ /**+ * Gets OAuth endpoints from the given OpenID configuration endpoint.+ *+ * @param hasHardcodedMetadata boolean+ */+ async getEndpointMetadataFromNetwork() {+ const options = {};+ const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from '${openIdConfigurationEndpoint}'`, this.correlationId);+ try {+ const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);+ const isValidResponse = isOpenIdConfigResponse(response.body);+ if (isValidResponse) {+ return response.body;+ } else {+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`, this.correlationId);+ return null;+ }+ } catch (e) {+ this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: '${e}'`, this.correlationId);+ return null;+ }+ }+ /**+ * Get OAuth endpoints for common authorities.+ */+ getEndpointMetadataFromHardcodedValues() {+ if (this.hostnameAndPort in EndpointMetadata) {+ return EndpointMetadata[this.hostnameAndPort];+ }+ return null;+ }+ /**+ * Update the retrieved metadata with regional information.+ * User selected Azure region will be used if configured.+ */+ async updateMetadataWithRegionalInformation(metadata) {+ const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;+ if (userConfiguredAzureRegion) {+ if (userConfiguredAzureRegion !== AZURE_REGION_AUTO_DISCOVER_FLAG) {+ this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;+ this.regionDiscoveryMetadata.region_used = userConfiguredAzureRegion;+ return _Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion, this.correlationId);+ }+ const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration?.environmentRegion, this.regionDiscoveryMetadata);+ if (autodetectedRegionName) {+ this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;+ this.regionDiscoveryMetadata.region_used = autodetectedRegionName;+ return _Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName, this.correlationId);+ }+ this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;+ }+ return metadata;+ }+ /**+ * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache+ * and returns where the information was retrieved from+ * @param metadataEntity+ * @returns AuthorityMetadataSource+ */+ async updateCloudDiscoveryMetadata(metadataEntity) {+ const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);+ if (localMetadataSource) {+ return localMetadataSource;+ }+ const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();+ if (metadata) {+ updateCloudDiscoveryMetadata(metadataEntity, metadata, true);+ return AuthorityMetadataSource.NETWORK;+ }+ throw createClientConfigurationError(untrustedAuthority, this.correlationId);+ }+ updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {+ this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration", this.correlationId);+ this.logger.verbosePii(`Known Authorities: '${this.authorityOptions.knownAuthorities || NOT_APPLICABLE}'`, this.correlationId);+ this.logger.verbosePii(`Authority Metadata: '${this.authorityOptions.authorityMetadata || NOT_APPLICABLE}'`, this.correlationId);+ this.logger.verbosePii(`Canonical Authority: '${metadataEntity.canonical_authority || NOT_APPLICABLE}'`, this.correlationId);+ const metadata = this.getCloudDiscoveryMetadataFromConfig();+ if (metadata) {+ this.logger.verbose("Found cloud discovery metadata in authority configuration", this.correlationId);+ updateCloudDiscoveryMetadata(metadataEntity, metadata, false);+ return AuthorityMetadataSource.CONFIG;+ }+ this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.", this.correlationId);+ const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort);+ if (hardcodedMetadata) {+ this.logger.verbose("Found cloud discovery metadata from hardcoded values.", this.correlationId);+ updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false);+ return AuthorityMetadataSource.HARDCODED_VALUES;+ }+ this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.", this.correlationId);+ const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);+ if (this.isAuthoritySameType(metadataEntity) && metadataEntity.aliasesFromNetwork && !metadataEntityExpired) {+ this.logger.verbose("Found cloud discovery metadata in the cache.", "");+ return AuthorityMetadataSource.CACHE;+ } else if (metadataEntityExpired) {+ this.logger.verbose("The metadata entity is expired.", "");+ }+ return null;+ }+ /**+ * Parse cloudDiscoveryMetadata config or check knownAuthorities+ */+ getCloudDiscoveryMetadataFromConfig() {+ if (this.authorityType === AuthorityType.Ciam) {+ this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host.", this.correlationId);+ return _Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);+ }+ if (this.authorityOptions.cloudDiscoveryMetadata) {+ this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config.", this.correlationId);+ try {+ this.logger.verbose("Attempting to parse the cloud discovery metadata.", this.correlationId);+ const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);+ const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);+ this.logger.verbose("Parsed the cloud discovery metadata.", "");+ if (metadata) {+ this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata.", this.correlationId);+ return metadata;+ } else {+ this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata.", this.correlationId);+ }+ } catch (e) {+ this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.", this.correlationId);+ throw createClientConfigurationError(invalidCloudDiscoveryMetadata, this.correlationId);+ }+ }+ if (this.isInKnownAuthorities(this.hostnameAndPort)) {+ this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host.", this.correlationId);+ return _Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);+ }+ return null;+ }+ /**+ * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config+ *+ * @param hasHardcodedMetadata boolean+ */+ async getCloudDiscoveryMetadataFromNetwork() {+ const instanceDiscoveryEndpoint = `${AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;+ const options = {};+ let match = null;+ try {+ const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);+ let typedResponseBody;+ let metadata;+ if (isCloudInstanceDiscoveryResponse(response.body)) {+ typedResponseBody = response.body;+ metadata = typedResponseBody.metadata;+ this.logger.verbosePii(`tenant_discovery_endpoint is: '${typedResponseBody.tenant_discovery_endpoint}'`, this.correlationId);+ } else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {+ this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: '${response.status}'`, this.correlationId);+ typedResponseBody = response.body;+ if (typedResponseBody.error === INVALID_INSTANCE) {+ this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.", this.correlationId);+ return null;+ }+ this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is '${typedResponseBody.error}'`, this.correlationId);+ this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is '${typedResponseBody.error_description}'`, this.correlationId);+ this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network, correlationId) to []", this.correlationId);+ metadata = [];+ } else {+ this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse", this.correlationId);+ return null;+ }+ this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);+ match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);+ } catch (error2) {+ if (error2 instanceof AuthError) {+ this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.+Error: '${error2.errorCode}'+Error Description: '${error2.errorMessage}'`, this.correlationId);+ } else {+ const typedError = error2;+ this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.+Error: '${typedError.name}'+Error Description: '${typedError.message}'`, this.correlationId);+ }+ return null;+ }+ if (!match) {+ this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.", this.correlationId);+ this.logger.verbose("Creating custom Authority for custom domain scenario.", this.correlationId);+ match = _Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);+ }+ return match;+ }+ /**+ * Helper function to determine if a host is included in the knownAuthorities config option.+ */+ isInKnownAuthorities(host) {+ const normalizedHost = host.toLowerCase();+ const matches = this.authorityOptions.knownAuthorities.filter((authority) => {+ return authority && UrlString.getDomainFromUrl(authority, this.correlationId).toLowerCase() === normalizedHost;+ });+ return matches.length > 0;+ }+ /**+ * helper function to populate the authority based on azureCloudOptions+ * @param authorityString+ * @param azureCloudOptions+ */+ static generateAuthority(authorityString, azureCloudOptions) {+ let authorityAzureCloudInstance;+ if (azureCloudOptions && azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {+ const tenant = azureCloudOptions.tenant ? azureCloudOptions.tenant : DEFAULT_COMMON_TENANT;+ authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;+ }+ return authorityAzureCloudInstance ? authorityAzureCloudInstance : authorityString;+ }+ /**+ * Creates cloud discovery metadata object from a given host+ * @param host+ */+ static createCloudDiscoveryMetadataFromHost(host) {+ return {+ preferred_network: host,+ preferred_cache: host,+ aliases: [host]+ };+ }+ /**+ * helper function to generate environment from authority object+ */+ getPreferredCache() {+ if (this.managedIdentity) {+ return DEFAULT_AUTHORITY_HOST;+ } else if (this.discoveryComplete()) {+ return this.metadata.preferred_cache;+ } else {+ throw createClientAuthError(endpointResolutionError, this.correlationId);+ }+ }+ /**+ * Returns whether or not the provided host is an alias of this authority instance+ * @param host+ */+ isAlias(host) {+ return this.metadata.aliases.indexOf(host) > -1;+ }+ /**+ * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery+ * @param host+ */+ isAliasOfKnownMicrosoftAuthority(host) {+ return InstanceDiscoveryMetadataAliases.has(host);+ }+ /**+ * Validates the `issuer` returned by an OIDC discovery document against+ * this authority, per+ * https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation+ *+ * The issuer is accepted when ANY of the following holds:+ * 1. The issuer scheme + host + port match the authority's (path may+ * differ). Applies to all authorities.+ * 2. The authority is a Microsoft cloud authority (public, sovereign,+ * or CIAM), the issuer is HTTPS, and the issuer host is in the known+ * Microsoft authority host set.+ * 3. Same as (2), but the issuer host is a single-label regional variant+ * of a known Microsoft host (e.g. `westus.login.microsoftonline.com`).+ * 4. Same as (2), but the issuer host matches the CIAM tenant pattern+ * `{tenant}.ciamlogin.com` with an optional `/{tenant}[.onmicrosoft.com][/v2.0]`+ * path.+ * 5. The issuer host is HTTPS and is explicitly listed in the+ * developer-configured `knownAuthorities`. This covers scenarios where+ * the OIDC discovery document returns an issuer host that differs from+ * the authority (e.g., a GUID-based issuer for a name-based CIAM authority).+ *+ * @param issuer The `issuer` value returned in the OIDC discovery document.+ * @throws ClientConfigurationError("issuer_validation_failed") on failure.+ */+ validateIssuer(issuer) {+ if (!issuer) {+ throw createClientConfigurationError(issuerValidationFailed, this.correlationId);+ }+ let issuerUrl;+ try {+ issuerUrl = new URL(issuer);+ } catch {+ throw createClientConfigurationError(issuerValidationFailed, this.correlationId);+ }+ const issuerScheme = issuerUrl.protocol;+ const issuerHost = issuerUrl.host;+ const authorityScheme = (this.canonicalAuthorityUrlComponents.Protocol || "").toLowerCase();+ const authorityHost = (this.canonicalAuthorityUrlComponents.HostNameAndPort || "").toLowerCase();+ const matchesAuthorityOrigin = this.matchesAuthorityOrigin(issuerScheme, issuerHost, authorityScheme, authorityHost);+ const matchesKnownMicrosoftHost = issuerScheme === "https:" && this.isAliasOfKnownMicrosoftAuthority(issuerHost);+ const matchesRegionalMicrosoftHost = issuerScheme === "https:" && this.matchesRegionalMicrosoftHost(issuerHost);+ const matchesCiamTenantPattern = this.matchesCiamTenantPattern(issuerUrl, authorityHost, this.canonicalAuthorityUrlComponents.PathSegments);+ const matchesKnownAuthority = issuerScheme === "https:" && this.isInKnownAuthorities(issuerHost);+ if (matchesAuthorityOrigin || matchesKnownMicrosoftHost || matchesRegionalMicrosoftHost || matchesCiamTenantPattern || matchesKnownAuthority) {+ return;+ }+ throw createClientConfigurationError(issuerValidationFailed, this.correlationId);+ }+ /**+ * Rule 1: The issuer scheme + host (and port) match the authority's. Path+ * may differ. Applies to all authorities.+ */+ matchesAuthorityOrigin(issuerScheme, issuerHost, authorityScheme, authorityHost) {+ return issuerScheme === authorityScheme && issuerHost === authorityHost;+ }+ /**+ * Rule 3: The issuer host is a regional variant+ * (`{region}.{host}`) of a known Microsoft authority host.+ * E.g. `westus2.login.microsoft.com`.+ */+ matchesRegionalMicrosoftHost(issuerHost) {+ const firstDot = issuerHost.indexOf(".");+ if (firstDot > 0 && firstDot < issuerHost.length - 1) {+ const hostWithoutRegion = issuerHost.substring(firstDot + 1);+ return this.isAliasOfKnownMicrosoftAuthority(hostWithoutRegion);+ }+ return false;+ }+ /**+ * Rule 4: The issuer matches one of the well-known CIAM tenant patterns+ * (`https://{tenant}.ciamlogin.com[/{tenant}[.onmicrosoft.com][/v2.0]]`).+ *+ * The bare tenant name is extracted from the authority's first path segment+ * when available (stripping the `.onmicrosoft.com` suffix that+ * `transformCIAMAuthority` adds), or otherwise from the leftmost label of+ * the authority host (to support CIAM custom domain scenarios).+ *+ * Both `/{tenant}` and `/{tenant}.onmicrosoft.com` path forms are accepted+ * because the OIDC issuer may use either form depending on the authority URL+ * that was used to trigger discovery.+ */+ matchesCiamTenantPattern(issuerUrl, authorityHost, authorityPathSegments) {+ const pathSegment = authorityPathSegments[0];+ const tenantName = pathSegment ? pathSegment.endsWith(AAD_TENANT_DOMAIN_SUFFIX) ? pathSegment.slice(0, -AAD_TENANT_DOMAIN_SUFFIX.length) : pathSegment : authorityHost.split(".")[0];+ if (!tenantName) {+ return false;+ }+ const ciamBaseURL = `https://${tenantName}${CIAM_AUTH_URL}`;+ const validCiamPatterns = [+ ciamBaseURL,+ `${ciamBaseURL}/${tenantName}`,+ `${ciamBaseURL}/${tenantName}/v2.0`,+ `${ciamBaseURL}/${tenantName}${AAD_TENANT_DOMAIN_SUFFIX}`,+ `${ciamBaseURL}/${tenantName}${AAD_TENANT_DOMAIN_SUFFIX}/v2.0`+ // https://{tenant}.ciamlogin.com/{tenant}.onmicrosoft.com/v2.0+ ];+ const issuerPath = issuerUrl.pathname.replace(/\/+$/, "");+ const normalizedIssuer = `${issuerUrl.protocol}//${issuerUrl.host}${issuerPath}`;+ return validCiamPatterns.some((pattern) => pattern === normalizedIssuer);+ }+ /**+ * Checks whether the provided host is that of a public cloud authority+ *+ * @param authority string+ * @returns bool+ */+ static isPublicCloudAuthority(host) {+ return KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;+ }+ /**+ * Rebuild the authority string with the region+ *+ * @param host string+ * @param region string+ */+ static buildRegionalAuthorityString(host, region, correlationId, queryString) {+ const authorityUrlInstance = new UrlString(host, correlationId);+ authorityUrlInstance.validateAsUri();+ const authorityUrlParts = authorityUrlInstance.getUrlComponents();+ let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;+ if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {+ hostNameAndPort = `${region}.${REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;+ }+ const url = UrlString.constructAuthorityUriFromObject({+ ...authorityUrlInstance.getUrlComponents(),+ HostNameAndPort: hostNameAndPort+ }, correlationId).urlString;+ if (queryString)+ return `${url}?${queryString}`;+ return url;+ }+ /**+ * Replace the endpoints in the metadata object with their regional equivalents.+ *+ * @param metadata OpenIdConfigResponse+ * @param azureRegion string+ */+ static replaceWithRegionalInformation(metadata, azureRegion, correlationId) {+ const regionalMetadata = { ...metadata };+ regionalMetadata.authorization_endpoint = _Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion, correlationId);+ regionalMetadata.token_endpoint = _Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion, correlationId);+ if (regionalMetadata.end_session_endpoint) {+ regionalMetadata.end_session_endpoint = _Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion, correlationId);+ }+ return regionalMetadata;+ }+ /**+ * Transform CIAM_AUTHORIY as per the below rules:+ * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it+ *+ * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`+ * `ciamlogin.com` can also change in the future and we should accommodate the same+ *+ * @param authority+ */+ static transformCIAMAuthority(authority, correlationId) {+ let ciamAuthority = authority;+ const authorityUrl = new UrlString(authority, correlationId);+ const authorityUrlComponents = authorityUrl.getUrlComponents();+ if (authorityUrlComponents.PathSegments.length === 0 && authorityUrlComponents.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {+ const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];+ ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${AAD_TENANT_DOMAIN_SUFFIX}`;+ }+ return ciamAuthority;+ }+ };+ Authority.reservedTenantDomains = /* @__PURE__ */ new Set([+ "{tenant}",+ "{tenantid}",+ AADAuthority.COMMON,+ AADAuthority.CONSUMERS,+ AADAuthority.ORGANIZATIONS+ ]);+ }+});++// node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs+var AuthorityFactory_exports = {};+__export(AuthorityFactory_exports, {+ createDiscoveredInstance: () => createDiscoveredInstance+});+async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger2, correlationId, performanceClient) {+ const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri), correlationId);+ const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger2, correlationId, performanceClient);+ try {+ await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), AuthorityResolveEndpointsAsync, logger2, performanceClient, correlationId)();+ return acquireTokenAuthority;+ } catch (e) {+ throw createClientAuthError(endpointResolutionError, correlationId);+ }+}+var init_AuthorityFactory = __esm({+ "node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs"() {+ "use strict";+ init_Authority();+ init_ClientAuthError();+ init_PerformanceEvents();+ init_FunctionWrappers();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs+var AuthorizationCodeClient;+var init_AuthorizationCodeClient = __esm({+ "node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs"() {+ "use strict";+ init_RequestParameterBuilder();+ init_UrlUtils();+ init_Constants();+ init_AADServerParamKeys();+ init_ClientConfiguration();+ init_ResponseHandler();+ init_ClientAuthError();+ init_UrlString();+ init_PopTokenGenerator();+ init_TimeUtils();+ init_ClientInfo();+ init_CcsCredential();+ init_ClientConfigurationError();+ init_PerformanceEvents();+ init_FunctionWrappers();+ init_ClientAssertionUtils();+ init_RequestThumbprint();+ init_Token();+ init_AuthorityFactory();+ init_Logger();+ init_packageMetadata();+ init_ClientAuthErrorCodes();+ init_ClientConfigurationErrorCodes();+ AuthorizationCodeClient = class {+ constructor(configuration, performanceClient) {+ this.includeRedirectUri = true;+ this.config = buildClientConfiguration(configuration);+ this.logger = new Logger(this.config.loggerOptions, name, version2);+ this.cryptoUtils = this.config.cryptoInterface;+ this.cacheManager = this.config.storageInterface;+ this.networkClient = this.config.networkInterface;+ this.serverTelemetryManager = this.config.serverTelemetryManager;+ this.authority = this.config.authOptions.authority;+ this.performanceClient = performanceClient;+ this.oidcDefaultScopes = this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;+ }+ /**+ * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the+ * authorization_code_grant+ * @param request+ */+ async acquireToken(request, apiId, authCodePayload) {+ if (!request.code) {+ throw createClientAuthError(requestCannotBeMade, request.correlationId);+ }+ if (authCodePayload && authCodePayload.cloud_instance_host_name) {+ await invokeAsync(this.updateTokenEndpointAuthority.bind(this), UpdateTokenEndpointAuthority, this.logger, this.performanceClient, request.correlationId)(authCodePayload.cloud_instance_host_name, request.correlationId);+ }+ const reqTimestamp = nowSeconds();+ const response = await invokeAsync(this.executeTokenRequest.bind(this), AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request, this.serverTelemetryManager);+ const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];+ const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);+ responseHandler.validateTokenResponse(response.body, request.correlationId);+ return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, authCodePayload, void 0, void 0, void 0, requestId);+ }+ /**+ * Used to log out the current user, and redirect the user to the postLogoutRedirectUri.+ * Default behaviour is to redirect the user to `window.location.href`.+ * @param authorityUri+ */+ getLogoutUri(logoutRequest) {+ if (!logoutRequest) {+ throw createClientConfigurationError(logoutRequestEmpty, "");+ }+ const queryString = this.createLogoutUrlQueryString(logoutRequest);+ return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);+ }+ /**+ * Executes POST request to token endpoint+ * @param authority+ * @param request+ */+ async executeTokenRequest(authority, request, serverTelemetryManager) {+ const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);+ const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);+ const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);+ let ccsCredential = void 0;+ if (request.clientInfo) {+ try {+ const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);+ ccsCredential = {+ credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,+ type: CcsCredentialType.HOME_ACCOUNT_ID+ };+ } catch (e) {+ this.logger.verbose(`Could not parse client info for CCS Header: '${e}'`, request.correlationId);+ }+ }+ const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request.ccsCredential);+ const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);+ return invokeAsync(executePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, serverTelemetryManager);+ }+ /**+ * Generates a map for all the params to be sent to the service+ * @param request+ */+ async createTokenRequestBody(request) {+ const parameters = /* @__PURE__ */ new Map();+ addClientId(parameters, request.embeddedClientId || request.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);+ if (!this.includeRedirectUri) {+ if (!request.redirectUri) {+ throw createClientConfigurationError(redirectUriEmpty, request.correlationId);+ }+ } else {+ addRedirectUri(parameters, request.redirectUri);+ }+ addScopes(parameters, request.scopes, request.correlationId, true, this.oidcDefaultScopes);+ addResource(parameters, request.resource);+ addAuthorizationCode(parameters, request.code);+ addLibraryInfo(parameters, this.config.libraryInfo);+ addApplicationTelemetry(parameters, this.config.telemetry.application);+ addThrottling(parameters);+ if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {+ addServerTelemetry(parameters, this.serverTelemetryManager);+ }+ if (request.codeVerifier) {+ addCodeVerifier(parameters, request.codeVerifier);+ }+ if (this.config.clientCredentials.clientSecret) {+ addClientSecret(parameters, this.config.clientCredentials.clientSecret);+ }+ if (this.config.clientCredentials.clientAssertion) {+ const clientAssertion = this.config.clientCredentials.clientAssertion;+ addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));+ addClientAssertionType(parameters, clientAssertion.assertionType);+ }+ addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT);+ addClientInfo(parameters);+ if (request.authenticationScheme === AuthenticationScheme.POP) {+ const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);+ let reqCnfData;+ if (!request.popKid) {+ const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);+ reqCnfData = generatedReqCnfData.reqCnfString;+ } else {+ reqCnfData = this.cryptoUtils.encodeKid(request.popKid);+ }+ addPopToken(parameters, reqCnfData);+ } else if (request.authenticationScheme === AuthenticationScheme.SSH) {+ if (request.sshJwk) {+ addSshJwk(parameters, request.sshJwk);+ } else {+ throw createClientConfigurationError(missingSshJwk, request.correlationId);+ }+ }+ let ccsCred = void 0;+ if (request.clientInfo) {+ try {+ const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);+ ccsCred = {+ credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,+ type: CcsCredentialType.HOME_ACCOUNT_ID+ };+ } catch (e) {+ this.logger.verbose(`Could not parse client info for CCS Header: '${e}'`, request.correlationId);+ }+ } else {+ ccsCred = request.ccsCredential;+ }+ if (this.config.systemOptions.preventCorsPreflight && ccsCred) {+ switch (ccsCred.type) {+ case CcsCredentialType.HOME_ACCOUNT_ID:+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);+ addCcsOid(parameters, clientInfo);+ } catch (e) {+ this.logger.verbose(`Could not parse home account ID for CCS Header: '${e}'`, request.correlationId);+ }+ break;+ case CcsCredentialType.UPN:+ addCcsUpn(parameters, ccsCred.credential);+ break;+ }+ }+ if (request.embeddedClientId) {+ addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);+ }+ if (request.extraParameters) {+ addExtraParameters(parameters, request.extraParameters);+ }+ if (request.enableSpaAuthorizationCode && (!request.extraParameters || !request.extraParameters[RETURN_SPA_CODE])) {+ addExtraParameters(parameters, {+ [RETURN_SPA_CODE]: "1"+ });+ }+ instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);+ addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);+ return mapToQueryString(parameters);+ }+ /**+ * This API validates the `EndSessionRequest` and creates a URL+ * @param request+ */+ createLogoutUrlQueryString(request) {+ const parameters = /* @__PURE__ */ new Map();+ if (request.postLogoutRedirectUri) {+ addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri);+ }+ if (request.correlationId) {+ addCorrelationId(parameters, request.correlationId);+ }+ if (request.idTokenHint) {+ addIdTokenHint(parameters, request.idTokenHint);+ }+ if (request.state) {+ addState(parameters, request.state);+ }+ if (request.logoutHint) {+ addLogoutHint(parameters, request.logoutHint);+ }+ if (request.extraQueryParameters) {+ addExtraParameters(parameters, request.extraQueryParameters);+ }+ if (this.config.authOptions.instanceAware) {+ addInstanceAware(parameters);+ }+ return mapToQueryString(parameters);+ }+ /**+ * Updates the authority to the cloud instance provided in the authorization response+ * @param cloudInstanceHostName - cloud instance host name from authorization code payload+ * @param correlationId - request correlation id+ */+ async updateTokenEndpointAuthority(cloudInstanceHostName, correlationId) {+ const cloudInstanceAuthorityUri = `https://${cloudInstanceHostName}/${this.authority.tenant}/`;+ const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);+ this.authority = cloudInstanceAuthority;+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs+var DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS, RefreshTokenClient;+var init_RefreshTokenClient = __esm({+ "node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs"() {+ "use strict";+ init_ClientConfiguration();+ init_RequestParameterBuilder();+ init_UrlUtils();+ init_Constants();+ init_AADServerParamKeys();+ init_ResponseHandler();+ init_PopTokenGenerator();+ init_ClientConfigurationError();+ init_ClientAuthError();+ init_ServerError();+ init_TimeUtils();+ init_UrlString();+ init_CcsCredential();+ init_ClientInfo();+ init_InteractionRequiredAuthError();+ init_PerformanceEvents();+ init_FunctionWrappers();+ init_ClientAssertionUtils();+ init_RequestThumbprint();+ init_Token();+ init_Logger();+ init_packageMetadata();+ init_InteractionRequiredAuthErrorCodes();+ init_ClientConfigurationErrorCodes();+ init_ClientAuthErrorCodes();+ DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300;+ RefreshTokenClient = class {+ constructor(configuration, performanceClient) {+ this.config = buildClientConfiguration(configuration);+ this.logger = new Logger(this.config.loggerOptions, name, version2);+ this.cryptoUtils = this.config.cryptoInterface;+ this.cacheManager = this.config.storageInterface;+ this.networkClient = this.config.networkInterface;+ this.serverTelemetryManager = this.config.serverTelemetryManager;+ this.authority = this.config.authOptions.authority;+ this.performanceClient = performanceClient;+ }+ async acquireToken(request, apiId) {+ const reqTimestamp = nowSeconds();+ const response = await invokeAsync(this.executeTokenRequest.bind(this), RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);+ const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];+ const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);+ responseHandler.validateTokenResponse(response.body, request.correlationId);+ return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, void 0, void 0, true, request.forceCache, requestId);+ }+ /**+ * Gets cached refresh token and attaches to request, then calls acquireToken API+ * @param request+ */+ async acquireTokenByRefreshToken(request, apiId) {+ if (!request) {+ throw createClientConfigurationError(tokenRequestEmpty, "");+ }+ if (!request.account) {+ throw createClientAuthError(noAccountInSilentRequest, request.correlationId);+ }+ const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, request.correlationId);+ if (isFOCI) {+ try {+ return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true, apiId);+ } catch (e) {+ const noFamilyRTInCache = e instanceof InteractionRequiredAuthError && e.errorCode === noTokensFound;+ const clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === INVALID_GRANT_ERROR && e.subError === CLIENT_MISMATCH_ERROR;+ if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {+ return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);+ } else {+ throw e;+ }+ }+ }+ return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);+ }+ /**+ * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached+ * @param request+ */+ async acquireTokenWithCachedRefreshToken(request, foci, apiId) {+ const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, void 0);+ if (!refreshToken) {+ throw createInteractionRequiredAuthError(noTokensFound, request.correlationId);+ }+ if (refreshToken.expiresOn) {+ const offset = request.refreshTokenExpirationOffsetSeconds || DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS;+ this.performanceClient?.addFields({+ cacheRtExpiresOnSeconds: Number(refreshToken.expiresOn),+ rtOffsetSeconds: offset+ }, request.correlationId);+ if (isTokenExpired(refreshToken.expiresOn, offset)) {+ throw createInteractionRequiredAuthError(refreshTokenExpired, request.correlationId);+ }+ }+ const refreshTokenRequest = {+ ...request,+ refreshToken: refreshToken.secret,+ authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER,+ ccsCredential: {+ credential: request.account.homeAccountId,+ type: CcsCredentialType.HOME_ACCOUNT_ID+ }+ };+ try {+ return await invokeAsync(this.acquireToken.bind(this), RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest, apiId);+ } catch (e) {+ if (e instanceof InteractionRequiredAuthError) {+ if (e.subError === badToken) {+ this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache", request.correlationId);+ const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken);+ this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId);+ }+ }+ throw e;+ }+ }+ /**+ * Constructs the network message and makes a NW call to the underlying secure token service+ * @param request+ * @param authority+ */+ async executeTokenRequest(request, authority) {+ const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);+ const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);+ const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);+ const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, request.ccsCredential);+ const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);+ return invokeAsync(executePostToTokenEndpoint, RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);+ }+ /**+ * Helper function to create the token request body+ * @param request+ */+ async createTokenRequestBody(request) {+ const parameters = /* @__PURE__ */ new Map();+ addClientId(parameters, request.embeddedClientId || request.extraParameters?.[CLIENT_ID] || this.config.authOptions.clientId);+ if (request.redirectUri) {+ addRedirectUri(parameters, request.redirectUri);+ }+ addScopes(parameters, request.scopes, request.correlationId, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);+ addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT);+ addClientInfo(parameters);+ addLibraryInfo(parameters, this.config.libraryInfo);+ addApplicationTelemetry(parameters, this.config.telemetry.application);+ addThrottling(parameters);+ if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {+ addServerTelemetry(parameters, this.serverTelemetryManager);+ }+ addRefreshToken(parameters, request.refreshToken);+ if (this.config.clientCredentials.clientSecret) {+ addClientSecret(parameters, this.config.clientCredentials.clientSecret);+ }+ if (this.config.clientCredentials.clientAssertion) {+ const clientAssertion = this.config.clientCredentials.clientAssertion;+ addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));+ addClientAssertionType(parameters, clientAssertion.assertionType);+ }+ if (request.authenticationScheme === AuthenticationScheme.POP) {+ const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);+ let reqCnfData;+ if (!request.popKid) {+ const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);+ reqCnfData = generatedReqCnfData.reqCnfString;+ } else {+ reqCnfData = this.cryptoUtils.encodeKid(request.popKid);+ }+ addPopToken(parameters, reqCnfData);+ } else if (request.authenticationScheme === AuthenticationScheme.SSH) {+ if (request.sshJwk) {+ addSshJwk(parameters, request.sshJwk);+ } else {+ throw createClientConfigurationError(missingSshJwk, request.correlationId);+ }+ }+ if (this.config.systemOptions.preventCorsPreflight && request.ccsCredential) {+ switch (request.ccsCredential.type) {+ case CcsCredentialType.HOME_ACCOUNT_ID:+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);+ addCcsOid(parameters, clientInfo);+ } catch (e) {+ this.logger.verbose(`Could not parse home account ID for CCS Header: '${e}'`, request.correlationId);+ }+ break;+ case CcsCredentialType.UPN:+ addCcsUpn(parameters, request.ccsCredential.credential);+ break;+ }+ }+ if (request.embeddedClientId) {+ addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);+ }+ if (request.extraParameters) {+ addExtraParameters(parameters, {+ ...request.extraParameters+ });+ }+ instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);+ addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);+ return mapToQueryString(parameters);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs+var SilentFlowClient;+var init_SilentFlowClient = __esm({+ "node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs"() {+ "use strict";+ init_ClientConfiguration();+ init_TimeUtils();+ init_ClientAuthError();+ init_ResponseHandler();+ init_Constants();+ init_StringUtils();+ init_AuthToken();+ init_PerformanceEvents();+ init_FunctionWrappers();+ init_Authority();+ init_Logger();+ init_packageMetadata();+ init_ClientAuthErrorCodes();+ SilentFlowClient = class {+ constructor(configuration, performanceClient) {+ this.config = buildClientConfiguration(configuration);+ this.logger = new Logger(this.config.loggerOptions, name, version2);+ this.cryptoUtils = this.config.cryptoInterface;+ this.cacheManager = this.config.storageInterface;+ this.networkClient = this.config.networkInterface;+ this.serverTelemetryManager = this.config.serverTelemetryManager;+ this.authority = this.config.authOptions.authority;+ this.performanceClient = performanceClient;+ }+ /**+ * Retrieves token from cache or throws an error if it must be refreshed.+ * @param request+ */+ async acquireCachedToken(request) {+ let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;+ if (request.forceRefresh || !StringUtils.isEmptyObj(request.claims)) {+ this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId);+ throw createClientAuthError(tokenRefreshRequired, request.correlationId);+ }+ if (!request.account) {+ throw createClientAuthError(noAccountInSilentRequest, request.correlationId);+ }+ const requestTenantId = request.account.tenantId || getTenantFromAuthorityString(request.authority, request.correlationId);+ const tokenKeys = this.cacheManager.getTokenKeys();+ const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId);+ if (!cachedAccessToken) {+ this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);+ throw createClientAuthError(tokenRefreshRequired, request.correlationId);+ } else if (wasClockTurnedBack(cachedAccessToken.cachedAt) || isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {+ this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId);+ throw createClientAuthError(tokenRefreshRequired, request.correlationId);+ } else if (request.resource) {+ if (cachedAccessToken.resource !== request.resource) {+ this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);+ throw createClientAuthError(tokenRefreshRequired, request.correlationId);+ }+ } else if (cachedAccessToken.refreshOn && isTokenExpired(cachedAccessToken.refreshOn, 0)) {+ lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;+ }+ const environment = request.authority || this.authority.getPreferredCache();+ const cacheRecord = {+ account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId),+ accessToken: cachedAccessToken,+ idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId),+ refreshToken: null,+ appMetadata: this.cacheManager.readAppMetadataFromCache(environment, request.correlationId)+ };+ this.setCacheOutcome(lastCacheOutcome, request.correlationId);+ if (this.config.serverTelemetryManager) {+ this.config.serverTelemetryManager.incrementCacheHits();+ }+ return [+ await invokeAsync(this.generateResultFromCacheRecord.bind(this), SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request),+ lastCacheOutcome+ ];+ }+ setCacheOutcome(cacheOutcome, correlationId) {+ this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);+ this.performanceClient?.addFields({+ cacheOutcome+ }, correlationId);+ if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {+ this.logger.info(`Token refresh is required due to cache outcome: '${cacheOutcome}'`, correlationId);+ }+ }+ /**+ * Helper function to build response object from the CacheRecord+ * @param cacheRecord+ */+ async generateResultFromCacheRecord(cacheRecord, request) {+ let idTokenClaims;+ if (cacheRecord.idToken) {+ idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode, request.correlationId);+ }+ return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, this.performanceClient, idTokenClaims);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/protocol/Authorize.mjs+var Authorize_exports = {};+__export(Authorize_exports, {+ getAuthorizationCodePayload: () => getAuthorizationCodePayload,+ getAuthorizeUrl: () => getAuthorizeUrl,+ getStandardAuthorizeRequestParameters: () => getStandardAuthorizeRequestParameters,+ validateAuthorizationResponse: () => validateAuthorizationResponse+});+function getStandardAuthorizeRequestParameters(authOptions, request, logger2, performanceClient) {+ const correlationId = request.correlationId;+ const parameters = /* @__PURE__ */ new Map();+ addClientId(parameters, request.embeddedClientId || request.extraQueryParameters?.[CLIENT_ID] || authOptions.clientId);+ const requestScopes = [+ ...request.scopes || [],+ ...request.extraScopesToConsent || []+ ];+ addScopes(parameters, requestScopes, request.correlationId, true, authOptions.authority.options.OIDCOptions?.defaultScopes);+ addResource(parameters, request.resource);+ addRedirectUri(parameters, request.redirectUri);+ addCorrelationId(parameters, correlationId);+ addResponseMode(parameters, request.responseMode);+ addClientInfo(parameters);+ addCliData(parameters);+ if (request.prompt) {+ addPrompt(parameters, request.prompt);+ performanceClient?.addFields({ prompt: request.prompt }, correlationId);+ }+ if (request.domainHint) {+ addDomainHint(parameters, request.domainHint);+ performanceClient?.addFields({ domainHintFromRequest: true }, correlationId);+ }+ if (request.prompt !== PromptValue.SELECT_ACCOUNT) {+ if (request.sid && request.prompt === PromptValue.NONE) {+ logger2.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request", request.correlationId);+ addSid(parameters, request.sid);+ performanceClient?.addFields({ sidFromRequest: true }, correlationId);+ } else if (request.account) {+ const accountSid = extractAccountSid(request.account);+ let accountLoginHintClaim = extractLoginHint(request.account);+ if (accountLoginHintClaim && request.domainHint) {+ logger2.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`, request.correlationId);+ accountLoginHintClaim = null;+ }+ if (accountLoginHintClaim) {+ logger2.verbose("createAuthCodeUrlQueryString: login_hint claim present on account", request.correlationId);+ addLoginHint(parameters, accountLoginHintClaim);+ performanceClient?.addFields({ loginHintFromClaim: true }, correlationId);+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);+ addCcsOid(parameters, clientInfo);+ } catch (e) {+ logger2.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);+ }+ } else if (accountSid && request.prompt === PromptValue.NONE) {+ logger2.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account", request.correlationId);+ addSid(parameters, accountSid);+ performanceClient?.addFields({ sidFromClaim: true }, correlationId);+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);+ addCcsOid(parameters, clientInfo);+ } catch (e) {+ logger2.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);+ }+ } else if (request.loginHint) {+ logger2.verbose("createAuthCodeUrlQueryString: Adding login_hint from request", request.correlationId);+ addLoginHint(parameters, request.loginHint);+ addCcsUpn(parameters, request.loginHint);+ performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);+ } else if (request.account.username) {+ logger2.verbose("createAuthCodeUrlQueryString: Adding login_hint from account", request.correlationId);+ addLoginHint(parameters, request.account.username);+ performanceClient?.addFields({ loginHintFromUpn: true }, correlationId);+ try {+ const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);+ addCcsOid(parameters, clientInfo);+ } catch (e) {+ logger2.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header", request.correlationId);+ }+ }+ } else if (request.loginHint) {+ logger2.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request", request.correlationId);+ addLoginHint(parameters, request.loginHint);+ addCcsUpn(parameters, request.loginHint);+ performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);+ }+ } else {+ logger2.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints", request.correlationId);+ }+ if (request.nonce) {+ addNonce(parameters, request.nonce);+ }+ if (request.state) {+ addState(parameters, request.state);+ }+ if (request.embeddedClientId) {+ addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri);+ }+ addClaims(parameters, request.correlationId, request.claims, authOptions.clientCapabilities, request.skipBrokerClaims);+ if (authOptions.instanceAware && (!request.extraQueryParameters || !Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) {+ addInstanceAware(parameters);+ }+ return parameters;+}+function getAuthorizeUrl(authority, requestParameters) {+ const queryString = mapToQueryString(requestParameters);+ return UrlString.appendQueryString(authority.authorizationEndpoint, queryString);+}+function getAuthorizationCodePayload(serverParams, cachedState, correlationId) {+ validateAuthorizationResponse(serverParams, cachedState, correlationId);+ if (!serverParams.code) {+ throw createClientAuthError(authorizationCodeMissingFromServerResponse, correlationId);+ }+ return serverParams;+}+function validateAuthorizationResponse(serverResponse, requestState, correlationId) {+ if (!serverResponse.state || !requestState) {+ throw serverResponse.state ? createClientAuthError(stateNotFound, correlationId, "Cached State") : createClientAuthError(stateNotFound, correlationId, "Server State");+ }+ let decodedServerResponseState;+ let decodedRequestState;+ try {+ decodedServerResponseState = decodeURIComponent(serverResponse.state);+ } catch (e) {+ throw createClientAuthError(invalidState, correlationId, serverResponse.state);+ }+ try {+ decodedRequestState = decodeURIComponent(requestState);+ } catch (e) {+ throw createClientAuthError(invalidState, correlationId, serverResponse.state);+ }+ if (decodedServerResponseState !== decodedRequestState) {+ throw createClientAuthError(stateMismatch, correlationId);+ }+ if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {+ const serverErrorNo = parseServerErrorNo(serverResponse);+ if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {+ throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.correlation_id || correlationId, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.claims || "", serverErrorNo);+ }+ throw new ServerError(serverResponse.error || "", serverResponse.correlation_id || correlationId, serverResponse.error_description, serverResponse.suberror, serverErrorNo);+ }+}+function parseServerErrorNo(serverResponse) {+ const errorCodePrefix = "code=";+ const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix);+ return errorCodePrefixIndex && errorCodePrefixIndex >= 0 ? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length) : void 0;+}+function extractAccountSid(account) {+ return account.idTokenClaims?.sid || null;+}+function extractLoginHint(account) {+ return account.loginHint || account.idTokenClaims?.login_hint || null;+}+var init_Authorize = __esm({+ "node_modules/@azure/msal-common/dist/protocol/Authorize.mjs"() {+ "use strict";+ init_RequestParameterBuilder();+ init_AADServerParamKeys();+ init_Constants();+ init_ClientInfo();+ init_UrlUtils();+ init_UrlString();+ init_ClientAuthError();+ init_InteractionRequiredAuthError();+ init_ServerError();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/request/BaseAuthRequest.mjs+function enforceResourceParameter(isMcp, request) {+ if (!isMcp) {+ return;+ }+ if (request.resource && (containsResourceParam(request.extraParameters) || containsResourceParam(request.extraQueryParameters))) {+ throw createClientAuthError(misplacedResourceParam, request.correlationId || "");+ }+ if (!request.resource) {+ throw createClientAuthError(resourceParameterRequired, request.correlationId || "");+ }+}+function containsResourceParam(params) {+ if (!params) {+ return false;+ }+ return Object.prototype.hasOwnProperty.call(params, "resource");+}+var init_BaseAuthRequest = __esm({+ "node_modules/@azure/msal-common/dist/request/BaseAuthRequest.mjs"() {+ "use strict";+ init_ClientAuthError();+ init_ClientAuthErrorCodes();+ }+});++// node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs+var AuthErrorCodes_exports = {};+__export(AuthErrorCodes_exports, {+ postRequestFailed: () => postRequestFailed,+ unexpectedError: () => unexpectedError+});+var unexpectedError, postRequestFailed;+var init_AuthErrorCodes = __esm({+ "node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs"() {+ "use strict";+ unexpectedError = "unexpected_error";+ postRequestFailed = "post_request_failed";+ }+});++// node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs+function makeExtraSkuString(params) {+ const { skus, libraryName, libraryVersion, extensionName, extensionVersion } = params;+ const skuMap = /* @__PURE__ */ new Map([+ [0, [libraryName, libraryVersion]],+ [2, [extensionName, extensionVersion]]+ ]);+ let skuArr = [];+ if (skus?.length) {+ skuArr = skus.split(skuGroupSeparator);+ if (skuArr.length < 4) {+ return skus;+ }+ } else {+ skuArr = Array.from({ length: 4 }, () => skuValueSeparator);+ }+ skuMap.forEach((value, key) => {+ if (value.length === 2 && value[0]?.length && value[1]?.length) {+ setSku({+ skuArr,+ index: key,+ skuName: value[0],+ skuVersion: value[1]+ });+ }+ });+ return skuArr.join(skuGroupSeparator);+}+function setSku(params) {+ const { skuArr, index, skuName, skuVersion } = params;+ if (index >= skuArr.length) {+ return;+ }+ skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);+}+var skuGroupSeparator, skuValueSeparator, ServerTelemetryManager;+var init_ServerTelemetryManager = __esm({+ "node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs"() {+ "use strict";+ init_Constants();+ init_AuthError();+ skuGroupSeparator = ",";+ skuValueSeparator = "|";+ ServerTelemetryManager = class _ServerTelemetryManager {+ constructor(telemetryRequest, cacheManager) {+ this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;+ this.cacheManager = cacheManager;+ this.apiId = telemetryRequest.apiId;+ this.correlationId = telemetryRequest.correlationId;+ this.wrapperSKU = telemetryRequest.wrapperSKU || "";+ this.wrapperVer = telemetryRequest.wrapperVer || "";+ this.telemetryCacheKey = SERVER_TELEM_CACHE_KEY + CACHE_KEY_SEPARATOR + telemetryRequest.clientId;+ }+ /**+ * API to add MSER Telemetry to request+ */+ generateCurrentRequestHeaderValue() {+ const request = `${this.apiId}${SERVER_TELEM_VALUE_SEPARATOR}${this.cacheOutcome}`;+ const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];+ const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();+ if (nativeBrokerErrorCode?.length) {+ platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);+ }+ const platformFields = platformFieldsArr.join(SERVER_TELEM_VALUE_SEPARATOR);+ const regionDiscoveryFields = this.getRegionDiscoveryFields();+ const requestWithRegionDiscoveryFields = [+ request,+ regionDiscoveryFields+ ].join(SERVER_TELEM_VALUE_SEPARATOR);+ return [+ SERVER_TELEM_SCHEMA_VERSION,+ requestWithRegionDiscoveryFields,+ platformFields+ ].join(SERVER_TELEM_CATEGORY_SEPARATOR);+ }+ /**+ * API to add MSER Telemetry for the last failed request+ */+ generateLastRequestHeaderValue() {+ const lastRequests = this.getLastRequests();+ const maxErrors = _ServerTelemetryManager.maxErrorsToSend(lastRequests);+ const failedRequests = lastRequests.failedRequests.slice(0, 2 * maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);+ const errors = lastRequests.errors.slice(0, maxErrors).join(SERVER_TELEM_VALUE_SEPARATOR);+ const errorCount = lastRequests.errors.length;+ const overflow = maxErrors < errorCount ? SERVER_TELEM_OVERFLOW_TRUE : SERVER_TELEM_OVERFLOW_FALSE;+ const platformFields = [errorCount, overflow].join(SERVER_TELEM_VALUE_SEPARATOR);+ return [+ SERVER_TELEM_SCHEMA_VERSION,+ lastRequests.cacheHits,+ failedRequests,+ errors,+ platformFields+ ].join(SERVER_TELEM_CATEGORY_SEPARATOR);+ }+ /**+ * API to cache token failures for MSER data capture+ * @param error+ */+ cacheFailedRequest(error2) {+ try {+ const lastRequests = this.getLastRequests();+ if (lastRequests.errors.length >= SERVER_TELEM_MAX_CACHED_ERRORS) {+ lastRequests.failedRequests.shift();+ lastRequests.failedRequests.shift();+ lastRequests.errors.shift();+ }+ lastRequests.failedRequests.push(this.apiId, this.correlationId);+ if (error2 instanceof Error && !!error2 && error2.toString()) {+ if (error2 instanceof AuthError) {+ if (error2.subError) {+ lastRequests.errors.push(error2.subError);+ } else if (error2.errorCode) {+ lastRequests.errors.push(error2.errorCode);+ } else {+ lastRequests.errors.push(error2.toString());+ }+ } else {+ lastRequests.errors.push(error2.toString());+ }+ } else {+ lastRequests.errors.push(SERVER_TELEM_UNKNOWN_ERROR);+ }+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);+ } catch {+ }+ return;+ }+ /**+ * Update server telemetry cache entry by incrementing cache hit counter+ */+ incrementCacheHits() {+ const lastRequests = this.getLastRequests();+ lastRequests.cacheHits += 1;+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);+ return lastRequests.cacheHits;+ }+ /**+ * Get the server telemetry entity from cache or initialize a new one+ */+ getLastRequests() {+ const initialValue = {+ failedRequests: [],+ errors: [],+ cacheHits: 0+ };+ const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey, this.correlationId);+ return lastRequests || initialValue;+ }+ /**+ * Remove server telemetry cache entry+ */+ clearTelemetryCache() {+ const lastRequests = this.getLastRequests();+ const numErrorsFlushed = _ServerTelemetryManager.maxErrorsToSend(lastRequests);+ const errorCount = lastRequests.errors.length;+ if (numErrorsFlushed === errorCount) {+ this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);+ } else {+ const serverTelemEntity = {+ failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),+ errors: lastRequests.errors.slice(numErrorsFlushed),+ cacheHits: 0+ };+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);+ }+ }+ /**+ * Returns the maximum number of errors that can be flushed to the server in the next network request+ * @param serverTelemetryEntity+ */+ static maxErrorsToSend(serverTelemetryEntity) {+ let i;+ let maxErrors = 0;+ let dataSize = 0;+ const errorCount = serverTelemetryEntity.errors.length;+ for (i = 0; i < errorCount; i++) {+ const apiId = serverTelemetryEntity.failedRequests[2 * i] || "";+ const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || "";+ const errorCode = serverTelemetryEntity.errors[i] || "";+ dataSize += apiId.toString().length + correlationId.toString().length + errorCode.length + 3;+ if (dataSize < SERVER_TELEM_MAX_LAST_HEADER_BYTES) {+ maxErrors += 1;+ } else {+ break;+ }+ }+ return maxErrors;+ }+ /**+ * Get the region discovery fields+ *+ * @returns string+ */+ getRegionDiscoveryFields() {+ const regionDiscoveryFields = [];+ regionDiscoveryFields.push(this.regionUsed || "");+ regionDiscoveryFields.push(this.regionSource || "");+ regionDiscoveryFields.push(this.regionOutcome || "");+ return regionDiscoveryFields.join(",");+ }+ /**+ * Update the region discovery metadata+ *+ * @param regionDiscoveryMetadata+ * @returns void+ */+ updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {+ this.regionUsed = regionDiscoveryMetadata.region_used;+ this.regionSource = regionDiscoveryMetadata.region_source;+ this.regionOutcome = regionDiscoveryMetadata.region_outcome;+ }+ /**+ * Set cache outcome+ */+ setCacheOutcome(cacheOutcome) {+ this.cacheOutcome = cacheOutcome;+ }+ setNativeBrokerErrorCode(errorCode) {+ const lastRequests = this.getLastRequests();+ lastRequests.nativeBrokerErrorCode = errorCode;+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);+ }+ getNativeBrokerErrorCode() {+ return this.getLastRequests().nativeBrokerErrorCode;+ }+ clearNativeBrokerErrorCode() {+ const lastRequests = this.getLastRequests();+ delete lastRequests.nativeBrokerErrorCode;+ this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);+ }+ static makeExtraSkuString(params) {+ return makeExtraSkuString(params);+ }+ };+ }+});++// node_modules/@azure/msal-common/dist/index-node.mjs+var init_index_node = __esm({+ "node_modules/@azure/msal-common/dist/index-node.mjs"() {+ "use strict";+ init_AuthorizationCodeClient();+ init_RefreshTokenClient();+ init_SilentFlowClient();+ init_ClientConfiguration();+ init_CcsCredential();+ init_Authority();+ init_AuthorityOptions();+ init_ProtocolMode();+ init_CacheManager();+ init_UrlString();+ init_Authorize();+ init_Token();+ init_BaseAuthRequest();+ init_RequestParameterBuilder();+ init_ResponseHandler();+ init_Logger();+ init_InteractionRequiredAuthError();+ init_AuthError();+ init_AuthErrorCodes();+ init_ServerError();+ init_NetworkError();+ init_ClientAuthError();+ init_ClientAuthErrorCodes();+ init_Constants();+ init_StringUtils();+ init_ServerTelemetryManager();+ init_AuthorityFactory();+ init_CacheHelpers();+ init_TimeUtils();+ init_UrlUtils();+ init_AADServerParamKeys();+ init_AccountEntityUtils();+ init_TokenCacheContext();+ init_ClientAssertionUtils();+ init_StubPerformanceClient();+ }+});++// node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs+var Deserializer;+var init_Deserializer = __esm({+ "node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs"() {+ "use strict";+ init_index_node();+ Deserializer = class {+ /**+ * Parse the JSON blob in memory and deserialize the content+ * @param cachedJson - JSON blob cache+ */+ static deserializeJSONBlob(jsonFile) {+ const deserializedCache = !jsonFile ? {} : JSON.parse(jsonFile);+ return deserializedCache;+ }+ /**+ * Deserializes accounts to AccountEntity objects+ * @param accounts - accounts of type SerializedAccountEntity+ */+ static deserializeAccounts(accounts) {+ const accountObjects = {};+ if (accounts) {+ Object.keys(accounts).map(function(key) {+ const serializedAcc = accounts[key];+ const mappedAcc = {+ homeAccountId: serializedAcc.home_account_id,+ environment: serializedAcc.environment,+ realm: serializedAcc.realm,+ localAccountId: serializedAcc.local_account_id,+ username: serializedAcc.username,+ authorityType: serializedAcc.authority_type,+ name: serializedAcc.name,+ clientInfo: serializedAcc.client_info,+ lastModificationTime: serializedAcc.last_modification_time,+ lastModificationApp: serializedAcc.last_modification_app,+ tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => {+ return JSON.parse(serializedTenantProfile);+ }),+ lastUpdatedAt: Date.now().toString()+ };+ const account = {};+ CacheManager.toObject(account, mappedAcc);+ accountObjects[key] = account;+ });+ }+ return accountObjects;+ }+ /**+ * Deserializes id tokens to IdTokenEntity objects+ * @param idTokens - credentials of type SerializedIdTokenEntity+ */+ static deserializeIdTokens(idTokens) {+ const idObjects = {};+ if (idTokens) {+ Object.keys(idTokens).map(function(key) {+ const serializedIdT = idTokens[key];+ const idToken = {+ homeAccountId: serializedIdT.home_account_id,+ environment: serializedIdT.environment,+ credentialType: serializedIdT.credential_type,+ clientId: serializedIdT.client_id,+ secret: serializedIdT.secret,+ realm: serializedIdT.realm,+ lastUpdatedAt: Date.now().toString()+ };+ idObjects[key] = idToken;+ });+ }+ return idObjects;+ }+ /**+ * Deserializes access tokens to AccessTokenEntity objects+ * @param accessTokens - access tokens of type SerializedAccessTokenEntity+ */+ static deserializeAccessTokens(accessTokens) {+ const atObjects = {};+ if (accessTokens) {+ Object.keys(accessTokens).map(function(key) {+ const serializedAT = accessTokens[key];+ const accessToken = {+ homeAccountId: serializedAT.home_account_id,+ environment: serializedAT.environment,+ credentialType: serializedAT.credential_type,+ clientId: serializedAT.client_id,+ secret: serializedAT.secret,+ realm: serializedAT.realm,+ target: serializedAT.target,+ cachedAt: serializedAT.cached_at,+ expiresOn: serializedAT.expires_on,+ extendedExpiresOn: serializedAT.extended_expires_on,+ refreshOn: serializedAT.refresh_on,+ keyId: serializedAT.key_id,+ tokenType: serializedAT.token_type,+ userAssertionHash: serializedAT.userAssertionHash,+ resource: serializedAT.resource,+ additionalCacheKeyComponents: serializedAT.additionalCacheKeyComponents,+ lastUpdatedAt: Date.now().toString()+ };+ atObjects[key] = accessToken;+ });+ }+ return atObjects;+ }+ /**+ * Deserializes refresh tokens to RefreshTokenEntity objects+ * @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity+ */+ static deserializeRefreshTokens(refreshTokens) {+ const rtObjects = {};+ if (refreshTokens) {+ Object.keys(refreshTokens).map(function(key) {+ const serializedRT = refreshTokens[key];+ const refreshToken = {+ homeAccountId: serializedRT.home_account_id,+ environment: serializedRT.environment,+ credentialType: serializedRT.credential_type,+ clientId: serializedRT.client_id,+ secret: serializedRT.secret,+ familyId: serializedRT.family_id,+ target: serializedRT.target,+ realm: serializedRT.realm,+ lastUpdatedAt: Date.now().toString()+ };+ rtObjects[key] = refreshToken;+ });+ }+ return rtObjects;+ }+ /**+ * Deserializes appMetadata to AppMetaData objects+ * @param appMetadata - app metadata of type SerializedAppMetadataEntity+ */+ static deserializeAppMetadata(appMetadata) {+ const appMetadataObjects = {};+ if (appMetadata) {+ Object.keys(appMetadata).map(function(key) {+ const serializedAmdt = appMetadata[key];+ appMetadataObjects[key] = {+ clientId: serializedAmdt.client_id,+ environment: serializedAmdt.environment,+ familyId: serializedAmdt.family_id+ };+ });+ }+ return appMetadataObjects;+ }+ /**+ * Deserialize an inMemory Cache+ * @param jsonCache - JSON blob cache+ */+ static deserializeAllCache(jsonCache) {+ return {+ accounts: jsonCache.Account ? this.deserializeAccounts(jsonCache.Account) : {},+ idTokens: jsonCache.IdToken ? this.deserializeIdTokens(jsonCache.IdToken) : {},+ accessTokens: jsonCache.AccessToken ? this.deserializeAccessTokens(jsonCache.AccessToken) : {},+ refreshTokens: jsonCache.RefreshToken ? this.deserializeRefreshTokens(jsonCache.RefreshToken) : {},+ appMetadata: jsonCache.AppMetadata ? this.deserializeAppMetadata(jsonCache.AppMetadata) : {}+ };+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/internals.mjs+var init_internals = __esm({+ "node_modules/@azure/msal-node/dist/internals.mjs"() {+ "use strict";+ init_Serializer();+ init_Deserializer();+ }+});++// node_modules/@azure/msal-node/dist/utils/Constants.mjs+var MANAGED_IDENTITY_DEFAULT_TENANT, DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod2, RANDOM_OCTET_SIZE, Hash, CharSet, CACHE, Constants, ApiId, JwtConstants, LOOPBACK_SERVER_CONSTANTS;+var init_Constants2 = __esm({+ "node_modules/@azure/msal-node/dist/utils/Constants.mjs"() {+ "use strict";+ init_index_node();+ MANAGED_IDENTITY_DEFAULT_TENANT = "managed_identity";+ DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY = `https://login.microsoftonline.com/${MANAGED_IDENTITY_DEFAULT_TENANT}/`;+ ManagedIdentityHeaders = {+ AUTHORIZATION_HEADER_NAME: "Authorization",+ METADATA_HEADER_NAME: "Metadata",+ APP_SERVICE_SECRET_HEADER_NAME: "X-IDENTITY-HEADER",+ ML_AND_SF_SECRET_HEADER_NAME: "secret",+ CLIENT_SKU: AADServerParamKeys_exports.X_CLIENT_SKU,+ CLIENT_VER: AADServerParamKeys_exports.X_CLIENT_VER,+ CLIENT_REQUEST_ID: "x-ms-client-request-id"+ };+ ManagedIdentityQueryParameters = {+ API_VERSION: "api-version",+ RESOURCE: "resource",+ SHA256_TOKEN_TO_REFRESH: "token_sha256_to_refresh",+ XMS_CC: "xms_cc"+ };+ ManagedIdentityEnvironmentVariableNames = {+ AZURE_POD_IDENTITY_AUTHORITY_HOST: "AZURE_POD_IDENTITY_AUTHORITY_HOST",+ DEFAULT_IDENTITY_CLIENT_ID: "DEFAULT_IDENTITY_CLIENT_ID",+ IDENTITY_ENDPOINT: "IDENTITY_ENDPOINT",+ IDENTITY_HEADER: "IDENTITY_HEADER",+ IDENTITY_SERVER_THUMBPRINT: "IDENTITY_SERVER_THUMBPRINT",+ IMDS_ENDPOINT: "IMDS_ENDPOINT",+ MSI_ENDPOINT: "MSI_ENDPOINT",+ MSI_SECRET: "MSI_SECRET"+ };+ ManagedIdentitySourceNames = {+ APP_SERVICE: "AppService",+ AZURE_ARC: "AzureArc",+ CLOUD_SHELL: "CloudShell",+ DEFAULT_TO_IMDS: "DefaultToImds",+ IMDS: "Imds",+ MACHINE_LEARNING: "MachineLearning",+ SERVICE_FABRIC: "ServiceFabric"+ };+ ManagedIdentityIdType = {+ SYSTEM_ASSIGNED: "system-assigned",+ USER_ASSIGNED_CLIENT_ID: "user-assigned-client-id",+ USER_ASSIGNED_RESOURCE_ID: "user-assigned-resource-id",+ USER_ASSIGNED_OBJECT_ID: "user-assigned-object-id"+ };+ HttpMethod2 = {+ GET: "GET",+ POST: "POST"+ };+ RANDOM_OCTET_SIZE = 32;+ Hash = {+ SHA256: "sha256"+ };+ CharSet = {+ CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"+ };+ CACHE = {+ KEY_SEPARATOR: "-"+ };+ Constants = {+ MSAL_SKU: "msal.js.node",+ JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",+ HTTP_PROTOCOL: "http://",+ LOCALHOST: "localhost"+ };+ ApiId = {+ acquireTokenSilent: 62,+ acquireTokenByUsernamePassword: 371,+ acquireTokenByDeviceCode: 671,+ acquireTokenByClientCredential: 771,+ acquireTokenByOBO: 772,+ acquireTokenWithManagedIdentity: 773,+ acquireTokenByUserFederatedIdentityCredential: 774,+ acquireTokenByCode: 871,+ acquireTokenByRefreshToken: 872+ };+ JwtConstants = {+ RSA_256: "RS256",+ PSS_256: "PS256",+ X5T_256: "x5t#S256",+ X5T: "x5t",+ X5C: "x5c",+ AUDIENCE: "aud",+ EXPIRATION_TIME: "exp",+ ISSUER: "iss",+ SUBJECT: "sub",+ NOT_BEFORE: "nbf",+ JWT_ID: "jti"+ };+ LOOPBACK_SERVER_CONSTANTS = {+ INTERVAL_MS: 100,+ TIMEOUT_MS: 5e3+ };+ }+});++// node_modules/@azure/msal-node/dist/network/HttpClient.mjs+function getHeaderDict(headers) {+ const headerDict = {};+ headers.forEach((value, key) => {+ headerDict[key] = value;+ });+ return headerDict;+}+function getFetchHeaders(options) {+ const headers = new Headers();+ if (!(options && options.headers)) {+ return headers;+ }+ Object.entries(options.headers).forEach(([key, value]) => {+ headers.append(key, value);+ });+ return headers;+}+var HttpClient;+var init_HttpClient = __esm({+ "node_modules/@azure/msal-node/dist/network/HttpClient.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ HttpClient = class {+ /**+ * Sends an HTTP GET request to the specified URL.+ *+ * This method handles GET requests with optional timeout support. The timeout+ * is implemented using AbortController, which provides a clean way to cancel+ * fetch requests that take too long to complete.+ *+ * @param url - The target URL for the GET request+ * @param options - Optional request configuration including headers+ * @param timeout - Optional timeout in milliseconds. If specified, the request+ * will be aborted if it doesn't complete within this time+ * @returns Promise that resolves to a NetworkResponse containing headers, body, and status+ * @throws {AuthError} When the request times out or response parsing fails+ * @throws {NetworkError} When the network request fails+ */+ async sendGetRequestAsync(url, options, timeout) {+ return this.sendRequest(url, HttpMethod2.GET, options, timeout);+ }+ /**+ * Sends an HTTP POST request to the specified URL.+ *+ * This method handles POST requests with request body support. Currently,+ * timeout functionality is not exposed for POST requests, but the underlying+ * implementation supports it through the shared sendRequest method.+ *+ * @param url - The target URL for the POST request+ * @param options - Optional request configuration including headers and body+ * @returns Promise that resolves to a NetworkResponse containing headers, body, and status+ * @throws {AuthError} When the request times out or response parsing fails+ * @throws {NetworkError} When the network request fails+ */+ async sendPostRequestAsync(url, options) {+ return this.sendRequest(url, HttpMethod2.POST, options);+ }+ /**+ * Core HTTP request implementation using native fetch API.+ *+ * This method handles GET and POST HTTP requests with comprehensive+ * timeout support and error handling. The timeout mechanism works as follows:+ *+ * 1. An AbortController is created for each request+ * 2. If a timeout is specified, setTimeout is used to call abort() after the delay+ * 3. The abort signal is passed to fetch, which will reject the promise if aborted+ * 4. Cleanup occurs in both success and error cases to prevent timer leaks+ *+ * Error handling priority:+ * 1. Timeout errors (AbortError) are converted to "Request timeout" messages+ * 2. Network/connection errors are wrapped with "Network request failed" prefix+ * 3. JSON parsing errors are wrapped with "Failed to parse response" prefix+ *+ * @param url - The target URL for the request+ * @param method - HTTP method (GET or POST)+ * @param options - Optional request configuration (headers, body)+ * @param timeout - Optional timeout in milliseconds for request cancellation+ * @returns Promise resolving to NetworkResponse with parsed JSON body+ * @throws {AuthError} For timeouts or JSON parsing errors+ * @throws {NetworkError} For network failures+ */+ async sendRequest(url, method, options, timeout) {+ const controller = new AbortController();+ let timeoutId;+ if (timeout) {+ timeoutId = setTimeout(() => {+ controller.abort();+ }, timeout);+ }+ const fetchOptions = {+ method,+ headers: getFetchHeaders(options),+ signal: controller.signal+ // Enable cancellation via AbortController+ };+ if (method === HttpMethod2.POST) {+ fetchOptions.body = options?.body || "";+ }+ let response;+ try {+ response = await fetch(url, fetchOptions);+ } catch (error2) {+ if (timeoutId) {+ clearTimeout(timeoutId);+ }+ if (error2 instanceof Error && error2.name === "AbortError") {+ throw createAuthError(ClientAuthErrorCodes_exports.networkError, "", "Request timeout");+ }+ const baseAuthError = createAuthError(ClientAuthErrorCodes_exports.networkError, "", `Network request failed: ${error2 instanceof Error ? error2.message : "unknown"}`);+ throw createNetworkError(baseAuthError, void 0, void 0, error2 instanceof Error ? error2 : void 0);+ }+ if (timeoutId) {+ clearTimeout(timeoutId);+ }+ try {+ return {+ headers: getHeaderDict(response.headers),+ body: await response.json(),+ status: response.status+ };+ } catch (error2) {+ throw createAuthError(ClientAuthErrorCodes_exports.tokenParsingError, "", `Failed to parse response: ${error2 instanceof Error ? error2.message : "unknown"}`);+ }+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs+var invalidFileExtension, invalidFilePath, invalidManagedIdentityIdType, invalidSecret, missingId, networkUnavailable, platformNotSupported, unableToCreateAzureArc, unableToCreateCloudShell, unableToCreateSource, unableToReadSecretFile, userAssignedNotAvailableAtRuntime, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat, MsiEnvironmentVariableUrlMalformedErrorCodes;+var init_ManagedIdentityErrorCodes = __esm({+ "node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs"() {+ "use strict";+ init_Constants2();+ invalidFileExtension = "invalid_file_extension";+ invalidFilePath = "invalid_file_path";+ invalidManagedIdentityIdType = "invalid_managed_identity_id_type";+ invalidSecret = "invalid_secret";+ missingId = "missing_client_id";+ networkUnavailable = "network_unavailable";+ platformNotSupported = "platform_not_supported";+ unableToCreateAzureArc = "unable_to_create_azure_arc";+ unableToCreateCloudShell = "unable_to_create_cloud_shell";+ unableToCreateSource = "unable_to_create_source";+ unableToReadSecretFile = "unable_to_read_secret_file";+ userAssignedNotAvailableAtRuntime = "user_assigned_not_available_at_runtime";+ wwwAuthenticateHeaderMissing = "www_authenticate_header_missing";+ wwwAuthenticateHeaderUnsupportedFormat = "www_authenticate_header_unsupported_format";+ MsiEnvironmentVariableUrlMalformedErrorCodes = {+ [ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]: "azure_pod_identity_authority_host_url_malformed",+ [ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]: "identity_endpoint_url_malformed",+ [ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]: "imds_endpoint_url_malformed",+ [ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]: "msi_endpoint_url_malformed"+ };+ }+});++// node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs+function createManagedIdentityError(errorCode, correlationId) {+ return new ManagedIdentityError(errorCode, correlationId);+}+var ManagedIdentityErrorMessages, ManagedIdentityError;+var init_ManagedIdentityError = __esm({+ "node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs"() {+ "use strict";+ init_index_node();+ init_ManagedIdentityErrorCodes();+ init_Constants2();+ ManagedIdentityErrorMessages = {+ [invalidFileExtension]: "The file path in the WWW-Authenticate header does not contain a .key file.",+ [invalidFilePath]: "The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.",+ [invalidManagedIdentityIdType]: "More than one ManagedIdentityIdType was provided.",+ [invalidSecret]: "The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.",+ [platformNotSupported]: "The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.",+ [missingId]: "A ManagedIdentityId id was not provided.",+ [MsiEnvironmentVariableUrlMalformedErrorCodes.AZURE_POD_IDENTITY_AUTHORITY_HOST]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`,+ [MsiEnvironmentVariableUrlMalformedErrorCodes.IDENTITY_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variable is malformed.`,+ [MsiEnvironmentVariableUrlMalformedErrorCodes.IMDS_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' environment variable is malformed.`,+ [MsiEnvironmentVariableUrlMalformedErrorCodes.MSI_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' environment variable is malformed.`,+ [networkUnavailable]: "Authentication unavailable. The request to the managed identity endpoint timed out.",+ [unableToCreateAzureArc]: "Azure Arc Managed Identities can only be system assigned.",+ [unableToCreateCloudShell]: "Cloud Shell Managed Identities can only be system assigned.",+ [unableToCreateSource]: "Unable to create a Managed Identity source based on environment variables.",+ [unableToReadSecretFile]: "Unable to read the secret file.",+ [userAssignedNotAvailableAtRuntime]: "Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.",+ [wwwAuthenticateHeaderMissing]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.",+ [wwwAuthenticateHeaderUnsupportedFormat]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format."+ };+ ManagedIdentityError = class _ManagedIdentityError extends AuthError {+ constructor(errorCode, correlationId) {+ super(errorCode, correlationId, ManagedIdentityErrorMessages[errorCode]);+ this.name = "ManagedIdentityError";+ Object.setPrototypeOf(this, _ManagedIdentityError.prototype);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs+var init_ManagedIdentityId = __esm({+ "node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs"() {+ "use strict";+ init_ManagedIdentityError();+ init_Constants2();+ init_ManagedIdentityErrorCodes();+ }+});++// node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs+var NodeAuthErrorMessage, NodeAuthError;+var init_NodeAuthError = __esm({+ "node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs"() {+ "use strict";+ init_index_node();+ NodeAuthErrorMessage = {+ invalidLoopbackAddressType: {+ code: "invalid_loopback_server_address_type",+ desc: "Loopback server address is not type string. This is unexpected."+ },+ unableToLoadRedirectUri: {+ code: "unable_to_load_redirectUrl",+ desc: "Loopback server callback was invoked without a url. This is unexpected."+ },+ noAuthCodeInResponse: {+ code: "no_auth_code_in_response",+ desc: "No auth code found in the server response. Please check your network trace to determine what happened."+ },+ noLoopbackServerExists: {+ code: "no_loopback_server_exists",+ desc: "No loopback server exists yet."+ },+ loopbackServerAlreadyExists: {+ code: "loopback_server_already_exists",+ desc: "Loopback server already exists. Cannot create another."+ },+ loopbackServerTimeout: {+ code: "loopback_server_timeout",+ desc: "Timed out waiting for auth code listener to be registered."+ },+ stateNotFoundError: {+ code: "state_not_found",+ desc: "State not found. Please verify that the request originated from msal."+ },+ thumbprintMissing: {+ code: "thumbprint_missing_from_client_certificate",+ desc: "Client certificate does not contain a SHA-1 or SHA-256 thumbprint."+ },+ redirectUriNotSupported: {+ code: "redirect_uri_not_supported",+ desc: "RedirectUri is not supported in this scenario. Please remove redirectUri from the request."+ }+ };+ NodeAuthError = class _NodeAuthError extends AuthError {+ constructor(errorCode, correlationId, errorMessage) {+ super(errorCode, correlationId, errorMessage);+ this.name = "NodeAuthError";+ }+ /**+ * Creates an error thrown if loopback server address is of type string.+ */+ static createInvalidLoopbackAddressTypeError() {+ return new _NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, "", `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);+ }+ /**+ * Creates an error thrown if the loopback server is unable to get a url.+ */+ static createUnableToLoadRedirectUrlError() {+ return new _NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, "", `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);+ }+ /**+ * Creates an error thrown if the server response does not contain an auth code.+ */+ static createNoAuthCodeInResponseError(correlationId = "") {+ return new _NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, correlationId, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);+ }+ /**+ * Creates an error thrown if the loopback server has not been spun up yet.+ */+ static createNoLoopbackServerExistsError() {+ return new _NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, "", `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);+ }+ /**+ * Creates an error thrown if a loopback server already exists when attempting to create another one.+ */+ static createLoopbackServerAlreadyExistsError() {+ return new _NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, "", `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);+ }+ /**+ * Creates an error thrown if the loopback server times out registering the auth code listener.+ */+ static createLoopbackServerTimeoutError(correlationId = "") {+ return new _NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, correlationId, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);+ }+ /**+ * Creates an error thrown when the state is not present.+ */+ static createStateNotFoundError(correlationId = "") {+ return new _NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, correlationId, NodeAuthErrorMessage.stateNotFoundError.desc);+ }+ /**+ * Creates an error thrown when client certificate was provided, but neither the SHA-1 or SHA-256 thumbprints were provided+ */+ static createThumbprintMissingError() {+ return new _NodeAuthError(NodeAuthErrorMessage.thumbprintMissing.code, "", NodeAuthErrorMessage.thumbprintMissing.desc);+ }+ /**+ * Creates an error thrown when redirectUri is provided in an unsupported scenario+ */+ static createRedirectUriNotSupportedError(correlationId = "") {+ return new _NodeAuthError(NodeAuthErrorMessage.redirectUriNotSupported.code, correlationId, NodeAuthErrorMessage.redirectUriNotSupported.desc);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/config/Configuration.mjs+function buildAppConfiguration({ auth: auth2, broker, cache, system, telemetry }) {+ const systemOptions = {+ ...DEFAULT_SYSTEM_OPTIONS2,+ networkClient: new HttpClient(),+ loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS,+ disableInternalRetries: system?.disableInternalRetries || false+ };+ if (!!auth2.clientCertificate && !!!auth2.clientCertificate.thumbprint && !!!auth2.clientCertificate.thumbprintSha256) {+ throw NodeAuthError.createStateNotFoundError();+ }+ return {+ auth: { ...DEFAULT_AUTH_OPTIONS, ...auth2 },+ broker: { ...broker },+ cache: { ...cache },+ system: { ...systemOptions, ...system },+ telemetry: { ...DEFAULT_TELEMETRY_OPTIONS2, ...telemetry }+ };+}+var DEFAULT_AUTH_OPTIONS, DEFAULT_LOGGER_OPTIONS, DEFAULT_SYSTEM_OPTIONS2, DEFAULT_TELEMETRY_OPTIONS2;+var init_Configuration = __esm({+ "node_modules/@azure/msal-node/dist/config/Configuration.mjs"() {+ "use strict";+ init_index_node();+ init_HttpClient();+ init_ManagedIdentityId();+ init_NodeAuthError();+ DEFAULT_AUTH_OPTIONS = {+ clientId: "",+ authority: Constants_exports.DEFAULT_AUTHORITY,+ clientSecret: "",+ clientAssertion: "",+ clientCertificate: {+ thumbprint: "",+ thumbprintSha256: "",+ privateKey: "",+ x5c: ""+ },+ knownAuthorities: [],+ cloudDiscoveryMetadata: "",+ authorityMetadata: "",+ clientCapabilities: [],+ azureCloudOptions: {+ azureCloudInstance: AzureCloudInstance.None,+ tenant: ""+ },+ isMcp: false+ };+ DEFAULT_LOGGER_OPTIONS = {+ loggerCallback: () => {+ },+ piiLoggingEnabled: false,+ logLevel: LogLevel.Info+ };+ DEFAULT_SYSTEM_OPTIONS2 = {+ loggerOptions: DEFAULT_LOGGER_OPTIONS,+ networkClient: new HttpClient(),+ disableInternalRetries: false,+ protocolMode: ProtocolMode.AAD+ };+ DEFAULT_TELEMETRY_OPTIONS2 = {+ application: {+ appName: "",+ appVersion: ""+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs+import { randomUUID as randomUUID3 } from "node:crypto";+var GuidGenerator;+var init_GuidGenerator = __esm({+ "node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs"() {+ "use strict";+ GuidGenerator = class {+ /**+ * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a+ * cryptographic pseudorandom number generator.+ */+ generateGuid() {+ return randomUUID3();+ }+ /**+ * verifies if a string is GUID+ * @param guid+ */+ isGuid(guid2) {+ const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+ return regexGuid.test(guid2);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs+var EncodingUtils;+var init_EncodingUtils = __esm({+ "node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs"() {+ "use strict";+ init_index_node();+ EncodingUtils = class _EncodingUtils {+ /**+ * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.+ * 'base64': Base64 encoding.+ *+ * @param str text+ */+ static base64Encode(str, encoding) {+ return Buffer.from(str, encoding).toString(Constants_exports.EncodingTypes.BASE64);+ }+ /**+ * encode a URL+ * @param str+ */+ static base64EncodeUrl(str, encoding) {+ return _EncodingUtils.base64Encode(str, encoding).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");+ }+ /**+ * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.+ * 'base64': Base64 encoding.+ *+ * @param base64Str Base64 encoded text+ */+ static base64Decode(base64Str) {+ return Buffer.from(base64Str, Constants_exports.EncodingTypes.BASE64).toString("utf8");+ }+ /**+ * @param base64Str Base64 encoded Url+ */+ static base64DecodeUrl(base64Str) {+ let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");+ while (str.length % 4) {+ str += "=";+ }+ return _EncodingUtils.base64Decode(str);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs+import crypto from "crypto";+var HashUtils;+var init_HashUtils = __esm({+ "node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs"() {+ "use strict";+ init_Constants2();+ HashUtils = class {+ /**+ * generate 'SHA256' hash+ * @param buffer+ */+ sha256(buffer) {+ return crypto.createHash(Hash.SHA256).update(buffer).digest();+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs+import crypto2 from "crypto";+var PkceGenerator;+var init_PkceGenerator = __esm({+ "node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ init_EncodingUtils();+ init_HashUtils();+ PkceGenerator = class {+ constructor() {+ this.hashUtils = new HashUtils();+ }+ /**+ * generates the codeVerfier and the challenge from the codeVerfier+ * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2+ */+ async generatePkceCodes() {+ const verifier = this.generateCodeVerifier();+ const challenge = this.generateCodeChallengeFromVerifier(verifier);+ return { verifier, challenge };+ }+ /**+ * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1+ */+ generateCodeVerifier() {+ const charArr = [];+ const maxNumber = 256 - 256 % CharSet.CV_CHARSET.length;+ while (charArr.length <= RANDOM_OCTET_SIZE) {+ const byte = crypto2.randomBytes(1)[0];+ if (byte >= maxNumber) {+ continue;+ }+ const index = byte % CharSet.CV_CHARSET.length;+ charArr.push(CharSet.CV_CHARSET[index]);+ }+ const verifier = charArr.join("");+ return EncodingUtils.base64EncodeUrl(verifier);+ }+ /**+ * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2+ * @param codeVerifier+ */+ generateCodeChallengeFromVerifier(codeVerifier) {+ return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString(Constants_exports.EncodingTypes.BASE64), Constants_exports.EncodingTypes.BASE64);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs+var CryptoProvider;+var init_CryptoProvider = __esm({+ "node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs"() {+ "use strict";+ init_index_node();+ init_GuidGenerator();+ init_EncodingUtils();+ init_PkceGenerator();+ init_HashUtils();+ CryptoProvider = class {+ constructor() {+ this.pkceGenerator = new PkceGenerator();+ this.guidGenerator = new GuidGenerator();+ this.hashUtils = new HashUtils();+ }+ /**+ * base64 URL safe encoded string+ */+ base64UrlEncode() {+ throw new Error("Method not implemented.");+ }+ /**+ * Stringifies and base64Url encodes input public key+ * @param inputKid - public key id+ * @returns Base64Url encoded public key+ */+ encodeKid() {+ throw new Error("Method not implemented.");+ }+ /**+ * Creates a new random GUID - used to populate state and nonce.+ * @returns string (GUID)+ */+ createNewGuid() {+ return this.guidGenerator.generateGuid();+ }+ /**+ * Encodes input string to base64.+ * @param input - string to be encoded+ */+ base64Encode(input) {+ return EncodingUtils.base64Encode(input);+ }+ /**+ * Decodes input string from base64.+ * @param input - string to be decoded+ */+ base64Decode(input) {+ return EncodingUtils.base64Decode(input);+ }+ /**+ * Generates PKCE codes used in Authorization Code Flow.+ */+ generatePkceCodes() {+ return this.pkceGenerator.generatePkceCodes();+ }+ /**+ * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node+ */+ getPublicKeyThumbprint() {+ throw new Error("Method not implemented.");+ }+ /**+ * Removes cryptographic keypair from key store matching the keyId passed in+ * @param kid - public key id+ */+ removeTokenBindingKey() {+ throw new Error("Method not implemented.");+ }+ /**+ * Removes all cryptographic keys from Keystore+ */+ clearKeystore() {+ throw new Error("Method not implemented.");+ }+ /**+ * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node+ */+ signJwt() {+ throw new Error("Method not implemented.");+ }+ /**+ * Returns the SHA-256 hash of an input string+ */+ async hashString(plainText) {+ return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString(Constants_exports.EncodingTypes.BASE64), Constants_exports.EncodingTypes.BASE64);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs+import { createHash as createHash2 } from "crypto";+function computeAdditionalCacheKeyHash(components) {+ const sortedKeys = Object.keys(components).sort();+ const input = sortedKeys.map((k) => k + components[k]).join("");+ return createHash2("sha256").update(input, "utf8").digest("base64url");+}+function generateCredentialKey(credential) {+ const familyId = credential.credentialType === Constants_exports.CredentialType.REFRESH_TOKEN && credential.familyId || credential.clientId;+ const scheme = credential.tokenType && credential.tokenType.toLowerCase() !== Constants_exports.AuthenticationScheme.BEARER.toLowerCase() ? credential.tokenType.toLowerCase() : "";+ const credentialKey = [+ credential.homeAccountId,+ credential.environment,+ credential.credentialType,+ familyId,+ credential.realm || "",+ credential.target || "",+ scheme+ ];+ if (credential.additionalCacheKeyComponents && Object.keys(credential.additionalCacheKeyComponents).length > 0) {+ credentialKey.push(computeAdditionalCacheKeyHash(credential.additionalCacheKeyComponents));+ }+ return credentialKey.join(CACHE.KEY_SEPARATOR).toLowerCase();+}+function generateAccountKey(account) {+ const homeTenantId = account.homeAccountId.split(".")[1];+ const accountKey = [+ account.homeAccountId,+ account.environment,+ homeTenantId || account.tenantId || ""+ ];+ return accountKey.join(CACHE.KEY_SEPARATOR).toLowerCase();+}+var init_CacheHelpers2 = __esm({+ "node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ }+});++// node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs+var NodeStorage;+var init_NodeStorage = __esm({+ "node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs"() {+ "use strict";+ init_index_node();+ init_Deserializer();+ init_Serializer();+ init_CacheHelpers2();+ NodeStorage = class extends CacheManager {+ constructor(logger2, clientId, cryptoImpl, staticAuthorityOptions) {+ super(clientId, cryptoImpl, logger2, new StubPerformanceClient(), staticAuthorityOptions);+ this.cache = {};+ this.changeEmitters = [];+ this.logger = logger2;+ }+ /**+ * Queue up callbacks+ * @param func - a callback function for cache change indication+ */+ registerChangeEmitter(func) {+ this.changeEmitters.push(func);+ }+ /**+ * Invoke the callback when cache changes+ */+ emitChange() {+ this.changeEmitters.forEach((func) => func.call(null));+ }+ /**+ * Converts cacheKVStore to InMemoryCache+ * @param cache - key value store+ */+ cacheToInMemoryCache(cache) {+ const inMemoryCache = {+ accounts: {},+ idTokens: {},+ accessTokens: {},+ refreshTokens: {},+ appMetadata: {}+ };+ for (const key in cache) {+ const value = cache[key];+ if (typeof value !== "object") {+ continue;+ }+ if (AccountEntityUtils_exports.isAccountEntity(value)) {+ inMemoryCache.accounts[key] = value;+ } else if (CacheHelpers_exports.isIdTokenEntity(value)) {+ inMemoryCache.idTokens[key] = value;+ } else if (CacheHelpers_exports.isAccessTokenEntity(value)) {+ inMemoryCache.accessTokens[key] = value;+ } else if (CacheHelpers_exports.isRefreshTokenEntity(value)) {+ inMemoryCache.refreshTokens[key] = value;+ } else if (CacheHelpers_exports.isAppMetadataEntity(key, value)) {+ inMemoryCache.appMetadata[key] = value;+ } else {+ continue;+ }+ }+ return inMemoryCache;+ }+ /**+ * converts inMemoryCache to CacheKVStore+ * @param inMemoryCache - kvstore map for inmemory+ */+ inMemoryCacheToCache(inMemoryCache) {+ let cache = this.getCache();+ cache = {+ ...cache,+ ...inMemoryCache.accounts,+ ...inMemoryCache.idTokens,+ ...inMemoryCache.accessTokens,+ ...inMemoryCache.refreshTokens,+ ...inMemoryCache.appMetadata+ };+ return cache;+ }+ /**+ * gets the current in memory cache for the client+ */+ getInMemoryCache() {+ this.logger.trace("Getting in-memory cache", "");+ const inMemoryCache = this.cacheToInMemoryCache(this.getCache());+ return inMemoryCache;+ }+ /**+ * sets the current in memory cache for the client+ * @param inMemoryCache - key value map in memory+ */+ setInMemoryCache(inMemoryCache) {+ this.logger.trace("Setting in-memory cache", "");+ const cache = this.inMemoryCacheToCache(inMemoryCache);+ this.setCache(cache);+ this.emitChange();+ }+ /**+ * get the current cache key-value store+ */+ getCache() {+ this.logger.trace("Getting cache key-value store", "");+ return this.cache;+ }+ /**+ * sets the current cache (key value store)+ * @param cacheMap - key value map+ */+ setCache(cache) {+ this.logger.trace("Setting cache key value store", "");+ this.cache = cache;+ this.emitChange();+ }+ /**+ * Gets cache item with given key.+ * @param key - lookup key for the cache entry+ */+ getItem(key) {+ this.logger.tracePii(`Item key: ${key}`, "");+ const cache = this.getCache();+ return cache[key];+ }+ /**+ * Gets cache item with given key-value+ * @param key - lookup key for the cache entry+ * @param value - value of the cache entry+ */+ setItem(key, value) {+ this.logger.tracePii(`Item key: ${key}`, "");+ const cache = this.getCache();+ cache[key] = value;+ this.setCache(cache);+ }+ generateCredentialKey(credential) {+ return generateCredentialKey(credential);+ }+ generateAccountKey(account) {+ return generateAccountKey(account);+ }+ getAccountKeys() {+ const inMemoryCache = this.getInMemoryCache();+ const accountKeys = Object.keys(inMemoryCache.accounts);+ return accountKeys;+ }+ getTokenKeys() {+ const inMemoryCache = this.getInMemoryCache();+ const tokenKeys = {+ idToken: Object.keys(inMemoryCache.idTokens),+ accessToken: Object.keys(inMemoryCache.accessTokens),+ refreshToken: Object.keys(inMemoryCache.refreshTokens)+ };+ return tokenKeys;+ }+ /**+ * Reads account from cache, builds it into an account entity and returns it.+ * @param accountKey - lookup key to fetch cache type AccountEntity+ * @returns+ */+ getAccount(accountKey) {+ const cachedAccount = this.getItem(accountKey);+ return cachedAccount && typeof cachedAccount === "object" ? { ...cachedAccount } : null;+ }+ /**+ * set account entity+ * @param account - cache value to be set of type AccountEntity+ */+ async setAccount(account) {+ const accountKey = this.generateAccountKey(AccountEntityUtils_exports.getAccountInfo(account));+ this.setItem(accountKey, account);+ }+ /**+ * fetch the idToken credential+ * @param idTokenKey - lookup key to fetch cache type IdTokenEntity+ */+ getIdTokenCredential(idTokenKey) {+ const idToken = this.getItem(idTokenKey);+ if (CacheHelpers_exports.isIdTokenEntity(idToken)) {+ return idToken;+ }+ return null;+ }+ /**+ * set idToken credential+ * @param idToken - cache value to be set of type IdTokenEntity+ */+ async setIdTokenCredential(idToken) {+ const idTokenKey = this.generateCredentialKey(idToken);+ this.setItem(idTokenKey, idToken);+ }+ /**+ * fetch the accessToken credential+ * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity+ */+ getAccessTokenCredential(accessTokenKey) {+ const accessToken = this.getItem(accessTokenKey);+ if (CacheHelpers_exports.isAccessTokenEntity(accessToken)) {+ return accessToken;+ }+ return null;+ }+ /**+ * set accessToken credential+ * @param accessToken - cache value to be set of type AccessTokenEntity+ */+ async setAccessTokenCredential(accessToken) {+ const accessTokenKey = this.generateCredentialKey(accessToken);+ this.setItem(accessTokenKey, accessToken);+ }+ /**+ * fetch the refreshToken credential+ * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity+ */+ getRefreshTokenCredential(refreshTokenKey) {+ const refreshToken = this.getItem(refreshTokenKey);+ if (CacheHelpers_exports.isRefreshTokenEntity(refreshToken)) {+ return refreshToken;+ }+ return null;+ }+ /**+ * set refreshToken credential+ * @param refreshToken - cache value to be set of type RefreshTokenEntity+ */+ async setRefreshTokenCredential(refreshToken) {+ const refreshTokenKey = this.generateCredentialKey(refreshToken);+ this.setItem(refreshTokenKey, refreshToken);+ }+ /**+ * fetch appMetadata entity from the platform cache+ * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity+ */+ getAppMetadata(appMetadataKey) {+ const appMetadata = this.getItem(appMetadataKey);+ if (CacheHelpers_exports.isAppMetadataEntity(appMetadataKey, appMetadata)) {+ return appMetadata;+ }+ return null;+ }+ /**+ * set appMetadata entity to the platform cache+ * @param appMetadata - cache value to be set of type AppMetadataEntity+ */+ setAppMetadata(appMetadata) {+ const appMetadataKey = CacheHelpers_exports.generateAppMetadataKey(appMetadata);+ this.setItem(appMetadataKey, appMetadata);+ }+ /**+ * fetch server telemetry entity from the platform cache+ * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity+ */+ getServerTelemetry(serverTelemetrykey) {+ const serverTelemetryEntity = this.getItem(serverTelemetrykey);+ if (serverTelemetryEntity && CacheHelpers_exports.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {+ return serverTelemetryEntity;+ }+ return null;+ }+ /**+ * set server telemetry entity to the platform cache+ * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity+ * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity+ */+ setServerTelemetry(serverTelemetryKey, serverTelemetry) {+ this.setItem(serverTelemetryKey, serverTelemetry);+ }+ /**+ * fetch authority metadata entity from the platform cache+ * @param key - lookup key to fetch cache type AuthorityMetadataEntity+ */+ getAuthorityMetadata(key) {+ const authorityMetadataEntity = this.getItem(key);+ if (authorityMetadataEntity && CacheHelpers_exports.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {+ return authorityMetadataEntity;+ }+ return null;+ }+ /**+ * Get all authority metadata keys+ */+ getAuthorityMetadataKeys() {+ return this.getKeys().filter((key) => {+ return this.isAuthorityMetadata(key);+ });+ }+ /**+ * set authority metadata entity to the platform cache+ * @param key - lookup key to fetch cache type AuthorityMetadataEntity+ * @param metadata - cache value to be set of type AuthorityMetadataEntity+ */+ setAuthorityMetadata(key, metadata) {+ this.setItem(key, metadata);+ }+ /**+ * fetch throttling entity from the platform cache+ * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity+ */+ getThrottlingCache(throttlingCacheKey) {+ const throttlingCache = this.getItem(throttlingCacheKey);+ if (throttlingCache && CacheHelpers_exports.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {+ return throttlingCache;+ }+ return null;+ }+ /**+ * set throttling entity to the platform cache+ * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity+ * @param throttlingCache - cache value to be set of type ThrottlingEntity+ */+ setThrottlingCache(throttlingCacheKey, throttlingCache) {+ this.setItem(throttlingCacheKey, throttlingCache);+ }+ /**+ * Removes the cache item from memory with the given key.+ * @param key - lookup key to remove a cache entity+ * @param inMemory - key value map of the cache+ */+ removeItem(key) {+ this.logger.tracePii(`Item key: ${key}`, "");+ let result = false;+ const cache = this.getCache();+ if (!!cache[key]) {+ delete cache[key];+ result = true;+ }+ if (result) {+ this.setCache(cache);+ this.emitChange();+ }+ return result;+ }+ /**+ * Remove account entity from the platform cache if it's outdated+ * @param accountKey - lookup key to fetch cache type AccountEntity+ */+ removeOutdatedAccount(accountKey) {+ this.removeItem(accountKey);+ }+ /**+ * Checks whether key is in cache.+ * @param key - look up key for a cache entity+ */+ containsKey(key) {+ return this.getKeys().includes(key);+ }+ /**+ * Gets all keys in window.+ */+ getKeys() {+ this.logger.trace("Retrieving all cache keys", "");+ const cache = this.getCache();+ return [...Object.keys(cache)];+ }+ /**+ * Clears all cache entries created by MSAL except authority metadata..+ */+ clear() {+ this.logger.trace("Clearing cache entries created by MSAL", "");+ const cacheKeys = this.getKeys();+ cacheKeys.forEach((key) => {+ if (this.isAuthorityMetadata(key)) {+ return;+ }+ this.removeItem(key);+ });+ this.emitChange();+ }+ /**+ * Initialize in memory cache from an exisiting cache vault+ * @param cache - blob formatted cache (JSON)+ */+ static generateInMemoryCache(cache) {+ return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache));+ }+ /**+ * retrieves the final JSON+ * @param inMemoryCache - itemised cache read from the JSON+ */+ static generateJsonCache(inMemoryCache) {+ return Serializer.serializeAllCache(inMemoryCache);+ }+ /**+ * Updates a credential's cache key if the current cache key is outdated+ */+ updateCredentialCacheKey(currentCacheKey, credential) {+ const updatedCacheKey = this.generateCredentialKey(credential);+ if (currentCacheKey !== updatedCacheKey) {+ const cacheItem = this.getItem(currentCacheKey);+ if (cacheItem) {+ this.removeItem(currentCacheKey);+ this.setItem(updatedCacheKey, cacheItem);+ this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`, "");+ return updatedCacheKey;+ } else {+ this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`, "");+ }+ }+ return currentCacheKey;+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/cache/TokenCache.mjs+var defaultSerializedCache, TokenCache;+var init_TokenCache = __esm({+ "node_modules/@azure/msal-node/dist/cache/TokenCache.mjs"() {+ "use strict";+ init_NodeStorage();+ init_index_node();+ init_Deserializer();+ init_Serializer();+ init_GuidGenerator();+ init_CryptoProvider();+ defaultSerializedCache = {+ Account: {},+ IdToken: {},+ AccessToken: {},+ RefreshToken: {},+ AppMetadata: {}+ };+ TokenCache = class {+ constructor(storage, logger2, cachePlugin) {+ this.cacheHasChanged = false;+ this.storage = storage;+ this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));+ if (cachePlugin) {+ this.persistence = cachePlugin;+ }+ this.logger = logger2;+ }+ /**+ * Set to true if cache state has changed since last time serialize or writeToPersistence was called+ */+ hasChanged() {+ return this.cacheHasChanged;+ }+ /**+ * Serializes in memory cache to JSON+ */+ serialize() {+ this.logger.trace("Serializing in-memory cache", "");+ let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());+ if (this.cacheSnapshot) {+ this.logger.trace("Reading cache snapshot from disk", "");+ finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);+ } else {+ this.logger.trace("No cache snapshot to merge", "");+ }+ this.cacheHasChanged = false;+ return JSON.stringify(finalState);+ }+ /**+ * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format+ * @param cache - blob formatted cache+ */+ deserialize(cache) {+ this.logger.trace("Deserializing JSON to in-memory cache", "");+ this.cacheSnapshot = cache;+ if (this.cacheSnapshot) {+ this.logger.trace("Reading cache snapshot from disk", "");+ const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));+ this.storage.setInMemoryCache(deserializedCache);+ } else {+ this.logger.trace("No cache snapshot to deserialize", "");+ }+ }+ /**+ * Fetches the cache key-value map+ */+ getKVStore() {+ return this.storage.getCache();+ }+ /**+ * Gets cache snapshot in CacheKVStore format+ */+ getCacheSnapshot() {+ const deserializedPersistentStorage = NodeStorage.generateInMemoryCache(this.cacheSnapshot);+ return this.storage.inMemoryCacheToCache(deserializedPersistentStorage);+ }+ /**+ * API that retrieves all accounts currently in cache to the user+ */+ async getAllAccounts(correlationId = new CryptoProvider().createNewGuid()) {+ this.logger.trace("getAllAccounts called", correlationId);+ let cacheContext;+ try {+ if (this.persistence) {+ cacheContext = new TokenCacheContext(this, false);+ await this.persistence.beforeCacheAccess(cacheContext);+ }+ return this.storage.getAllAccounts({}, correlationId);+ } finally {+ if (this.persistence && cacheContext) {+ await this.persistence.afterCacheAccess(cacheContext);+ }+ }+ }+ /**+ * Returns the signed in account matching homeAccountId.+ * (the account object is created at the time of successful login)+ * or null when no matching account is found+ * @param homeAccountId - unique identifier for an account (uid.utid)+ */+ async getAccountByHomeId(homeAccountId) {+ const allAccounts = await this.getAllAccounts();+ if (homeAccountId && allAccounts && allAccounts.length) {+ return allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null;+ } else {+ return null;+ }+ }+ /**+ * Returns the signed in account matching localAccountId.+ * (the account object is created at the time of successful login)+ * or null when no matching account is found+ * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)+ */+ async getAccountByLocalId(localAccountId) {+ const allAccounts = await this.getAllAccounts();+ if (localAccountId && allAccounts && allAccounts.length) {+ return allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null;+ } else {+ return null;+ }+ }+ /**+ * API to remove a specific account and the relevant data from cache+ * @param account - AccountInfo passed by the user+ */+ async removeAccount(account, correlationId) {+ this.logger.trace("removeAccount called", correlationId || "");+ let cacheContext;+ try {+ if (this.persistence) {+ cacheContext = new TokenCacheContext(this, true);+ await this.persistence.beforeCacheAccess(cacheContext);+ }+ this.storage.removeAccount(account, correlationId || new GuidGenerator().generateGuid());+ } finally {+ if (this.persistence && cacheContext) {+ await this.persistence.afterCacheAccess(cacheContext);+ }+ }+ }+ /**+ * Overwrites in-memory cache with persistent cache+ */+ async overwriteCache() {+ if (!this.persistence) {+ this.logger.info("No persistence layer specified, cache cannot be overwritten", "");+ return;+ }+ this.logger.info("Overwriting in-memory cache with persistent cache", "");+ this.storage.clear();+ const cacheContext = new TokenCacheContext(this, false);+ await this.persistence.beforeCacheAccess(cacheContext);+ const cacheSnapshot = this.getCacheSnapshot();+ this.storage.setCache(cacheSnapshot);+ await this.persistence.afterCacheAccess(cacheContext);+ }+ /**+ * Called when the cache has changed state.+ */+ handleChangeEvent() {+ this.cacheHasChanged = true;+ }+ /**+ * Merge in memory cache with the cache snapshot.+ * @param oldState - cache before changes+ * @param currentState - current cache state in the library+ */+ mergeState(oldState, currentState) {+ this.logger.trace("Merging in-memory cache with cache snapshot", "");+ const stateAfterRemoval = this.mergeRemovals(oldState, currentState);+ return this.mergeUpdates(stateAfterRemoval, currentState);+ }+ /**+ * Deep update of oldState based on newState values+ * @param oldState - cache before changes+ * @param newState - updated cache+ */+ mergeUpdates(oldState, newState) {+ Object.keys(newState).forEach((newKey) => {+ const newValue = newState[newKey];+ if (!oldState.hasOwnProperty(newKey)) {+ if (newValue !== null) {+ oldState[newKey] = newValue;+ }+ } else {+ const newValueNotNull = newValue !== null;+ const newValueIsObject = typeof newValue === "object";+ const newValueIsNotArray = !Array.isArray(newValue);+ const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && oldState[newKey] !== null;+ if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {+ this.mergeUpdates(oldState[newKey], newValue);+ } else {+ oldState[newKey] = newValue;+ }+ }+ });+ return oldState;+ }+ /**+ * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of+ * oldState that are not recognized, they are left untouched.+ * @param oldState - cache before changes+ * @param newState - updated cache+ */+ mergeRemovals(oldState, newState) {+ this.logger.trace("Remove updated entries in cache", "");+ const accounts = oldState.Account ? this.mergeRemovalsDict(oldState.Account, newState.Account) : oldState.Account;+ const accessTokens = oldState.AccessToken ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) : oldState.AccessToken;+ const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;+ const idTokens = oldState.IdToken ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) : oldState.IdToken;+ const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;+ return {+ ...oldState,+ Account: accounts,+ AccessToken: accessTokens,+ RefreshToken: refreshTokens,+ IdToken: idTokens,+ AppMetadata: appMetadata+ };+ }+ /**+ * Helper to merge new cache with the old one+ * @param oldState - cache before changes+ * @param newState - updated cache+ */+ mergeRemovalsDict(oldState, newState) {+ const finalState = { ...oldState };+ Object.keys(oldState).forEach((oldKey) => {+ if (!newState || !newState.hasOwnProperty(oldKey)) {+ delete finalState[oldKey];+ }+ });+ return finalState;+ }+ /**+ * Helper to overlay as a part of cache merge+ * @param passedInCache - cache read from the blob+ */+ overlayDefaults(passedInCache) {+ this.logger.trace("Overlaying input cache with the default cache", "");+ return {+ Account: {+ ...defaultSerializedCache.Account,+ ...passedInCache.Account+ },+ IdToken: {+ ...defaultSerializedCache.IdToken,+ ...passedInCache.IdToken+ },+ AccessToken: {+ ...defaultSerializedCache.AccessToken,+ ...passedInCache.AccessToken+ },+ RefreshToken: {+ ...defaultSerializedCache.RefreshToken,+ ...passedInCache.RefreshToken+ },+ AppMetadata: {+ ...defaultSerializedCache.AppMetadata,+ ...passedInCache.AppMetadata+ }+ };+ }+ };+ }+});++// node_modules/safe-buffer/index.js+var require_safe_buffer = __commonJS({+ "node_modules/safe-buffer/index.js"(exports, module) {+ var buffer = __require("buffer");+ var Buffer2 = buffer.Buffer;+ function copyProps(src, dst) {+ for (var key in src) {+ dst[key] = src[key];+ }+ }+ if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {+ module.exports = buffer;+ } else {+ copyProps(buffer, exports);+ exports.Buffer = SafeBuffer;+ }+ function SafeBuffer(arg, encodingOrOffset, length) {+ return Buffer2(arg, encodingOrOffset, length);+ }+ SafeBuffer.prototype = Object.create(Buffer2.prototype);+ copyProps(Buffer2, SafeBuffer);+ SafeBuffer.from = function(arg, encodingOrOffset, length) {+ if (typeof arg === "number") {+ throw new TypeError("Argument must not be a number");+ }+ return Buffer2(arg, encodingOrOffset, length);+ };+ SafeBuffer.alloc = function(size, fill, encoding) {+ if (typeof size !== "number") {+ throw new TypeError("Argument must be a number");+ }+ var buf = Buffer2(size);+ if (fill !== void 0) {+ if (typeof encoding === "string") {+ buf.fill(fill, encoding);+ } else {+ buf.fill(fill);+ }+ } else {+ buf.fill(0);+ }+ return buf;+ };+ SafeBuffer.allocUnsafe = function(size) {+ if (typeof size !== "number") {+ throw new TypeError("Argument must be a number");+ }+ return Buffer2(size);+ };+ SafeBuffer.allocUnsafeSlow = function(size) {+ if (typeof size !== "number") {+ throw new TypeError("Argument must be a number");+ }+ return buffer.SlowBuffer(size);+ };+ }+});++// node_modules/jws/lib/data-stream.js+var require_data_stream = __commonJS({+ "node_modules/jws/lib/data-stream.js"(exports, module) {+ var Buffer2 = require_safe_buffer().Buffer;+ var Stream = __require("stream");+ var util2 = __require("util");+ function DataStream(data) {+ this.buffer = null;+ this.writable = true;+ this.readable = true;+ if (!data) {+ this.buffer = Buffer2.alloc(0);+ return this;+ }+ if (typeof data.pipe === "function") {+ this.buffer = Buffer2.alloc(0);+ data.pipe(this);+ return this;+ }+ if (data.length || typeof data === "object") {+ this.buffer = data;+ this.writable = false;+ process.nextTick(function() {+ this.emit("end", data);+ this.readable = false;+ this.emit("close");+ }.bind(this));+ return this;+ }+ throw new TypeError("Unexpected data type (" + typeof data + ")");+ }+ util2.inherits(DataStream, Stream);+ DataStream.prototype.write = function write(data) {+ this.buffer = Buffer2.concat([this.buffer, Buffer2.from(data)]);+ this.emit("data", data);+ };+ DataStream.prototype.end = function end(data) {+ if (data)+ this.write(data);+ this.emit("end", data);+ this.emit("close");+ this.writable = false;+ this.readable = false;+ };+ module.exports = DataStream;+ }+});++// node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js+var require_param_bytes_for_alg = __commonJS({+ "node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js"(exports, module) {+ "use strict";+ function getParamSize(keySize) {+ var result = (keySize / 8 | 0) + (keySize % 8 === 0 ? 0 : 1);+ return result;+ }+ var paramBytesForAlg = {+ ES256: getParamSize(256),+ ES384: getParamSize(384),+ ES512: getParamSize(521)+ };+ function getParamBytesForAlg(alg) {+ var paramBytes = paramBytesForAlg[alg];+ if (paramBytes) {+ return paramBytes;+ }+ throw new Error('Unknown algorithm "' + alg + '"');+ }+ module.exports = getParamBytesForAlg;+ }+});++// node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js+var require_ecdsa_sig_formatter = __commonJS({+ "node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js"(exports, module) {+ "use strict";+ var Buffer2 = require_safe_buffer().Buffer;+ var getParamBytesForAlg = require_param_bytes_for_alg();+ var MAX_OCTET = 128;+ var CLASS_UNIVERSAL = 0;+ var PRIMITIVE_BIT = 32;+ var TAG_SEQ = 16;+ var TAG_INT = 2;+ var ENCODED_TAG_SEQ = TAG_SEQ | PRIMITIVE_BIT | CLASS_UNIVERSAL << 6;+ var ENCODED_TAG_INT = TAG_INT | CLASS_UNIVERSAL << 6;+ function base64Url(base642) {+ return base642.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");+ }+ function signatureAsBuffer(signature) {+ if (Buffer2.isBuffer(signature)) {+ return signature;+ } else if ("string" === typeof signature) {+ return Buffer2.from(signature, "base64");+ }+ throw new TypeError("ECDSA signature must be a Base64 string or a Buffer");+ }+ function derToJose(signature, alg) {+ signature = signatureAsBuffer(signature);+ var paramBytes = getParamBytesForAlg(alg);+ var maxEncodedParamLength = paramBytes + 1;+ var inputLength = signature.length;+ var offset = 0;+ if (signature[offset++] !== ENCODED_TAG_SEQ) {+ throw new Error('Could not find expected "seq"');+ }+ var seqLength = signature[offset++];+ if (seqLength === (MAX_OCTET | 1)) {+ seqLength = signature[offset++];+ }+ if (inputLength - offset < seqLength) {+ throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining');+ }+ if (signature[offset++] !== ENCODED_TAG_INT) {+ throw new Error('Could not find expected "int" for "r"');+ }+ var rLength = signature[offset++];+ if (inputLength - offset - 2 < rLength) {+ throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available');+ }+ if (maxEncodedParamLength < rLength) {+ throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable');+ }+ var rOffset = offset;+ offset += rLength;+ if (signature[offset++] !== ENCODED_TAG_INT) {+ throw new Error('Could not find expected "int" for "s"');+ }+ var sLength = signature[offset++];+ if (inputLength - offset !== sLength) {+ throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"');+ }+ if (maxEncodedParamLength < sLength) {+ throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable');+ }+ var sOffset = offset;+ offset += sLength;+ if (offset !== inputLength) {+ throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain');+ }+ var rPadding = paramBytes - rLength, sPadding = paramBytes - sLength;+ var dst = Buffer2.allocUnsafe(rPadding + rLength + sPadding + sLength);+ for (offset = 0; offset < rPadding; ++offset) {+ dst[offset] = 0;+ }+ signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength);+ offset = paramBytes;+ for (var o = offset; offset < o + sPadding; ++offset) {+ dst[offset] = 0;+ }+ signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength);+ dst = dst.toString("base64");+ dst = base64Url(dst);+ return dst;+ }+ function countPadding(buf, start, stop) {+ var padding = 0;+ while (start + padding < stop && buf[start + padding] === 0) {+ ++padding;+ }+ var needsSign = buf[start + padding] >= MAX_OCTET;+ if (needsSign) {+ --padding;+ }+ return padding;+ }+ function joseToDer(signature, alg) {+ signature = signatureAsBuffer(signature);+ var paramBytes = getParamBytesForAlg(alg);+ var signatureBytes = signature.length;+ if (signatureBytes !== paramBytes * 2) {+ throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"');+ }+ var rPadding = countPadding(signature, 0, paramBytes);+ var sPadding = countPadding(signature, paramBytes, signature.length);+ var rLength = paramBytes - rPadding;+ var sLength = paramBytes - sPadding;+ var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength;+ var shortLength = rsBytes < MAX_OCTET;+ var dst = Buffer2.allocUnsafe((shortLength ? 2 : 3) + rsBytes);+ var offset = 0;+ dst[offset++] = ENCODED_TAG_SEQ;+ if (shortLength) {+ dst[offset++] = rsBytes;+ } else {+ dst[offset++] = MAX_OCTET | 1;+ dst[offset++] = rsBytes & 255;+ }+ dst[offset++] = ENCODED_TAG_INT;+ dst[offset++] = rLength;+ if (rPadding < 0) {+ dst[offset++] = 0;+ offset += signature.copy(dst, offset, 0, paramBytes);+ } else {+ offset += signature.copy(dst, offset, rPadding, paramBytes);+ }+ dst[offset++] = ENCODED_TAG_INT;+ dst[offset++] = sLength;+ if (sPadding < 0) {+ dst[offset++] = 0;+ signature.copy(dst, offset, paramBytes);+ } else {+ signature.copy(dst, offset, paramBytes + sPadding);+ }+ return dst;+ }+ module.exports = {+ derToJose,+ joseToDer+ };+ }+});++// node_modules/buffer-equal-constant-time/index.js+var require_buffer_equal_constant_time = __commonJS({+ "node_modules/buffer-equal-constant-time/index.js"(exports, module) {+ "use strict";+ var Buffer2 = __require("buffer").Buffer;+ var SlowBuffer = __require("buffer").SlowBuffer;+ module.exports = bufferEq;+ function bufferEq(a, b) {+ if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {+ return false;+ }+ if (a.length !== b.length) {+ return false;+ }+ var c = 0;+ for (var i = 0; i < a.length; i++) {+ c |= a[i] ^ b[i];+ }+ return c === 0;+ }+ bufferEq.install = function() {+ Buffer2.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {+ return bufferEq(this, that);+ };+ };+ var origBufEqual = Buffer2.prototype.equal;+ var origSlowBufEqual = SlowBuffer.prototype.equal;+ bufferEq.restore = function() {+ Buffer2.prototype.equal = origBufEqual;+ SlowBuffer.prototype.equal = origSlowBufEqual;+ };+ }+});++// node_modules/jwa/index.js+var require_jwa = __commonJS({+ "node_modules/jwa/index.js"(exports, module) {+ var Buffer2 = require_safe_buffer().Buffer;+ var crypto3 = __require("crypto");+ var formatEcdsa = require_ecdsa_sig_formatter();+ var util2 = __require("util");+ var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".';+ var MSG_INVALID_SECRET = "secret must be a string or buffer";+ var MSG_INVALID_VERIFIER_KEY = "key must be a string or a buffer";+ var MSG_INVALID_SIGNER_KEY = "key must be a string, a buffer or an object";+ var supportsKeyObjects = typeof crypto3.createPublicKey === "function";+ if (supportsKeyObjects) {+ MSG_INVALID_VERIFIER_KEY += " or a KeyObject";+ MSG_INVALID_SECRET += "or a KeyObject";+ }+ function checkIsPublicKey(key) {+ if (Buffer2.isBuffer(key)) {+ return;+ }+ if (typeof key === "string") {+ return;+ }+ if (!supportsKeyObjects) {+ throw typeError(MSG_INVALID_VERIFIER_KEY);+ }+ if (typeof key !== "object") {+ throw typeError(MSG_INVALID_VERIFIER_KEY);+ }+ if (typeof key.type !== "string") {+ throw typeError(MSG_INVALID_VERIFIER_KEY);+ }+ if (typeof key.asymmetricKeyType !== "string") {+ throw typeError(MSG_INVALID_VERIFIER_KEY);+ }+ if (typeof key.export !== "function") {+ throw typeError(MSG_INVALID_VERIFIER_KEY);+ }+ }+ function checkIsPrivateKey(key) {+ if (Buffer2.isBuffer(key)) {+ return;+ }+ if (typeof key === "string") {+ return;+ }+ if (typeof key === "object") {+ return;+ }+ throw typeError(MSG_INVALID_SIGNER_KEY);+ }+ function checkIsSecretKey(key) {+ if (Buffer2.isBuffer(key)) {+ return;+ }+ if (typeof key === "string") {+ return key;+ }+ if (!supportsKeyObjects) {+ throw typeError(MSG_INVALID_SECRET);+ }+ if (typeof key !== "object") {+ throw typeError(MSG_INVALID_SECRET);+ }+ if (key.type !== "secret") {+ throw typeError(MSG_INVALID_SECRET);+ }+ if (typeof key.export !== "function") {+ throw typeError(MSG_INVALID_SECRET);+ }+ }+ function fromBase64(base642) {+ return base642.replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");+ }+ function toBase64(base64url2) {+ base64url2 = base64url2.toString();+ var padding = 4 - base64url2.length % 4;+ if (padding !== 4) {+ for (var i = 0; i < padding; ++i) {+ base64url2 += "=";+ }+ }+ return base64url2.replace(/\-/g, "+").replace(/_/g, "/");+ }+ function typeError(template) {+ var args = [].slice.call(arguments, 1);+ var errMsg = util2.format.bind(util2, template).apply(null, args);+ return new TypeError(errMsg);+ }+ function bufferOrString(obj) {+ return Buffer2.isBuffer(obj) || typeof obj === "string";+ }+ function normalizeInput(thing) {+ if (!bufferOrString(thing))+ thing = JSON.stringify(thing);+ return thing;+ }+ function createHmacSigner(bits) {+ return function sign(thing, secret) {+ checkIsSecretKey(secret);+ thing = normalizeInput(thing);+ var hmac = crypto3.createHmac("sha" + bits, secret);+ var sig = (hmac.update(thing), hmac.digest("base64"));+ return fromBase64(sig);+ };+ }+ var bufferEqual;+ var timingSafeEqual = "timingSafeEqual" in crypto3 ? function timingSafeEqual2(a, b) {+ if (a.byteLength !== b.byteLength) {+ return false;+ }+ return crypto3.timingSafeEqual(a, b);+ } : function timingSafeEqual2(a, b) {+ if (!bufferEqual) {+ bufferEqual = require_buffer_equal_constant_time();+ }+ return bufferEqual(a, b);+ };+ function createHmacVerifier(bits) {+ return function verify(thing, signature, secret) {+ var computedSig = createHmacSigner(bits)(thing, secret);+ return timingSafeEqual(Buffer2.from(signature), Buffer2.from(computedSig));+ };+ }+ function createKeySigner(bits) {+ return function sign(thing, privateKey) {+ checkIsPrivateKey(privateKey);+ thing = normalizeInput(thing);+ var signer = crypto3.createSign("RSA-SHA" + bits);+ var sig = (signer.update(thing), signer.sign(privateKey, "base64"));+ return fromBase64(sig);+ };+ }+ function createKeyVerifier(bits) {+ return function verify(thing, signature, publicKey) {+ checkIsPublicKey(publicKey);+ thing = normalizeInput(thing);+ signature = toBase64(signature);+ var verifier = crypto3.createVerify("RSA-SHA" + bits);+ verifier.update(thing);+ return verifier.verify(publicKey, signature, "base64");+ };+ }+ function createPSSKeySigner(bits) {+ return function sign(thing, privateKey) {+ checkIsPrivateKey(privateKey);+ thing = normalizeInput(thing);+ var signer = crypto3.createSign("RSA-SHA" + bits);+ var sig = (signer.update(thing), signer.sign({+ key: privateKey,+ padding: crypto3.constants.RSA_PKCS1_PSS_PADDING,+ saltLength: crypto3.constants.RSA_PSS_SALTLEN_DIGEST+ }, "base64"));+ return fromBase64(sig);+ };+ }+ function createPSSKeyVerifier(bits) {+ return function verify(thing, signature, publicKey) {+ checkIsPublicKey(publicKey);+ thing = normalizeInput(thing);+ signature = toBase64(signature);+ var verifier = crypto3.createVerify("RSA-SHA" + bits);+ verifier.update(thing);+ return verifier.verify({+ key: publicKey,+ padding: crypto3.constants.RSA_PKCS1_PSS_PADDING,+ saltLength: crypto3.constants.RSA_PSS_SALTLEN_DIGEST+ }, signature, "base64");+ };+ }+ function createECDSASigner(bits) {+ var inner = createKeySigner(bits);+ return function sign() {+ var signature = inner.apply(null, arguments);+ signature = formatEcdsa.derToJose(signature, "ES" + bits);+ return signature;+ };+ }+ function createECDSAVerifer(bits) {+ var inner = createKeyVerifier(bits);+ return function verify(thing, signature, publicKey) {+ signature = formatEcdsa.joseToDer(signature, "ES" + bits).toString("base64");+ var result = inner(thing, signature, publicKey);+ return result;+ };+ }+ function createNoneSigner() {+ return function sign() {+ return "";+ };+ }+ function createNoneVerifier() {+ return function verify(thing, signature) {+ return signature === "";+ };+ }+ module.exports = function jwa(algorithm) {+ var signerFactories = {+ hs: createHmacSigner,+ rs: createKeySigner,+ ps: createPSSKeySigner,+ es: createECDSASigner,+ none: createNoneSigner+ };+ var verifierFactories = {+ hs: createHmacVerifier,+ rs: createKeyVerifier,+ ps: createPSSKeyVerifier,+ es: createECDSAVerifer,+ none: createNoneVerifier+ };+ var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);+ if (!match)+ throw typeError(MSG_INVALID_ALGORITHM, algorithm);+ var algo = (match[1] || match[3]).toLowerCase();+ var bits = match[2];+ return {+ sign: signerFactories[algo](bits),+ verify: verifierFactories[algo](bits)+ };+ };+ }+});++// node_modules/jws/lib/tostring.js+var require_tostring = __commonJS({+ "node_modules/jws/lib/tostring.js"(exports, module) {+ var Buffer2 = __require("buffer").Buffer;+ module.exports = function toString(obj) {+ if (typeof obj === "string")+ return obj;+ if (typeof obj === "number" || Buffer2.isBuffer(obj))+ return obj.toString();+ return JSON.stringify(obj);+ };+ }+});++// node_modules/jws/lib/sign-stream.js+var require_sign_stream = __commonJS({+ "node_modules/jws/lib/sign-stream.js"(exports, module) {+ var Buffer2 = require_safe_buffer().Buffer;+ var DataStream = require_data_stream();+ var jwa = require_jwa();+ var Stream = __require("stream");+ var toString = require_tostring();+ var util2 = __require("util");+ function base64url2(string3, encoding) {+ return Buffer2.from(string3, encoding).toString("base64").replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");+ }+ function jwsSecuredInput(header, payload, encoding) {+ encoding = encoding || "utf8";+ var encodedHeader = base64url2(toString(header), "binary");+ var encodedPayload = base64url2(toString(payload), encoding);+ return util2.format("%s.%s", encodedHeader, encodedPayload);+ }+ function jwsSign(opts) {+ var header = opts.header;+ var payload = opts.payload;+ var secretOrKey = opts.secret || opts.privateKey;+ var encoding = opts.encoding;+ var algo = jwa(header.alg);+ var securedInput = jwsSecuredInput(header, payload, encoding);+ var signature = algo.sign(securedInput, secretOrKey);+ return util2.format("%s.%s", securedInput, signature);+ }+ function SignStream(opts) {+ var secret = opts.secret;+ secret = secret == null ? opts.privateKey : secret;+ secret = secret == null ? opts.key : secret;+ if (/^hs/i.test(opts.header.alg) === true && secret == null) {+ throw new TypeError("secret must be a string or buffer or a KeyObject");+ }+ var secretStream = new DataStream(secret);+ this.readable = true;+ this.header = opts.header;+ this.encoding = opts.encoding;+ this.secret = this.privateKey = this.key = secretStream;+ this.payload = new DataStream(opts.payload);+ this.secret.once("close", function() {+ if (!this.payload.writable && this.readable)+ this.sign();+ }.bind(this));+ this.payload.once("close", function() {+ if (!this.secret.writable && this.readable)+ this.sign();+ }.bind(this));+ }+ util2.inherits(SignStream, Stream);+ SignStream.prototype.sign = function sign() {+ try {+ var signature = jwsSign({+ header: this.header,+ payload: this.payload.buffer,+ secret: this.secret.buffer,+ encoding: this.encoding+ });+ this.emit("done", signature);+ this.emit("data", signature);+ this.emit("end");+ this.readable = false;+ return signature;+ } catch (e) {+ this.readable = false;+ this.emit("error", e);+ this.emit("close");+ }+ };+ SignStream.sign = jwsSign;+ module.exports = SignStream;+ }+});++// node_modules/jws/lib/verify-stream.js+var require_verify_stream = __commonJS({+ "node_modules/jws/lib/verify-stream.js"(exports, module) {+ var Buffer2 = require_safe_buffer().Buffer;+ var DataStream = require_data_stream();+ var jwa = require_jwa();+ var Stream = __require("stream");+ var toString = require_tostring();+ var util2 = __require("util");+ var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;+ function isObject2(thing) {+ return Object.prototype.toString.call(thing) === "[object Object]";+ }+ function safeJsonParse(thing) {+ if (isObject2(thing))+ return thing;+ try {+ return JSON.parse(thing);+ } catch (e) {+ return void 0;+ }+ }+ function headerFromJWS(jwsSig) {+ var encodedHeader = jwsSig.split(".", 1)[0];+ return safeJsonParse(Buffer2.from(encodedHeader, "base64").toString("binary"));+ }+ function securedInputFromJWS(jwsSig) {+ return jwsSig.split(".", 2).join(".");+ }+ function signatureFromJWS(jwsSig) {+ return jwsSig.split(".")[2];+ }+ function payloadFromJWS(jwsSig, encoding) {+ encoding = encoding || "utf8";+ var payload = jwsSig.split(".")[1];+ return Buffer2.from(payload, "base64").toString(encoding);+ }+ function isValidJws(string3) {+ return JWS_REGEX.test(string3) && !!headerFromJWS(string3);+ }+ function jwsVerify(jwsSig, algorithm, secretOrKey) {+ if (!algorithm) {+ var err = new Error("Missing algorithm parameter for jws.verify");+ err.code = "MISSING_ALGORITHM";+ throw err;+ }+ jwsSig = toString(jwsSig);+ var signature = signatureFromJWS(jwsSig);+ var securedInput = securedInputFromJWS(jwsSig);+ var algo = jwa(algorithm);+ return algo.verify(securedInput, signature, secretOrKey);+ }+ function jwsDecode(jwsSig, opts) {+ opts = opts || {};+ jwsSig = toString(jwsSig);+ if (!isValidJws(jwsSig))+ return null;+ var header = headerFromJWS(jwsSig);+ if (!header)+ return null;+ var payload = payloadFromJWS(jwsSig);+ if (header.typ === "JWT" || opts.json)+ payload = JSON.parse(payload, opts.encoding);+ return {+ header,+ payload,+ signature: signatureFromJWS(jwsSig)+ };+ }+ function VerifyStream(opts) {+ opts = opts || {};+ var secretOrKey = opts.secret;+ secretOrKey = secretOrKey == null ? opts.publicKey : secretOrKey;+ secretOrKey = secretOrKey == null ? opts.key : secretOrKey;+ if (/^hs/i.test(opts.algorithm) === true && secretOrKey == null) {+ throw new TypeError("secret must be a string or buffer or a KeyObject");+ }+ var secretStream = new DataStream(secretOrKey);+ this.readable = true;+ this.algorithm = opts.algorithm;+ this.encoding = opts.encoding;+ this.secret = this.publicKey = this.key = secretStream;+ this.signature = new DataStream(opts.signature);+ this.secret.once("close", function() {+ if (!this.signature.writable && this.readable)+ this.verify();+ }.bind(this));+ this.signature.once("close", function() {+ if (!this.secret.writable && this.readable)+ this.verify();+ }.bind(this));+ }+ util2.inherits(VerifyStream, Stream);+ VerifyStream.prototype.verify = function verify() {+ try {+ var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer);+ var obj = jwsDecode(this.signature.buffer, this.encoding);+ this.emit("done", valid, obj);+ this.emit("data", valid);+ this.emit("end");+ this.readable = false;+ return valid;+ } catch (e) {+ this.readable = false;+ this.emit("error", e);+ this.emit("close");+ }+ };+ VerifyStream.decode = jwsDecode;+ VerifyStream.isValid = isValidJws;+ VerifyStream.verify = jwsVerify;+ module.exports = VerifyStream;+ }+});++// node_modules/jws/index.js+var require_jws = __commonJS({+ "node_modules/jws/index.js"(exports) {+ var SignStream = require_sign_stream();+ var VerifyStream = require_verify_stream();+ var ALGORITHMS = [+ "HS256",+ "HS384",+ "HS512",+ "RS256",+ "RS384",+ "RS512",+ "PS256",+ "PS384",+ "PS512",+ "ES256",+ "ES384",+ "ES512"+ ];+ exports.ALGORITHMS = ALGORITHMS;+ exports.sign = SignStream.sign;+ exports.verify = VerifyStream.verify;+ exports.decode = VerifyStream.decode;+ exports.isValid = VerifyStream.isValid;+ exports.createSign = function createSign(opts) {+ return new SignStream(opts);+ };+ exports.createVerify = function createVerify(opts) {+ return new VerifyStream(opts);+ };+ }+});++// node_modules/jsonwebtoken/decode.js+var require_decode = __commonJS({+ "node_modules/jsonwebtoken/decode.js"(exports, module) {+ var jws = require_jws();+ module.exports = function(jwt2, options) {+ options = options || {};+ var decoded = jws.decode(jwt2, options);+ if (!decoded) {+ return null;+ }+ var payload = decoded.payload;+ if (typeof payload === "string") {+ try {+ var obj = JSON.parse(payload);+ if (obj !== null && typeof obj === "object") {+ payload = obj;+ }+ } catch (e) {+ }+ }+ if (options.complete === true) {+ return {+ header: decoded.header,+ payload,+ signature: decoded.signature+ };+ }+ return payload;+ };+ }+});++// node_modules/jsonwebtoken/lib/JsonWebTokenError.js+var require_JsonWebTokenError = __commonJS({+ "node_modules/jsonwebtoken/lib/JsonWebTokenError.js"(exports, module) {+ var JsonWebTokenError = function(message, error2) {+ Error.call(this, message);+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, this.constructor);+ }+ this.name = "JsonWebTokenError";+ this.message = message;+ if (error2) this.inner = error2;+ };+ JsonWebTokenError.prototype = Object.create(Error.prototype);+ JsonWebTokenError.prototype.constructor = JsonWebTokenError;+ module.exports = JsonWebTokenError;+ }+});++// node_modules/jsonwebtoken/lib/NotBeforeError.js+var require_NotBeforeError = __commonJS({+ "node_modules/jsonwebtoken/lib/NotBeforeError.js"(exports, module) {+ var JsonWebTokenError = require_JsonWebTokenError();+ var NotBeforeError = function(message, date3) {+ JsonWebTokenError.call(this, message);+ this.name = "NotBeforeError";+ this.date = date3;+ };+ NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);+ NotBeforeError.prototype.constructor = NotBeforeError;+ module.exports = NotBeforeError;+ }+});++// node_modules/jsonwebtoken/lib/TokenExpiredError.js+var require_TokenExpiredError = __commonJS({+ "node_modules/jsonwebtoken/lib/TokenExpiredError.js"(exports, module) {+ var JsonWebTokenError = require_JsonWebTokenError();+ var TokenExpiredError = function(message, expiredAt) {+ JsonWebTokenError.call(this, message);+ this.name = "TokenExpiredError";+ this.expiredAt = expiredAt;+ };+ TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);+ TokenExpiredError.prototype.constructor = TokenExpiredError;+ module.exports = TokenExpiredError;+ }+});++// node_modules/ms/index.js+var require_ms = __commonJS({+ "node_modules/ms/index.js"(exports, module) {+ var s = 1e3;+ var m = s * 60;+ var h = m * 60;+ var d = h * 24;+ var w = d * 7;+ var y = d * 365.25;+ module.exports = function(val, options) {+ options = options || {};+ var type = typeof val;+ if (type === "string" && val.length > 0) {+ return parse3(val);+ } else if (type === "number" && isFinite(val)) {+ return options.long ? fmtLong(val) : fmtShort(val);+ }+ throw new Error(+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)+ );+ };+ function parse3(str) {+ str = String(str);+ if (str.length > 100) {+ return;+ }+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(+ str+ );+ if (!match) {+ return;+ }+ var n = parseFloat(match[1]);+ var type = (match[2] || "ms").toLowerCase();+ switch (type) {+ case "years":+ case "year":+ case "yrs":+ case "yr":+ case "y":+ return n * y;+ case "weeks":+ case "week":+ case "w":+ return n * w;+ case "days":+ case "day":+ case "d":+ return n * d;+ case "hours":+ case "hour":+ case "hrs":+ case "hr":+ case "h":+ return n * h;+ case "minutes":+ case "minute":+ case "mins":+ case "min":+ case "m":+ return n * m;+ case "seconds":+ case "second":+ case "secs":+ case "sec":+ case "s":+ return n * s;+ case "milliseconds":+ case "millisecond":+ case "msecs":+ case "msec":+ case "ms":+ return n;+ default:+ return void 0;+ }+ }+ function fmtShort(ms) {+ var msAbs = Math.abs(ms);+ if (msAbs >= d) {+ return Math.round(ms / d) + "d";+ }+ if (msAbs >= h) {+ return Math.round(ms / h) + "h";+ }+ if (msAbs >= m) {+ return Math.round(ms / m) + "m";+ }+ if (msAbs >= s) {+ return Math.round(ms / s) + "s";+ }+ return ms + "ms";+ }+ function fmtLong(ms) {+ var msAbs = Math.abs(ms);+ if (msAbs >= d) {+ return plural(ms, msAbs, d, "day");+ }+ if (msAbs >= h) {+ return plural(ms, msAbs, h, "hour");+ }+ if (msAbs >= m) {+ return plural(ms, msAbs, m, "minute");+ }+ if (msAbs >= s) {+ return plural(ms, msAbs, s, "second");+ }+ return ms + " ms";+ }+ function plural(ms, msAbs, n, name3) {+ var isPlural = msAbs >= n * 1.5;+ return Math.round(ms / n) + " " + name3 + (isPlural ? "s" : "");+ }+ }+});++// node_modules/jsonwebtoken/lib/timespan.js+var require_timespan = __commonJS({+ "node_modules/jsonwebtoken/lib/timespan.js"(exports, module) {+ var ms = require_ms();+ module.exports = function(time3, iat) {+ var timestamp = iat || Math.floor(Date.now() / 1e3);+ if (typeof time3 === "string") {+ var milliseconds = ms(time3);+ if (typeof milliseconds === "undefined") {+ return;+ }+ return Math.floor(timestamp + milliseconds / 1e3);+ } else if (typeof time3 === "number") {+ return timestamp + time3;+ } else {+ return;+ }+ };+ }+});++// node_modules/semver/internal/constants.js+var require_constants = __commonJS({+ "node_modules/semver/internal/constants.js"(exports, module) {+ "use strict";+ var SEMVER_SPEC_VERSION = "2.0.0";+ var MAX_LENGTH = 256;+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */+ 9007199254740991;+ var MAX_SAFE_COMPONENT_LENGTH = 16;+ var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;+ var RELEASE_TYPES = [+ "major",+ "premajor",+ "minor",+ "preminor",+ "patch",+ "prepatch",+ "prerelease"+ ];+ module.exports = {+ MAX_LENGTH,+ MAX_SAFE_COMPONENT_LENGTH,+ MAX_SAFE_BUILD_LENGTH,+ MAX_SAFE_INTEGER,+ RELEASE_TYPES,+ SEMVER_SPEC_VERSION,+ FLAG_INCLUDE_PRERELEASE: 1,+ FLAG_LOOSE: 2+ };+ }+});++// node_modules/semver/internal/debug.js+var require_debug = __commonJS({+ "node_modules/semver/internal/debug.js"(exports, module) {+ "use strict";+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {+ };+ module.exports = debug;+ }+});++// node_modules/semver/internal/re.js+var require_re = __commonJS({+ "node_modules/semver/internal/re.js"(exports, module) {+ "use strict";+ var {+ MAX_SAFE_COMPONENT_LENGTH,+ MAX_SAFE_BUILD_LENGTH,+ MAX_LENGTH+ } = require_constants();+ var debug = require_debug();+ exports = module.exports = {};+ var re = exports.re = [];+ var safeRe = exports.safeRe = [];+ var src = exports.src = [];+ var safeSrc = exports.safeSrc = [];+ var t = exports.t = {};+ var R = 0;+ var LETTERDASHNUMBER = "[a-zA-Z0-9-]";+ var safeRegexReplacements = [+ ["\\s", 1],+ ["\\d", MAX_LENGTH],+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]+ ];+ var makeSafeRegex = (value) => {+ for (const [token, max] of safeRegexReplacements) {+ value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);+ }+ return value;+ };+ var createToken = (name3, value, isGlobal) => {+ const safe = makeSafeRegex(value);+ const index = R++;+ debug(name3, index, value);+ t[name3] = index;+ src[index] = value;+ safeSrc[index] = safe;+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);+ safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);+ };+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");+ createToken("NUMERICIDENTIFIERLOOSE", "\\d+");+ createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);+ createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);+ createToken("GTLT", "((?:<|>)?=?)");+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);+ createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);+ createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);+ createToken("COERCERTL", src[t.COERCE], true);+ createToken("COERCERTLFULL", src[t.COERCEFULL], true);+ createToken("LONETILDE", "(?:~>?)");+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);+ exports.tildeTrimReplace = "$1~";+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("LONECARET", "(?:\\^)");+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);+ exports.caretTrimReplace = "$1^";+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);+ exports.comparatorTrimReplace = "$1$2$3";+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);+ createToken("STAR", "(<|>)?=?\\s*\\*");+ createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");+ createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");+ }+});++// node_modules/semver/internal/parse-options.js+var require_parse_options = __commonJS({+ "node_modules/semver/internal/parse-options.js"(exports, module) {+ "use strict";+ var looseOption = Object.freeze({ loose: true });+ var emptyOpts = Object.freeze({});+ var parseOptions = (options) => {+ if (!options) {+ return emptyOpts;+ }+ if (typeof options !== "object") {+ return looseOption;+ }+ return options;+ };+ module.exports = parseOptions;+ }+});++// node_modules/semver/internal/identifiers.js+var require_identifiers = __commonJS({+ "node_modules/semver/internal/identifiers.js"(exports, module) {+ "use strict";+ var numeric = /^[0-9]+$/;+ var compareIdentifiers = (a, b) => {+ if (typeof a === "number" && typeof b === "number") {+ return a === b ? 0 : a < b ? -1 : 1;+ }+ const anum = numeric.test(a);+ const bnum = numeric.test(b);+ if (anum && bnum) {+ a = +a;+ b = +b;+ }+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;+ };+ var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);+ module.exports = {+ compareIdentifiers,+ rcompareIdentifiers+ };+ }+});++// node_modules/semver/classes/semver.js+var require_semver = __commonJS({+ "node_modules/semver/classes/semver.js"(exports, module) {+ "use strict";+ var debug = require_debug();+ var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();+ var { safeRe: re, t } = require_re();+ var parseOptions = require_parse_options();+ var { compareIdentifiers } = require_identifiers();+ var isPrereleaseIdentifier = (prerelease, identifier) => {+ const identifiers = identifier.split(".");+ if (identifiers.length > prerelease.length) {+ return false;+ }+ for (let i = 0; i < identifiers.length; i++) {+ if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {+ return false;+ }+ }+ return true;+ };+ var SemVer = class _SemVer {+ constructor(version4, options) {+ options = parseOptions(options);+ if (version4 instanceof _SemVer) {+ if (version4.loose === !!options.loose && version4.includePrerelease === !!options.includePrerelease) {+ return version4;+ } else {+ version4 = version4.version;+ }+ } else if (typeof version4 !== "string") {+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version4}".`);+ }+ if (version4.length > MAX_LENGTH) {+ throw new TypeError(+ `version is longer than ${MAX_LENGTH} characters`+ );+ }+ debug("SemVer", version4, options);+ this.options = options;+ this.loose = !!options.loose;+ this.includePrerelease = !!options.includePrerelease;+ const m = version4.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);+ if (!m) {+ throw new TypeError(`Invalid Version: ${version4}`);+ }+ this.raw = version4;+ this.major = +m[1];+ this.minor = +m[2];+ this.patch = +m[3];+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {+ throw new TypeError("Invalid major version");+ }+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {+ throw new TypeError("Invalid minor version");+ }+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {+ throw new TypeError("Invalid patch version");+ }+ if (!m[4]) {+ this.prerelease = [];+ } else {+ this.prerelease = m[4].split(".").map((id) => {+ if (/^[0-9]+$/.test(id)) {+ const num = +id;+ if (num >= 0 && num < MAX_SAFE_INTEGER) {+ return num;+ }+ }+ return id;+ });+ }+ this.build = m[5] ? m[5].split(".") : [];+ this.format();+ }+ format() {+ this.version = `${this.major}.${this.minor}.${this.patch}`;+ if (this.prerelease.length) {+ this.version += `-${this.prerelease.join(".")}`;+ }+ return this.version;+ }+ toString() {+ return this.version;+ }+ compare(other) {+ debug("SemVer.compare", this.version, this.options, other);+ if (!(other instanceof _SemVer)) {+ if (typeof other === "string" && other === this.version) {+ return 0;+ }+ other = new _SemVer(other, this.options);+ }+ if (other.version === this.version) {+ return 0;+ }+ return this.compareMain(other) || this.comparePre(other);+ }+ compareMain(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ if (this.major < other.major) {+ return -1;+ }+ if (this.major > other.major) {+ return 1;+ }+ if (this.minor < other.minor) {+ return -1;+ }+ if (this.minor > other.minor) {+ return 1;+ }+ if (this.patch < other.patch) {+ return -1;+ }+ if (this.patch > other.patch) {+ return 1;+ }+ return 0;+ }+ comparePre(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ if (this.prerelease.length && !other.prerelease.length) {+ return -1;+ } else if (!this.prerelease.length && other.prerelease.length) {+ return 1;+ } else if (!this.prerelease.length && !other.prerelease.length) {+ return 0;+ }+ let i = 0;+ do {+ const a = this.prerelease[i];+ const b = other.prerelease[i];+ debug("prerelease compare", i, a, b);+ if (a === void 0 && b === void 0) {+ return 0;+ } else if (b === void 0) {+ return 1;+ } else if (a === void 0) {+ return -1;+ } else if (a === b) {+ continue;+ } else {+ return compareIdentifiers(a, b);+ }+ } while (++i);+ }+ compareBuild(other) {+ if (!(other instanceof _SemVer)) {+ other = new _SemVer(other, this.options);+ }+ let i = 0;+ do {+ const a = this.build[i];+ const b = other.build[i];+ debug("build compare", i, a, b);+ if (a === void 0 && b === void 0) {+ return 0;+ } else if (b === void 0) {+ return 1;+ } else if (a === void 0) {+ return -1;+ } else if (a === b) {+ continue;+ } else {+ return compareIdentifiers(a, b);+ }+ } while (++i);+ }+ // preminor will bump the version up to the next minor release, and immediately+ // down to pre-release. premajor and prepatch work the same way.+ inc(release, identifier, identifierBase) {+ if (release.startsWith("pre")) {+ if (!identifier && identifierBase === false) {+ throw new Error("invalid increment argument: identifier is empty");+ }+ if (identifier) {+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);+ if (!match || match[1] !== identifier) {+ throw new Error(`invalid identifier: ${identifier}`);+ }+ }+ }+ switch (release) {+ case "premajor":+ this.prerelease.length = 0;+ this.patch = 0;+ this.minor = 0;+ this.major++;+ this.inc("pre", identifier, identifierBase);+ break;+ case "preminor":+ this.prerelease.length = 0;+ this.patch = 0;+ this.minor++;+ this.inc("pre", identifier, identifierBase);+ break;+ case "prepatch":+ this.prerelease.length = 0;+ this.inc("patch", identifier, identifierBase);+ this.inc("pre", identifier, identifierBase);+ break;+ // If the input is a non-prerelease version, this acts the same as+ // prepatch.+ case "prerelease":+ if (this.prerelease.length === 0) {+ this.inc("patch", identifier, identifierBase);+ }+ this.inc("pre", identifier, identifierBase);+ break;+ case "release":+ if (this.prerelease.length === 0) {+ throw new Error(`version ${this.raw} is not a prerelease`);+ }+ this.prerelease.length = 0;+ break;+ case "major":+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {+ this.major++;+ }+ this.minor = 0;+ this.patch = 0;+ this.prerelease = [];+ break;+ case "minor":+ if (this.patch !== 0 || this.prerelease.length === 0) {+ this.minor++;+ }+ this.patch = 0;+ this.prerelease = [];+ break;+ case "patch":+ if (this.prerelease.length === 0) {+ this.patch++;+ }+ this.prerelease = [];+ break;+ // This probably shouldn't be used publicly.+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.+ case "pre": {+ const base = Number(identifierBase) ? 1 : 0;+ if (this.prerelease.length === 0) {+ this.prerelease = [base];+ } else {+ let i = this.prerelease.length;+ while (--i >= 0) {+ if (typeof this.prerelease[i] === "number") {+ this.prerelease[i]++;+ i = -2;+ }+ }+ if (i === -1) {+ if (identifier === this.prerelease.join(".") && identifierBase === false) {+ throw new Error("invalid increment argument: identifier already exists");+ }+ this.prerelease.push(base);+ }+ }+ if (identifier) {+ let prerelease = [identifier, base];+ if (identifierBase === false) {+ prerelease = [identifier];+ }+ if (isPrereleaseIdentifier(this.prerelease, identifier)) {+ const prereleaseBase = this.prerelease[identifier.split(".").length];+ if (isNaN(prereleaseBase)) {+ this.prerelease = prerelease;+ }+ } else {+ this.prerelease = prerelease;+ }+ }+ break;+ }+ default:+ throw new Error(`invalid increment argument: ${release}`);+ }+ this.raw = this.format();+ if (this.build.length) {+ this.raw += `+${this.build.join(".")}`;+ }+ return this;+ }+ };+ module.exports = SemVer;+ }+});++// node_modules/semver/functions/parse.js+var require_parse = __commonJS({+ "node_modules/semver/functions/parse.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var parse3 = (version4, options, throwErrors = false) => {+ if (version4 instanceof SemVer) {+ return version4;+ }+ try {+ return new SemVer(version4, options);+ } catch (er) {+ if (!throwErrors) {+ return null;+ }+ throw er;+ }+ };+ module.exports = parse3;+ }+});++// node_modules/semver/functions/valid.js+var require_valid = __commonJS({+ "node_modules/semver/functions/valid.js"(exports, module) {+ "use strict";+ var parse3 = require_parse();+ var valid = (version4, options) => {+ const v = parse3(version4, options);+ return v ? v.version : null;+ };+ module.exports = valid;+ }+});++// node_modules/semver/functions/clean.js+var require_clean = __commonJS({+ "node_modules/semver/functions/clean.js"(exports, module) {+ "use strict";+ var parse3 = require_parse();+ var clean = (version4, options) => {+ const s = parse3(version4.trim().replace(/^[=v]+/, ""), options);+ return s ? s.version : null;+ };+ module.exports = clean;+ }+});++// node_modules/semver/functions/inc.js+var require_inc = __commonJS({+ "node_modules/semver/functions/inc.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var inc = (version4, release, options, identifier, identifierBase) => {+ if (typeof options === "string") {+ identifierBase = identifier;+ identifier = options;+ options = void 0;+ }+ try {+ return new SemVer(+ version4 instanceof SemVer ? version4.version : version4,+ options+ ).inc(release, identifier, identifierBase).version;+ } catch (er) {+ return null;+ }+ };+ module.exports = inc;+ }+});++// node_modules/semver/functions/diff.js+var require_diff = __commonJS({+ "node_modules/semver/functions/diff.js"(exports, module) {+ "use strict";+ var parse3 = require_parse();+ var diff = (version1, version22) => {+ const v1 = parse3(version1, null, true);+ const v2 = parse3(version22, null, true);+ const comparison = v1.compare(v2);+ if (comparison === 0) {+ return null;+ }+ const v1Higher = comparison > 0;+ const highVersion = v1Higher ? v1 : v2;+ const lowVersion = v1Higher ? v2 : v1;+ const highHasPre = !!highVersion.prerelease.length;+ const lowHasPre = !!lowVersion.prerelease.length;+ if (lowHasPre && !highHasPre) {+ if (!lowVersion.patch && !lowVersion.minor) {+ return "major";+ }+ if (lowVersion.compareMain(highVersion) === 0) {+ if (lowVersion.minor && !lowVersion.patch) {+ return "minor";+ }+ return "patch";+ }+ }+ const prefix = highHasPre ? "pre" : "";+ if (v1.major !== v2.major) {+ return prefix + "major";+ }+ if (v1.minor !== v2.minor) {+ return prefix + "minor";+ }+ if (v1.patch !== v2.patch) {+ return prefix + "patch";+ }+ return "prerelease";+ };+ module.exports = diff;+ }+});++// node_modules/semver/functions/major.js+var require_major = __commonJS({+ "node_modules/semver/functions/major.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var major = (a, loose) => new SemVer(a, loose).major;+ module.exports = major;+ }+});++// node_modules/semver/functions/minor.js+var require_minor = __commonJS({+ "node_modules/semver/functions/minor.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var minor = (a, loose) => new SemVer(a, loose).minor;+ module.exports = minor;+ }+});++// node_modules/semver/functions/patch.js+var require_patch = __commonJS({+ "node_modules/semver/functions/patch.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var patch = (a, loose) => new SemVer(a, loose).patch;+ module.exports = patch;+ }+});++// node_modules/semver/functions/prerelease.js+var require_prerelease = __commonJS({+ "node_modules/semver/functions/prerelease.js"(exports, module) {+ "use strict";+ var parse3 = require_parse();+ var prerelease = (version4, options) => {+ const parsed = parse3(version4, options);+ return parsed && parsed.prerelease.length ? parsed.prerelease : null;+ };+ module.exports = prerelease;+ }+});++// node_modules/semver/functions/compare.js+var require_compare = __commonJS({+ "node_modules/semver/functions/compare.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));+ module.exports = compare;+ }+});++// node_modules/semver/functions/rcompare.js+var require_rcompare = __commonJS({+ "node_modules/semver/functions/rcompare.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var rcompare = (a, b, loose) => compare(b, a, loose);+ module.exports = rcompare;+ }+});++// node_modules/semver/functions/compare-loose.js+var require_compare_loose = __commonJS({+ "node_modules/semver/functions/compare-loose.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var compareLoose = (a, b) => compare(a, b, true);+ module.exports = compareLoose;+ }+});++// node_modules/semver/functions/compare-build.js+var require_compare_build = __commonJS({+ "node_modules/semver/functions/compare-build.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var compareBuild = (a, b, loose) => {+ const versionA = new SemVer(a, loose);+ const versionB = new SemVer(b, loose);+ return versionA.compare(versionB) || versionA.compareBuild(versionB);+ };+ module.exports = compareBuild;+ }+});++// node_modules/semver/functions/sort.js+var require_sort = __commonJS({+ "node_modules/semver/functions/sort.js"(exports, module) {+ "use strict";+ var compareBuild = require_compare_build();+ var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));+ module.exports = sort;+ }+});++// node_modules/semver/functions/rsort.js+var require_rsort = __commonJS({+ "node_modules/semver/functions/rsort.js"(exports, module) {+ "use strict";+ var compareBuild = require_compare_build();+ var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));+ module.exports = rsort;+ }+});++// node_modules/semver/functions/gt.js+var require_gt = __commonJS({+ "node_modules/semver/functions/gt.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var gt = (a, b, loose) => compare(a, b, loose) > 0;+ module.exports = gt;+ }+});++// node_modules/semver/functions/lt.js+var require_lt = __commonJS({+ "node_modules/semver/functions/lt.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var lt = (a, b, loose) => compare(a, b, loose) < 0;+ module.exports = lt;+ }+});++// node_modules/semver/functions/eq.js+var require_eq = __commonJS({+ "node_modules/semver/functions/eq.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var eq = (a, b, loose) => compare(a, b, loose) === 0;+ module.exports = eq;+ }+});++// node_modules/semver/functions/neq.js+var require_neq = __commonJS({+ "node_modules/semver/functions/neq.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var neq = (a, b, loose) => compare(a, b, loose) !== 0;+ module.exports = neq;+ }+});++// node_modules/semver/functions/gte.js+var require_gte = __commonJS({+ "node_modules/semver/functions/gte.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var gte = (a, b, loose) => compare(a, b, loose) >= 0;+ module.exports = gte;+ }+});++// node_modules/semver/functions/lte.js+var require_lte = __commonJS({+ "node_modules/semver/functions/lte.js"(exports, module) {+ "use strict";+ var compare = require_compare();+ var lte = (a, b, loose) => compare(a, b, loose) <= 0;+ module.exports = lte;+ }+});++// node_modules/semver/functions/cmp.js+var require_cmp = __commonJS({+ "node_modules/semver/functions/cmp.js"(exports, module) {+ "use strict";+ var eq = require_eq();+ var neq = require_neq();+ var gt = require_gt();+ var gte = require_gte();+ var lt = require_lt();+ var lte = require_lte();+ var cmp = (a, op, b, loose) => {+ switch (op) {+ case "===":+ if (typeof a === "object") {+ a = a.version;+ }+ if (typeof b === "object") {+ b = b.version;+ }+ return a === b;+ case "!==":+ if (typeof a === "object") {+ a = a.version;+ }+ if (typeof b === "object") {+ b = b.version;+ }+ return a !== b;+ case "":+ case "=":+ case "==":+ return eq(a, b, loose);+ case "!=":+ return neq(a, b, loose);+ case ">":+ return gt(a, b, loose);+ case ">=":+ return gte(a, b, loose);+ case "<":+ return lt(a, b, loose);+ case "<=":+ return lte(a, b, loose);+ default:+ throw new TypeError(`Invalid operator: ${op}`);+ }+ };+ module.exports = cmp;+ }+});++// node_modules/semver/functions/coerce.js+var require_coerce = __commonJS({+ "node_modules/semver/functions/coerce.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var parse3 = require_parse();+ var { safeRe: re, t } = require_re();+ var coerce2 = (version4, options) => {+ if (version4 instanceof SemVer) {+ return version4;+ }+ if (typeof version4 === "number") {+ version4 = String(version4);+ }+ if (typeof version4 !== "string") {+ return null;+ }+ options = options || {};+ let match = null;+ if (!options.rtl) {+ match = version4.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);+ } else {+ const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];+ let next;+ while ((next = coerceRtlRegex.exec(version4)) && (!match || match.index + match[0].length !== version4.length)) {+ if (!match || next.index + next[0].length !== match.index + match[0].length) {+ match = next;+ }+ coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;+ }+ coerceRtlRegex.lastIndex = -1;+ }+ if (match === null) {+ return null;+ }+ const major = match[2];+ const minor = match[3] || "0";+ const patch = match[4] || "0";+ const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";+ const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";+ return parse3(`${major}.${minor}.${patch}${prerelease}${build}`, options);+ };+ module.exports = coerce2;+ }+});++// node_modules/semver/functions/truncate.js+var require_truncate = __commonJS({+ "node_modules/semver/functions/truncate.js"(exports, module) {+ "use strict";+ var parse3 = require_parse();+ var constants = require_constants();+ var SemVer = require_semver();+ var truncate = (version4, truncation, options) => {+ if (!constants.RELEASE_TYPES.includes(truncation)) {+ return null;+ }+ const clonedVersion = cloneInputVersion(version4, options);+ return clonedVersion && doTruncation(clonedVersion, truncation);+ };+ var cloneInputVersion = (version4, options) => {+ const versionStringToParse = version4 instanceof SemVer ? version4.version : version4;+ return parse3(versionStringToParse, options);+ };+ var doTruncation = (version4, truncation) => {+ if (isPrerelease(truncation)) {+ return version4.version;+ }+ version4.prerelease = [];+ switch (truncation) {+ case "major":+ version4.minor = 0;+ version4.patch = 0;+ break;+ case "minor":+ version4.patch = 0;+ break;+ }+ return version4.format();+ };+ var isPrerelease = (type) => {+ return type.startsWith("pre");+ };+ module.exports = truncate;+ }+});++// node_modules/semver/internal/lrucache.js+var require_lrucache = __commonJS({+ "node_modules/semver/internal/lrucache.js"(exports, module) {+ "use strict";+ var LRUCache = class {+ constructor() {+ this.max = 1e3;+ this.map = /* @__PURE__ */ new Map();+ }+ get(key) {+ const value = this.map.get(key);+ if (value === void 0) {+ return void 0;+ } else {+ this.map.delete(key);+ this.map.set(key, value);+ return value;+ }+ }+ delete(key) {+ return this.map.delete(key);+ }+ set(key, value) {+ const deleted = this.delete(key);+ if (!deleted && value !== void 0) {+ if (this.map.size >= this.max) {+ const firstKey = this.map.keys().next().value;+ this.delete(firstKey);+ }+ this.map.set(key, value);+ }+ return this;+ }+ };+ module.exports = LRUCache;+ }+});++// node_modules/semver/classes/range.js+var require_range = __commonJS({+ "node_modules/semver/classes/range.js"(exports, module) {+ "use strict";+ var SPACE_CHARACTERS = /\s+/g;+ var Range = class _Range {+ constructor(range, options) {+ options = parseOptions(options);+ if (range instanceof _Range) {+ if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {+ return range;+ } else {+ return new _Range(range.raw, options);+ }+ }+ if (range instanceof Comparator) {+ this.raw = range.value;+ this.set = [[range]];+ this.formatted = void 0;+ return this;+ }+ this.options = options;+ this.loose = !!options.loose;+ this.includePrerelease = !!options.includePrerelease;+ this.raw = range.trim().replace(SPACE_CHARACTERS, " ");+ this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c) => c.length);+ if (!this.set.length) {+ throw new TypeError(`Invalid SemVer Range: ${this.raw}`);+ }+ if (this.set.length > 1) {+ const first = this.set[0];+ this.set = this.set.filter((c) => !isNullSet(c[0]));+ if (this.set.length === 0) {+ this.set = [first];+ } else if (this.set.length > 1) {+ for (const c of this.set) {+ if (c.length === 1 && isAny(c[0])) {+ this.set = [c];+ break;+ }+ }+ }+ }+ this.formatted = void 0;+ }+ get range() {+ if (this.formatted === void 0) {+ this.formatted = "";+ for (let i = 0; i < this.set.length; i++) {+ if (i > 0) {+ this.formatted += "||";+ }+ const comps = this.set[i];+ for (let k = 0; k < comps.length; k++) {+ if (k > 0) {+ this.formatted += " ";+ }+ this.formatted += comps[k].toString().trim();+ }+ }+ }+ return this.formatted;+ }+ format() {+ return this.range;+ }+ toString() {+ return this.range;+ }+ parseRange(range) {+ range = range.replace(BUILDSTRIPRE, "");+ const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);+ const memoKey = memoOpts + ":" + range;+ const cached2 = cache.get(memoKey);+ if (cached2) {+ return cached2;+ }+ const loose = this.options.loose;+ const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];+ range = range.replace(hr, hyphenReplace(this.options.includePrerelease));+ debug("hyphen replace", range);+ range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);+ debug("comparator trim", range);+ range = range.replace(re[t.TILDETRIM], tildeTrimReplace);+ debug("tilde trim", range);+ range = range.replace(re[t.CARETTRIM], caretTrimReplace);+ debug("caret trim", range);+ let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));+ if (loose) {+ rangeList = rangeList.filter((comp) => {+ debug("loose invalid filter", comp, this.options);+ return !!comp.match(re[t.COMPARATORLOOSE]);+ });+ }+ debug("range list", rangeList);+ const rangeMap = /* @__PURE__ */ new Map();+ const comparators = rangeList.map((comp) => new Comparator(comp, this.options));+ for (const comp of comparators) {+ if (isNullSet(comp)) {+ return [comp];+ }+ rangeMap.set(comp.value, comp);+ }+ if (rangeMap.size > 1 && rangeMap.has("")) {+ rangeMap.delete("");+ }+ const result = [...rangeMap.values()];+ cache.set(memoKey, result);+ return result;+ }+ intersects(range, options) {+ if (!(range instanceof _Range)) {+ throw new TypeError("a Range is required");+ }+ return this.set.some((thisComparators) => {+ return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {+ return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {+ return rangeComparators.every((rangeComparator) => {+ return thisComparator.intersects(rangeComparator, options);+ });+ });+ });+ });+ }+ // if ANY of the sets match ALL of its comparators, then pass+ test(version4) {+ if (!version4) {+ return false;+ }+ if (typeof version4 === "string") {+ try {+ version4 = new SemVer(version4, this.options);+ } catch (er) {+ return false;+ }+ }+ for (let i = 0; i < this.set.length; i++) {+ if (testSet(this.set[i], version4, this.options)) {+ return true;+ }+ }+ return false;+ }+ };+ module.exports = Range;+ var LRU = require_lrucache();+ var cache = new LRU();+ var parseOptions = require_parse_options();+ var Comparator = require_comparator();+ var debug = require_debug();+ var SemVer = require_semver();+ var {+ safeRe: re,+ src,+ t,+ comparatorTrimReplace,+ tildeTrimReplace,+ caretTrimReplace+ } = require_re();+ var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();+ var BUILDSTRIPRE = new RegExp(src[t.BUILD], "g");+ var isNullSet = (c) => c.value === "<0.0.0-0";+ var isAny = (c) => c.value === "";+ var isSatisfiable = (comparators, options) => {+ let result = true;+ const remainingComparators = comparators.slice();+ let testComparator = remainingComparators.pop();+ while (result && remainingComparators.length) {+ result = remainingComparators.every((otherComparator) => {+ return testComparator.intersects(otherComparator, options);+ });+ testComparator = remainingComparators.pop();+ }+ return result;+ };+ var parseComparator = (comp, options) => {+ comp = comp.replace(re[t.BUILD], "");+ debug("comp", comp, options);+ comp = replaceCarets(comp, options);+ debug("caret", comp);+ comp = replaceTildes(comp, options);+ debug("tildes", comp);+ comp = replaceXRanges(comp, options);+ debug("xrange", comp);+ comp = replaceStars(comp, options);+ debug("stars", comp);+ return comp;+ };+ var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";+ var invalidXRangeOrder = (M, m, p) => isX(M) && !isX(m) || isX(m) && p && !isX(p);+ var replaceTildes = (comp, options) => {+ return comp.trim().split(/\s+/).map((c) => replaceTilde(c, options)).join(" ");+ };+ var replaceTilde = (comp, options) => {+ const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];+ const z = options.includePrerelease ? "-0" : "";+ return comp.replace(r, (_, M, m, p, pr) => {+ debug("tilde", comp, _, M, m, p, pr);+ let ret;+ if (isX(M)) {+ ret = "";+ } else if (isX(m)) {+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;+ } else if (isX(p)) {+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;+ } else if (pr) {+ debug("replaceTilde pr", pr);+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;+ } else {+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;+ }+ debug("tilde return", ret);+ return ret;+ });+ };+ var replaceCarets = (comp, options) => {+ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" ");+ };+ var replaceCaret = (comp, options) => {+ debug("caret", comp, options);+ const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];+ const z = options.includePrerelease ? "-0" : "";+ return comp.replace(r, (_, M, m, p, pr) => {+ debug("caret", comp, _, M, m, p, pr);+ let ret;+ if (isX(M)) {+ ret = "";+ } else if (isX(m)) {+ ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;+ } else if (isX(p)) {+ if (M === "0") {+ ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;+ } else {+ ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;+ }+ } else if (pr) {+ debug("replaceCaret pr", pr);+ if (M === "0") {+ if (m === "0") {+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;+ } else {+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;+ }+ } else {+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;+ }+ } else {+ debug("no pr");+ if (M === "0") {+ if (m === "0") {+ ret = `>=${M}.${m}.${p} <${M}.${m}.${+p + 1}-0`;+ } else {+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;+ }+ } else {+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;+ }+ }+ debug("caret return", ret);+ return ret;+ });+ };+ var replaceXRanges = (comp, options) => {+ debug("replaceXRanges", comp, options);+ return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" ");+ };+ var replaceXRange = (comp, options) => {+ comp = comp.trim();+ const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {+ debug("xRange", comp, ret, gtlt, M, m, p, pr);+ if (invalidXRangeOrder(M, m, p)) {+ return comp;+ }+ const xM = isX(M);+ const xm = xM || isX(m);+ const xp = xm || isX(p);+ const anyX = xp;+ if (gtlt === "=" && anyX) {+ gtlt = "";+ }+ pr = options.includePrerelease ? "-0" : "";+ if (xM) {+ if (gtlt === ">" || gtlt === "<") {+ ret = "<0.0.0-0";+ } else {+ ret = "*";+ }+ } else if (gtlt && anyX) {+ if (xm) {+ m = 0;+ }+ p = 0;+ if (gtlt === ">") {+ gtlt = ">=";+ if (xm) {+ M = +M + 1;+ m = 0;+ p = 0;+ } else {+ m = +m + 1;+ p = 0;+ }+ } else if (gtlt === "<=") {+ gtlt = "<";+ if (xm) {+ M = +M + 1;+ } else {+ m = +m + 1;+ }+ }+ if (gtlt === "<") {+ pr = "-0";+ }+ ret = `${gtlt + M}.${m}.${p}${pr}`;+ } else if (xm) {+ ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;+ } else if (xp) {+ ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;+ }+ debug("xRange return", ret);+ return ret;+ });+ };+ var replaceStars = (comp, options) => {+ debug("replaceStars", comp, options);+ return comp.trim().replace(re[t.STAR], "");+ };+ var replaceGTE0 = (comp, options) => {+ debug("replaceGTE0", comp, options);+ return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");+ };+ var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {+ if (isX(fM)) {+ from = "";+ } else if (isX(fm)) {+ from = `>=${fM}.0.0${incPr ? "-0" : ""}`;+ } else if (isX(fp)) {+ from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;+ } else if (fpr) {+ from = `>=${from}`;+ } else {+ from = `>=${from}${incPr ? "-0" : ""}`;+ }+ if (isX(tM)) {+ to = "";+ } else if (isX(tm)) {+ to = `<${+tM + 1}.0.0-0`;+ } else if (isX(tp)) {+ to = `<${tM}.${+tm + 1}.0-0`;+ } else if (tpr) {+ to = `<=${tM}.${tm}.${tp}-${tpr}`;+ } else if (incPr) {+ to = `<${tM}.${tm}.${+tp + 1}-0`;+ } else {+ to = `<=${to}`;+ }+ return `${from} ${to}`.trim();+ };+ var testSet = (set, version4, options) => {+ for (let i = 0; i < set.length; i++) {+ if (!set[i].test(version4)) {+ return false;+ }+ }+ if (version4.prerelease.length && !options.includePrerelease) {+ for (let i = 0; i < set.length; i++) {+ debug(set[i].semver);+ if (set[i].semver === Comparator.ANY) {+ continue;+ }+ if (set[i].semver.prerelease.length > 0) {+ const allowed = set[i].semver;+ if (allowed.major === version4.major && allowed.minor === version4.minor && allowed.patch === version4.patch) {+ return true;+ }+ }+ }+ return false;+ }+ return true;+ };+ }+});++// node_modules/semver/classes/comparator.js+var require_comparator = __commonJS({+ "node_modules/semver/classes/comparator.js"(exports, module) {+ "use strict";+ var ANY = Symbol("SemVer ANY");+ var Comparator = class _Comparator {+ static get ANY() {+ return ANY;+ }+ constructor(comp, options) {+ options = parseOptions(options);+ if (comp instanceof _Comparator) {+ if (comp.loose === !!options.loose) {+ return comp;+ } else {+ comp = comp.value;+ }+ }+ comp = comp.trim().split(/\s+/).join(" ");+ debug("comparator", comp, options);+ this.options = options;+ this.loose = !!options.loose;+ this.parse(comp);+ if (this.semver === ANY) {+ this.value = "";+ } else {+ this.value = this.operator + this.semver.version;+ }+ debug("comp", this);+ }+ parse(comp) {+ const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];+ const m = comp.match(r);+ if (!m) {+ throw new TypeError(`Invalid comparator: ${comp}`);+ }+ this.operator = m[1] !== void 0 ? m[1] : "";+ if (this.operator === "=") {+ this.operator = "";+ }+ if (!m[2]) {+ this.semver = ANY;+ } else {+ this.semver = new SemVer(m[2], this.options.loose);+ }+ }+ toString() {+ return this.value;+ }+ test(version4) {+ debug("Comparator.test", version4, this.options.loose);+ if (this.semver === ANY || version4 === ANY) {+ return true;+ }+ if (typeof version4 === "string") {+ try {+ version4 = new SemVer(version4, this.options);+ } catch (er) {+ return false;+ }+ }+ return cmp(version4, this.operator, this.semver, this.options);+ }+ intersects(comp, options) {+ if (!(comp instanceof _Comparator)) {+ throw new TypeError("a Comparator is required");+ }+ if (this.operator === "") {+ if (this.value === "") {+ return true;+ }+ return new Range(comp.value, options).test(this.value);+ } else if (comp.operator === "") {+ if (comp.value === "") {+ return true;+ }+ return new Range(this.value, options).test(comp.semver);+ }+ options = parseOptions(options);+ if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {+ return false;+ }+ if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {+ return false;+ }+ if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {+ return true;+ }+ if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {+ return true;+ }+ if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {+ return true;+ }+ if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {+ return true;+ }+ if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {+ return true;+ }+ return false;+ }+ };+ module.exports = Comparator;+ var parseOptions = require_parse_options();+ var { safeRe: re, t } = require_re();+ var cmp = require_cmp();+ var debug = require_debug();+ var SemVer = require_semver();+ var Range = require_range();+ }+});++// node_modules/semver/functions/satisfies.js+var require_satisfies = __commonJS({+ "node_modules/semver/functions/satisfies.js"(exports, module) {+ "use strict";+ var Range = require_range();+ var satisfies = (version4, range, options) => {+ try {+ range = new Range(range, options);+ } catch (er) {+ return false;+ }+ return range.test(version4);+ };+ module.exports = satisfies;+ }+});++// node_modules/semver/ranges/to-comparators.js+var require_to_comparators = __commonJS({+ "node_modules/semver/ranges/to-comparators.js"(exports, module) {+ "use strict";+ var Range = require_range();+ var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c) => c.value).join(" ").trim().split(" "));+ module.exports = toComparators;+ }+});++// node_modules/semver/ranges/max-satisfying.js+var require_max_satisfying = __commonJS({+ "node_modules/semver/ranges/max-satisfying.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var Range = require_range();+ var maxSatisfying = (versions, range, options) => {+ let max = null;+ let maxSV = null;+ let rangeObj = null;+ try {+ rangeObj = new Range(range, options);+ } catch (er) {+ return null;+ }+ versions.forEach((v) => {+ if (rangeObj.test(v)) {+ if (!max || maxSV.compare(v) === -1) {+ max = v;+ maxSV = new SemVer(max, options);+ }+ }+ });+ return max;+ };+ module.exports = maxSatisfying;+ }+});++// node_modules/semver/ranges/min-satisfying.js+var require_min_satisfying = __commonJS({+ "node_modules/semver/ranges/min-satisfying.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var Range = require_range();+ var minSatisfying = (versions, range, options) => {+ let min = null;+ let minSV = null;+ let rangeObj = null;+ try {+ rangeObj = new Range(range, options);+ } catch (er) {+ return null;+ }+ versions.forEach((v) => {+ if (rangeObj.test(v)) {+ if (!min || minSV.compare(v) === 1) {+ min = v;+ minSV = new SemVer(min, options);+ }+ }+ });+ return min;+ };+ module.exports = minSatisfying;+ }+});++// node_modules/semver/ranges/min-version.js+var require_min_version = __commonJS({+ "node_modules/semver/ranges/min-version.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var Range = require_range();+ var gt = require_gt();+ var minVersion = (range, loose) => {+ range = new Range(range, loose);+ let minver = new SemVer("0.0.0");+ if (range.test(minver)) {+ return minver;+ }+ minver = new SemVer("0.0.0-0");+ if (range.test(minver)) {+ return minver;+ }+ minver = null;+ for (let i = 0; i < range.set.length; ++i) {+ const comparators = range.set[i];+ let setMin = null;+ comparators.forEach((comparator) => {+ const compver = new SemVer(comparator.semver.version);+ switch (comparator.operator) {+ case ">":+ if (compver.prerelease.length === 0) {+ compver.patch++;+ } else {+ compver.prerelease.push(0);+ }+ compver.raw = compver.format();+ /* fallthrough */+ case "":+ case ">=":+ if (!setMin || gt(compver, setMin)) {+ setMin = compver;+ }+ break;+ case "<":+ case "<=":+ break;+ /* istanbul ignore next */+ default:+ throw new Error(`Unexpected operation: ${comparator.operator}`);+ }+ });+ if (setMin && (!minver || gt(minver, setMin))) {+ minver = setMin;+ }+ }+ if (minver && range.test(minver)) {+ return minver;+ }+ return null;+ };+ module.exports = minVersion;+ }+});++// node_modules/semver/ranges/valid.js+var require_valid2 = __commonJS({+ "node_modules/semver/ranges/valid.js"(exports, module) {+ "use strict";+ var Range = require_range();+ var validRange = (range, options) => {+ try {+ return new Range(range, options).range || "*";+ } catch (er) {+ return null;+ }+ };+ module.exports = validRange;+ }+});++// node_modules/semver/ranges/outside.js+var require_outside = __commonJS({+ "node_modules/semver/ranges/outside.js"(exports, module) {+ "use strict";+ var SemVer = require_semver();+ var Comparator = require_comparator();+ var { ANY } = Comparator;+ var Range = require_range();+ var satisfies = require_satisfies();+ var gt = require_gt();+ var lt = require_lt();+ var lte = require_lte();+ var gte = require_gte();+ var outside = (version4, range, hilo, options) => {+ version4 = new SemVer(version4, options);+ range = new Range(range, options);+ let gtfn, ltefn, ltfn, comp, ecomp;+ switch (hilo) {+ case ">":+ gtfn = gt;+ ltefn = lte;+ ltfn = lt;+ comp = ">";+ ecomp = ">=";+ break;+ case "<":+ gtfn = lt;+ ltefn = gte;+ ltfn = gt;+ comp = "<";+ ecomp = "<=";+ break;+ default:+ throw new TypeError('Must provide a hilo val of "<" or ">"');+ }+ if (satisfies(version4, range, options)) {+ return false;+ }+ for (let i = 0; i < range.set.length; ++i) {+ const comparators = range.set[i];+ let high = null;+ let low = null;+ comparators.forEach((comparator) => {+ if (comparator.semver === ANY) {+ comparator = new Comparator(">=0.0.0");+ }+ high = high || comparator;+ low = low || comparator;+ if (gtfn(comparator.semver, high.semver, options)) {+ high = comparator;+ } else if (ltfn(comparator.semver, low.semver, options)) {+ low = comparator;+ }+ });+ if (high.operator === comp || high.operator === ecomp) {+ return false;+ }+ if ((!low.operator || low.operator === comp) && ltefn(version4, low.semver)) {+ return false;+ } else if (low.operator === ecomp && ltfn(version4, low.semver)) {+ return false;+ }+ }+ return true;+ };+ module.exports = outside;+ }+});++// node_modules/semver/ranges/gtr.js+var require_gtr = __commonJS({+ "node_modules/semver/ranges/gtr.js"(exports, module) {+ "use strict";+ var outside = require_outside();+ var gtr = (version4, range, options) => outside(version4, range, ">", options);+ module.exports = gtr;+ }+});++// node_modules/semver/ranges/ltr.js+var require_ltr = __commonJS({+ "node_modules/semver/ranges/ltr.js"(exports, module) {+ "use strict";+ var outside = require_outside();+ var ltr = (version4, range, options) => outside(version4, range, "<", options);+ module.exports = ltr;+ }+});++// node_modules/semver/ranges/intersects.js+var require_intersects = __commonJS({+ "node_modules/semver/ranges/intersects.js"(exports, module) {+ "use strict";+ var Range = require_range();+ var intersects = (r1, r2, options) => {+ r1 = new Range(r1, options);+ r2 = new Range(r2, options);+ return r1.intersects(r2, options);+ };+ module.exports = intersects;+ }+});++// node_modules/semver/ranges/simplify.js+var require_simplify = __commonJS({+ "node_modules/semver/ranges/simplify.js"(exports, module) {+ "use strict";+ var satisfies = require_satisfies();+ var compare = require_compare();+ module.exports = (versions, range, options) => {+ const set = [];+ let first = null;+ let prev = null;+ const v = versions.sort((a, b) => compare(a, b, options));+ for (const version4 of v) {+ const included = satisfies(version4, range, options);+ if (included) {+ prev = version4;+ if (!first) {+ first = version4;+ }+ } else {+ if (prev) {+ set.push([first, prev]);+ }+ prev = null;+ first = null;+ }+ }+ if (first) {+ set.push([first, null]);+ }+ const ranges = [];+ for (const [min, max] of set) {+ if (min === max) {+ ranges.push(min);+ } else if (!max && min === v[0]) {+ ranges.push("*");+ } else if (!max) {+ ranges.push(`>=${min}`);+ } else if (min === v[0]) {+ ranges.push(`<=${max}`);+ } else {+ ranges.push(`${min} - ${max}`);+ }+ }+ const simplified = ranges.join(" || ");+ const original = typeof range.raw === "string" ? range.raw : String(range);+ return simplified.length < original.length ? simplified : range;+ };+ }+});++// node_modules/semver/ranges/subset.js+var require_subset = __commonJS({+ "node_modules/semver/ranges/subset.js"(exports, module) {+ "use strict";+ var Range = require_range();+ var Comparator = require_comparator();+ var { ANY } = Comparator;+ var satisfies = require_satisfies();+ var compare = require_compare();+ var subset = (sub, dom, options = {}) => {+ if (sub === dom) {+ return true;+ }+ sub = new Range(sub, options);+ dom = new Range(dom, options);+ let sawNonNull = false;+ OUTER: for (const simpleSub of sub.set) {+ for (const simpleDom of dom.set) {+ const isSub = simpleSubset(simpleSub, simpleDom, options);+ sawNonNull = sawNonNull || isSub !== null;+ if (isSub) {+ continue OUTER;+ }+ }+ if (sawNonNull) {+ return false;+ }+ }+ return true;+ };+ var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];+ var minimumVersion = [new Comparator(">=0.0.0")];+ var simpleSubset = (sub, dom, options) => {+ if (sub === dom) {+ return true;+ }+ if (sub.length === 1 && sub[0].semver === ANY) {+ if (dom.length === 1 && dom[0].semver === ANY) {+ return true;+ } else if (options.includePrerelease) {+ sub = minimumVersionWithPreRelease;+ } else {+ sub = minimumVersion;+ }+ }+ if (dom.length === 1 && dom[0].semver === ANY) {+ if (options.includePrerelease) {+ return true;+ } else {+ dom = minimumVersion;+ }+ }+ const eqSet = /* @__PURE__ */ new Set();+ let gt, lt;+ for (const c of sub) {+ if (c.operator === ">" || c.operator === ">=") {+ gt = higherGT(gt, c, options);+ } else if (c.operator === "<" || c.operator === "<=") {+ lt = lowerLT(lt, c, options);+ } else {+ eqSet.add(c.semver);+ }+ }+ if (eqSet.size > 1) {+ return null;+ }+ let gtltComp;+ if (gt && lt) {+ gtltComp = compare(gt.semver, lt.semver, options);+ if (gtltComp > 0) {+ return null;+ } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {+ return null;+ }+ }+ for (const eq of eqSet) {+ if (gt && !satisfies(eq, String(gt), options)) {+ return null;+ }+ if (lt && !satisfies(eq, String(lt), options)) {+ return null;+ }+ for (const c of dom) {+ if (!satisfies(eq, String(c), options)) {+ return false;+ }+ }+ return true;+ }+ let higher, lower;+ let hasDomLT, hasDomGT;+ let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;+ let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;+ if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {+ needDomLTPre = false;+ }+ for (const c of dom) {+ hasDomGT = hasDomGT || c.operator === ">" || c.operator === ">=";+ hasDomLT = hasDomLT || c.operator === "<" || c.operator === "<=";+ if (gt) {+ if (needDomGTPre) {+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {+ needDomGTPre = false;+ }+ }+ if (c.operator === ">" || c.operator === ">=") {+ higher = higherGT(gt, c, options);+ if (higher === c && higher !== gt) {+ return false;+ }+ } else if (gt.operator === ">=" && !c.test(gt.semver)) {+ return false;+ }+ }+ if (lt) {+ if (needDomLTPre) {+ if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {+ needDomLTPre = false;+ }+ }+ if (c.operator === "<" || c.operator === "<=") {+ lower = lowerLT(lt, c, options);+ if (lower === c && lower !== lt) {+ return false;+ }+ } else if (lt.operator === "<=" && !c.test(lt.semver)) {+ return false;+ }+ }+ if (!c.operator && (lt || gt) && gtltComp !== 0) {+ return false;+ }+ }+ if (gt && hasDomLT && !lt && gtltComp !== 0) {+ return false;+ }+ if (lt && hasDomGT && !gt && gtltComp !== 0) {+ return false;+ }+ if (needDomGTPre || needDomLTPre) {+ return false;+ }+ return true;+ };+ var higherGT = (a, b, options) => {+ if (!a) {+ return b;+ }+ const comp = compare(a.semver, b.semver, options);+ return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;+ };+ var lowerLT = (a, b, options) => {+ if (!a) {+ return b;+ }+ const comp = compare(a.semver, b.semver, options);+ return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;+ };+ module.exports = subset;+ }+});++// node_modules/semver/index.js+var require_semver2 = __commonJS({+ "node_modules/semver/index.js"(exports, module) {+ "use strict";+ var internalRe = require_re();+ var constants = require_constants();+ var SemVer = require_semver();+ var identifiers = require_identifiers();+ var parse3 = require_parse();+ var valid = require_valid();+ var clean = require_clean();+ var inc = require_inc();+ var diff = require_diff();+ var major = require_major();+ var minor = require_minor();+ var patch = require_patch();+ var prerelease = require_prerelease();+ var compare = require_compare();+ var rcompare = require_rcompare();+ var compareLoose = require_compare_loose();+ var compareBuild = require_compare_build();+ var sort = require_sort();+ var rsort = require_rsort();+ var gt = require_gt();+ var lt = require_lt();+ var eq = require_eq();+ var neq = require_neq();+ var gte = require_gte();+ var lte = require_lte();+ var cmp = require_cmp();+ var coerce2 = require_coerce();+ var truncate = require_truncate();+ var Comparator = require_comparator();+ var Range = require_range();+ var satisfies = require_satisfies();+ var toComparators = require_to_comparators();+ var maxSatisfying = require_max_satisfying();+ var minSatisfying = require_min_satisfying();+ var minVersion = require_min_version();+ var validRange = require_valid2();+ var outside = require_outside();+ var gtr = require_gtr();+ var ltr = require_ltr();+ var intersects = require_intersects();+ var simplifyRange = require_simplify();+ var subset = require_subset();+ module.exports = {+ parse: parse3,+ valid,+ clean,+ inc,+ diff,+ major,+ minor,+ patch,+ prerelease,+ compare,+ rcompare,+ compareLoose,+ compareBuild,+ sort,+ rsort,+ gt,+ lt,+ eq,+ neq,+ gte,+ lte,+ cmp,+ coerce: coerce2,+ truncate,+ Comparator,+ Range,+ satisfies,+ toComparators,+ maxSatisfying,+ minSatisfying,+ minVersion,+ validRange,+ outside,+ gtr,+ ltr,+ intersects,+ simplifyRange,+ subset,+ SemVer,+ re: internalRe.re,+ src: internalRe.src,+ tokens: internalRe.t,+ SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,+ RELEASE_TYPES: constants.RELEASE_TYPES,+ compareIdentifiers: identifiers.compareIdentifiers,+ rcompareIdentifiers: identifiers.rcompareIdentifiers+ };+ }+});++// node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js+var require_asymmetricKeyDetailsSupported = __commonJS({+ "node_modules/jsonwebtoken/lib/asymmetricKeyDetailsSupported.js"(exports, module) {+ var semver = require_semver2();+ module.exports = semver.satisfies(process.version, ">=15.7.0");+ }+});++// node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js+var require_rsaPssKeyDetailsSupported = __commonJS({+ "node_modules/jsonwebtoken/lib/rsaPssKeyDetailsSupported.js"(exports, module) {+ var semver = require_semver2();+ module.exports = semver.satisfies(process.version, ">=16.9.0");+ }+});++// node_modules/jsonwebtoken/lib/validateAsymmetricKey.js+var require_validateAsymmetricKey = __commonJS({+ "node_modules/jsonwebtoken/lib/validateAsymmetricKey.js"(exports, module) {+ var ASYMMETRIC_KEY_DETAILS_SUPPORTED = require_asymmetricKeyDetailsSupported();+ var RSA_PSS_KEY_DETAILS_SUPPORTED = require_rsaPssKeyDetailsSupported();+ var allowedAlgorithmsForKeys = {+ "ec": ["ES256", "ES384", "ES512"],+ "rsa": ["RS256", "PS256", "RS384", "PS384", "RS512", "PS512"],+ "rsa-pss": ["PS256", "PS384", "PS512"]+ };+ var allowedCurves = {+ ES256: "prime256v1",+ ES384: "secp384r1",+ ES512: "secp521r1"+ };+ module.exports = function(algorithm, key) {+ if (!algorithm || !key) return;+ const keyType = key.asymmetricKeyType;+ if (!keyType) return;+ const allowedAlgorithms = allowedAlgorithmsForKeys[keyType];+ if (!allowedAlgorithms) {+ throw new Error(`Unknown key type "${keyType}".`);+ }+ if (!allowedAlgorithms.includes(algorithm)) {+ throw new Error(`"alg" parameter for "${keyType}" key type must be one of: ${allowedAlgorithms.join(", ")}.`);+ }+ if (ASYMMETRIC_KEY_DETAILS_SUPPORTED) {+ switch (keyType) {+ case "ec":+ const keyCurve = key.asymmetricKeyDetails.namedCurve;+ const allowedCurve = allowedCurves[algorithm];+ if (keyCurve !== allowedCurve) {+ throw new Error(`"alg" parameter "${algorithm}" requires curve "${allowedCurve}".`);+ }+ break;+ case "rsa-pss":+ if (RSA_PSS_KEY_DETAILS_SUPPORTED) {+ const length = parseInt(algorithm.slice(-3), 10);+ const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;+ if (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm) {+ throw new Error(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${algorithm}.`);+ }+ if (saltLength !== void 0 && saltLength > length >> 3) {+ throw new Error(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${algorithm}.`);+ }+ }+ break;+ }+ }+ };+ }+});++// node_modules/jsonwebtoken/lib/psSupported.js+var require_psSupported = __commonJS({+ "node_modules/jsonwebtoken/lib/psSupported.js"(exports, module) {+ var semver = require_semver2();+ module.exports = semver.satisfies(process.version, "^6.12.0 || >=8.0.0");+ }+});++// node_modules/jsonwebtoken/verify.js+var require_verify = __commonJS({+ "node_modules/jsonwebtoken/verify.js"(exports, module) {+ var JsonWebTokenError = require_JsonWebTokenError();+ var NotBeforeError = require_NotBeforeError();+ var TokenExpiredError = require_TokenExpiredError();+ var decode = require_decode();+ var timespan = require_timespan();+ var validateAsymmetricKey = require_validateAsymmetricKey();+ var PS_SUPPORTED = require_psSupported();+ var jws = require_jws();+ var { KeyObject, createSecretKey, createPublicKey } = __require("crypto");+ var PUB_KEY_ALGS = ["RS256", "RS384", "RS512"];+ var EC_KEY_ALGS = ["ES256", "ES384", "ES512"];+ var RSA_KEY_ALGS = ["RS256", "RS384", "RS512"];+ var HS_ALGS = ["HS256", "HS384", "HS512"];+ if (PS_SUPPORTED) {+ PUB_KEY_ALGS.splice(PUB_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");+ RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, "PS256", "PS384", "PS512");+ }+ module.exports = function(jwtString, secretOrPublicKey, options, callback) {+ if (typeof options === "function" && !callback) {+ callback = options;+ options = {};+ }+ if (!options) {+ options = {};+ }+ options = Object.assign({}, options);+ let done;+ if (callback) {+ done = callback;+ } else {+ done = function(err, data) {+ if (err) throw err;+ return data;+ };+ }+ if (options.clockTimestamp && typeof options.clockTimestamp !== "number") {+ return done(new JsonWebTokenError("clockTimestamp must be a number"));+ }+ if (options.nonce !== void 0 && (typeof options.nonce !== "string" || options.nonce.trim() === "")) {+ return done(new JsonWebTokenError("nonce must be a non-empty string"));+ }+ if (options.allowInvalidAsymmetricKeyTypes !== void 0 && typeof options.allowInvalidAsymmetricKeyTypes !== "boolean") {+ return done(new JsonWebTokenError("allowInvalidAsymmetricKeyTypes must be a boolean"));+ }+ const clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1e3);+ if (!jwtString) {+ return done(new JsonWebTokenError("jwt must be provided"));+ }+ if (typeof jwtString !== "string") {+ return done(new JsonWebTokenError("jwt must be a string"));+ }+ const parts = jwtString.split(".");+ if (parts.length !== 3) {+ return done(new JsonWebTokenError("jwt malformed"));+ }+ let decodedToken;+ try {+ decodedToken = decode(jwtString, { complete: true });+ } catch (err) {+ return done(err);+ }+ if (!decodedToken) {+ return done(new JsonWebTokenError("invalid token"));+ }+ const header = decodedToken.header;+ let getSecret;+ if (typeof secretOrPublicKey === "function") {+ if (!callback) {+ return done(new JsonWebTokenError("verify must be called asynchronous if secret or public key is provided as a callback"));+ }+ getSecret = secretOrPublicKey;+ } else {+ getSecret = function(header2, secretCallback) {+ return secretCallback(null, secretOrPublicKey);+ };+ }+ return getSecret(header, function(err, secretOrPublicKey2) {+ if (err) {+ return done(new JsonWebTokenError("error in secret or public key callback: " + err.message));+ }+ const hasSignature = parts[2].trim() !== "";+ if (!hasSignature && secretOrPublicKey2) {+ return done(new JsonWebTokenError("jwt signature is required"));+ }+ if (hasSignature && !secretOrPublicKey2) {+ return done(new JsonWebTokenError("secret or public key must be provided"));+ }+ if (!hasSignature && !options.algorithms) {+ return done(new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens'));+ }+ if (secretOrPublicKey2 != null && !(secretOrPublicKey2 instanceof KeyObject)) {+ try {+ secretOrPublicKey2 = createPublicKey(secretOrPublicKey2);+ } catch (_) {+ try {+ secretOrPublicKey2 = createSecretKey(typeof secretOrPublicKey2 === "string" ? Buffer.from(secretOrPublicKey2) : secretOrPublicKey2);+ } catch (_2) {+ return done(new JsonWebTokenError("secretOrPublicKey is not valid key material"));+ }+ }+ }+ if (!options.algorithms) {+ if (secretOrPublicKey2.type === "secret") {+ options.algorithms = HS_ALGS;+ } else if (["rsa", "rsa-pss"].includes(secretOrPublicKey2.asymmetricKeyType)) {+ options.algorithms = RSA_KEY_ALGS;+ } else if (secretOrPublicKey2.asymmetricKeyType === "ec") {+ options.algorithms = EC_KEY_ALGS;+ } else {+ options.algorithms = PUB_KEY_ALGS;+ }+ }+ if (options.algorithms.indexOf(decodedToken.header.alg) === -1) {+ return done(new JsonWebTokenError("invalid algorithm"));+ }+ if (header.alg.startsWith("HS") && secretOrPublicKey2.type !== "secret") {+ return done(new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${header.alg}`));+ } else if (/^(?:RS|PS|ES)/.test(header.alg) && secretOrPublicKey2.type !== "public") {+ return done(new JsonWebTokenError(`secretOrPublicKey must be an asymmetric key when using ${header.alg}`));+ }+ if (!options.allowInvalidAsymmetricKeyTypes) {+ try {+ validateAsymmetricKey(header.alg, secretOrPublicKey2);+ } catch (e) {+ return done(e);+ }+ }+ let valid;+ try {+ valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey2);+ } catch (e) {+ return done(e);+ }+ if (!valid) {+ return done(new JsonWebTokenError("invalid signature"));+ }+ const payload = decodedToken.payload;+ if (typeof payload.nbf !== "undefined" && !options.ignoreNotBefore) {+ if (typeof payload.nbf !== "number") {+ return done(new JsonWebTokenError("invalid nbf value"));+ }+ if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {+ return done(new NotBeforeError("jwt not active", new Date(payload.nbf * 1e3)));+ }+ }+ if (typeof payload.exp !== "undefined" && !options.ignoreExpiration) {+ if (typeof payload.exp !== "number") {+ return done(new JsonWebTokenError("invalid exp value"));+ }+ if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {+ return done(new TokenExpiredError("jwt expired", new Date(payload.exp * 1e3)));+ }+ }+ if (options.audience) {+ const audiences = Array.isArray(options.audience) ? options.audience : [options.audience];+ const target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];+ const match = target.some(function(targetAudience) {+ return audiences.some(function(audience) {+ return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;+ });+ });+ if (!match) {+ return done(new JsonWebTokenError("jwt audience invalid. expected: " + audiences.join(" or ")));+ }+ }+ if (options.issuer) {+ const invalid_issuer = typeof options.issuer === "string" && payload.iss !== options.issuer || Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1;+ if (invalid_issuer) {+ return done(new JsonWebTokenError("jwt issuer invalid. expected: " + options.issuer));+ }+ }+ if (options.subject) {+ if (payload.sub !== options.subject) {+ return done(new JsonWebTokenError("jwt subject invalid. expected: " + options.subject));+ }+ }+ if (options.jwtid) {+ if (payload.jti !== options.jwtid) {+ return done(new JsonWebTokenError("jwt jwtid invalid. expected: " + options.jwtid));+ }+ }+ if (options.nonce) {+ if (payload.nonce !== options.nonce) {+ return done(new JsonWebTokenError("jwt nonce invalid. expected: " + options.nonce));+ }+ }+ if (options.maxAge) {+ if (typeof payload.iat !== "number") {+ return done(new JsonWebTokenError("iat required when maxAge is specified"));+ }+ const maxAgeTimestamp = timespan(options.maxAge, payload.iat);+ if (typeof maxAgeTimestamp === "undefined") {+ return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));+ }+ if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {+ return done(new TokenExpiredError("maxAge exceeded", new Date(maxAgeTimestamp * 1e3)));+ }+ }+ if (options.complete === true) {+ const signature = decodedToken.signature;+ return done(null, {+ header,+ payload,+ signature+ });+ }+ return done(null, payload);+ });+ };+ }+});++// node_modules/lodash.includes/index.js+var require_lodash = __commonJS({+ "node_modules/lodash.includes/index.js"(exports, module) {+ var INFINITY = 1 / 0;+ var MAX_SAFE_INTEGER = 9007199254740991;+ var MAX_INTEGER = 17976931348623157e292;+ var NAN = 0 / 0;+ var argsTag = "[object Arguments]";+ var funcTag = "[object Function]";+ var genTag = "[object GeneratorFunction]";+ var stringTag = "[object String]";+ var symbolTag = "[object Symbol]";+ var reTrim = /^\s+|\s+$/g;+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;+ var reIsBinary = /^0b[01]+$/i;+ var reIsOctal = /^0o[0-7]+$/i;+ var reIsUint = /^(?:0|[1-9]\d*)$/;+ var freeParseInt = parseInt;+ function arrayMap(array2, iteratee) {+ var index = -1, length = array2 ? array2.length : 0, result = Array(length);+ while (++index < length) {+ result[index] = iteratee(array2[index], index, array2);+ }+ return result;+ }+ function baseFindIndex(array2, predicate, fromIndex, fromRight) {+ var length = array2.length, index = fromIndex + (fromRight ? 1 : -1);+ while (fromRight ? index-- : ++index < length) {+ if (predicate(array2[index], index, array2)) {+ return index;+ }+ }+ return -1;+ }+ function baseIndexOf(array2, value, fromIndex) {+ if (value !== value) {+ return baseFindIndex(array2, baseIsNaN, fromIndex);+ }+ var index = fromIndex - 1, length = array2.length;+ while (++index < length) {+ if (array2[index] === value) {+ return index;+ }+ }+ return -1;+ }+ function baseIsNaN(value) {+ return value !== value;+ }+ function baseTimes(n, iteratee) {+ var index = -1, result = Array(n);+ while (++index < n) {+ result[index] = iteratee(index);+ }+ return result;+ }+ function baseValues(object3, props) {+ return arrayMap(props, function(key) {+ return object3[key];+ });+ }+ function overArg(func, transform2) {+ return function(arg) {+ return func(transform2(arg));+ };+ }+ var objectProto = Object.prototype;+ var hasOwnProperty = objectProto.hasOwnProperty;+ var objectToString = objectProto.toString;+ var propertyIsEnumerable = objectProto.propertyIsEnumerable;+ var nativeKeys = overArg(Object.keys, Object);+ var nativeMax = Math.max;+ function arrayLikeKeys(value, inherited) {+ var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];+ var length = result.length, skipIndexes = !!length;+ for (var key in value) {+ if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) {+ result.push(key);+ }+ }+ return result;+ }+ function baseKeys(object3) {+ if (!isPrototype(object3)) {+ return nativeKeys(object3);+ }+ var result = [];+ for (var key in Object(object3)) {+ if (hasOwnProperty.call(object3, key) && key != "constructor") {+ result.push(key);+ }+ }+ return result;+ }+ function isIndex(value, length) {+ length = length == null ? MAX_SAFE_INTEGER : length;+ return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);+ }+ function isPrototype(value) {+ var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;+ return value === proto;+ }+ function includes(collection, value, fromIndex, guard) {+ collection = isArrayLike(collection) ? collection : values(collection);+ fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;+ var length = collection.length;+ if (fromIndex < 0) {+ fromIndex = nativeMax(length + fromIndex, 0);+ }+ return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;+ }+ function isArguments(value) {+ return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag);+ }+ var isArray = Array.isArray;+ function isArrayLike(value) {+ return value != null && isLength(value.length) && !isFunction(value);+ }+ function isArrayLikeObject(value) {+ return isObjectLike(value) && isArrayLike(value);+ }+ function isFunction(value) {+ var tag = isObject2(value) ? objectToString.call(value) : "";+ return tag == funcTag || tag == genTag;+ }+ function isLength(value) {+ return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;+ }+ function isObject2(value) {+ var type = typeof value;+ return !!value && (type == "object" || type == "function");+ }+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isString(value) {+ return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag;+ }+ function isSymbol(value) {+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;+ }+ function toFinite(value) {+ if (!value) {+ return value === 0 ? value : 0;+ }+ value = toNumber(value);+ if (value === INFINITY || value === -INFINITY) {+ var sign = value < 0 ? -1 : 1;+ return sign * MAX_INTEGER;+ }+ return value === value ? value : 0;+ }+ function toInteger(value) {+ var result = toFinite(value), remainder = result % 1;+ return result === result ? remainder ? result - remainder : result : 0;+ }+ function toNumber(value) {+ if (typeof value == "number") {+ return value;+ }+ if (isSymbol(value)) {+ return NAN;+ }+ if (isObject2(value)) {+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;+ value = isObject2(other) ? other + "" : other;+ }+ if (typeof value != "string") {+ return value === 0 ? value : +value;+ }+ value = value.replace(reTrim, "");+ var isBinary = reIsBinary.test(value);+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;+ }+ function keys(object3) {+ return isArrayLike(object3) ? arrayLikeKeys(object3) : baseKeys(object3);+ }+ function values(object3) {+ return object3 ? baseValues(object3, keys(object3)) : [];+ }+ module.exports = includes;+ }+});++// node_modules/lodash.isboolean/index.js+var require_lodash2 = __commonJS({+ "node_modules/lodash.isboolean/index.js"(exports, module) {+ var boolTag = "[object Boolean]";+ var objectProto = Object.prototype;+ var objectToString = objectProto.toString;+ function isBoolean(value) {+ return value === true || value === false || isObjectLike(value) && objectToString.call(value) == boolTag;+ }+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ module.exports = isBoolean;+ }+});++// node_modules/lodash.isinteger/index.js+var require_lodash3 = __commonJS({+ "node_modules/lodash.isinteger/index.js"(exports, module) {+ var INFINITY = 1 / 0;+ var MAX_INTEGER = 17976931348623157e292;+ var NAN = 0 / 0;+ var symbolTag = "[object Symbol]";+ var reTrim = /^\s+|\s+$/g;+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;+ var reIsBinary = /^0b[01]+$/i;+ var reIsOctal = /^0o[0-7]+$/i;+ var freeParseInt = parseInt;+ var objectProto = Object.prototype;+ var objectToString = objectProto.toString;+ function isInteger(value) {+ return typeof value == "number" && value == toInteger(value);+ }+ function isObject2(value) {+ var type = typeof value;+ return !!value && (type == "object" || type == "function");+ }+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isSymbol(value) {+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;+ }+ function toFinite(value) {+ if (!value) {+ return value === 0 ? value : 0;+ }+ value = toNumber(value);+ if (value === INFINITY || value === -INFINITY) {+ var sign = value < 0 ? -1 : 1;+ return sign * MAX_INTEGER;+ }+ return value === value ? value : 0;+ }+ function toInteger(value) {+ var result = toFinite(value), remainder = result % 1;+ return result === result ? remainder ? result - remainder : result : 0;+ }+ function toNumber(value) {+ if (typeof value == "number") {+ return value;+ }+ if (isSymbol(value)) {+ return NAN;+ }+ if (isObject2(value)) {+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;+ value = isObject2(other) ? other + "" : other;+ }+ if (typeof value != "string") {+ return value === 0 ? value : +value;+ }+ value = value.replace(reTrim, "");+ var isBinary = reIsBinary.test(value);+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;+ }+ module.exports = isInteger;+ }+});++// node_modules/lodash.isnumber/index.js+var require_lodash4 = __commonJS({+ "node_modules/lodash.isnumber/index.js"(exports, module) {+ var numberTag = "[object Number]";+ var objectProto = Object.prototype;+ var objectToString = objectProto.toString;+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isNumber(value) {+ return typeof value == "number" || isObjectLike(value) && objectToString.call(value) == numberTag;+ }+ module.exports = isNumber;+ }+});++// node_modules/lodash.isplainobject/index.js+var require_lodash5 = __commonJS({+ "node_modules/lodash.isplainobject/index.js"(exports, module) {+ var objectTag = "[object Object]";+ function isHostObject(value) {+ var result = false;+ if (value != null && typeof value.toString != "function") {+ try {+ result = !!(value + "");+ } catch (e) {+ }+ }+ return result;+ }+ function overArg(func, transform2) {+ return function(arg) {+ return func(transform2(arg));+ };+ }+ var funcProto = Function.prototype;+ var objectProto = Object.prototype;+ var funcToString = funcProto.toString;+ var hasOwnProperty = objectProto.hasOwnProperty;+ var objectCtorString = funcToString.call(Object);+ var objectToString = objectProto.toString;+ var getPrototype = overArg(Object.getPrototypeOf, Object);+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isPlainObject4(value) {+ if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) {+ return false;+ }+ var proto = getPrototype(value);+ if (proto === null) {+ return true;+ }+ var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;+ return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;+ }+ module.exports = isPlainObject4;+ }+});++// node_modules/lodash.isstring/index.js+var require_lodash6 = __commonJS({+ "node_modules/lodash.isstring/index.js"(exports, module) {+ var stringTag = "[object String]";+ var objectProto = Object.prototype;+ var objectToString = objectProto.toString;+ var isArray = Array.isArray;+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isString(value) {+ return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag;+ }+ module.exports = isString;+ }+});++// node_modules/lodash.once/index.js+var require_lodash7 = __commonJS({+ "node_modules/lodash.once/index.js"(exports, module) {+ var FUNC_ERROR_TEXT = "Expected a function";+ var INFINITY = 1 / 0;+ var MAX_INTEGER = 17976931348623157e292;+ var NAN = 0 / 0;+ var symbolTag = "[object Symbol]";+ var reTrim = /^\s+|\s+$/g;+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;+ var reIsBinary = /^0b[01]+$/i;+ var reIsOctal = /^0o[0-7]+$/i;+ var freeParseInt = parseInt;+ var objectProto = Object.prototype;+ var objectToString = objectProto.toString;+ function before(n, func) {+ var result;+ if (typeof func != "function") {+ throw new TypeError(FUNC_ERROR_TEXT);+ }+ n = toInteger(n);+ return function() {+ if (--n > 0) {+ result = func.apply(this, arguments);+ }+ if (n <= 1) {+ func = void 0;+ }+ return result;+ };+ }+ function once(func) {+ return before(2, func);+ }+ function isObject2(value) {+ var type = typeof value;+ return !!value && (type == "object" || type == "function");+ }+ function isObjectLike(value) {+ return !!value && typeof value == "object";+ }+ function isSymbol(value) {+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;+ }+ function toFinite(value) {+ if (!value) {+ return value === 0 ? value : 0;+ }+ value = toNumber(value);+ if (value === INFINITY || value === -INFINITY) {+ var sign = value < 0 ? -1 : 1;+ return sign * MAX_INTEGER;+ }+ return value === value ? value : 0;+ }+ function toInteger(value) {+ var result = toFinite(value), remainder = result % 1;+ return result === result ? remainder ? result - remainder : result : 0;+ }+ function toNumber(value) {+ if (typeof value == "number") {+ return value;+ }+ if (isSymbol(value)) {+ return NAN;+ }+ if (isObject2(value)) {+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;+ value = isObject2(other) ? other + "" : other;+ }+ if (typeof value != "string") {+ return value === 0 ? value : +value;+ }+ value = value.replace(reTrim, "");+ var isBinary = reIsBinary.test(value);+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;+ }+ module.exports = once;+ }+});++// node_modules/jsonwebtoken/sign.js+var require_sign = __commonJS({+ "node_modules/jsonwebtoken/sign.js"(exports, module) {+ var timespan = require_timespan();+ var PS_SUPPORTED = require_psSupported();+ var validateAsymmetricKey = require_validateAsymmetricKey();+ var jws = require_jws();+ var includes = require_lodash();+ var isBoolean = require_lodash2();+ var isInteger = require_lodash3();+ var isNumber = require_lodash4();+ var isPlainObject4 = require_lodash5();+ var isString = require_lodash6();+ var once = require_lodash7();+ var { KeyObject, createSecretKey, createPrivateKey } = __require("crypto");+ var SUPPORTED_ALGS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "HS256", "HS384", "HS512", "none"];+ if (PS_SUPPORTED) {+ SUPPORTED_ALGS.splice(3, 0, "PS256", "PS384", "PS512");+ }+ var sign_options_schema = {+ expiresIn: { isValid: function(value) {+ return isInteger(value) || isString(value) && value;+ }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },+ notBefore: { isValid: function(value) {+ return isInteger(value) || isString(value) && value;+ }, message: '"notBefore" should be a number of seconds or string representing a timespan' },+ audience: { isValid: function(value) {+ return isString(value) || Array.isArray(value);+ }, message: '"audience" must be a string or array' },+ algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' },+ header: { isValid: isPlainObject4, message: '"header" must be an object' },+ encoding: { isValid: isString, message: '"encoding" must be a string' },+ issuer: { isValid: isString, message: '"issuer" must be a string' },+ subject: { isValid: isString, message: '"subject" must be a string' },+ jwtid: { isValid: isString, message: '"jwtid" must be a string' },+ noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' },+ keyid: { isValid: isString, message: '"keyid" must be a string' },+ mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' },+ allowInsecureKeySizes: { isValid: isBoolean, message: '"allowInsecureKeySizes" must be a boolean' },+ allowInvalidAsymmetricKeyTypes: { isValid: isBoolean, message: '"allowInvalidAsymmetricKeyTypes" must be a boolean' }+ };+ var registered_claims_schema = {+ iat: { isValid: isNumber, message: '"iat" should be a number of seconds' },+ exp: { isValid: isNumber, message: '"exp" should be a number of seconds' },+ nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' }+ };+ function validate(schema, allowUnknown, object3, parameterName) {+ if (!isPlainObject4(object3)) {+ throw new Error('Expected "' + parameterName + '" to be a plain object.');+ }+ Object.keys(object3).forEach(function(key) {+ const validator = schema[key];+ if (!validator) {+ if (!allowUnknown) {+ throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');+ }+ return;+ }+ if (!validator.isValid(object3[key])) {+ throw new Error(validator.message);+ }+ });+ }+ function validateOptions(options) {+ return validate(sign_options_schema, false, options, "options");+ }+ function validatePayload(payload) {+ return validate(registered_claims_schema, true, payload, "payload");+ }+ var options_to_payload = {+ "audience": "aud",+ "issuer": "iss",+ "subject": "sub",+ "jwtid": "jti"+ };+ var options_for_objects = [+ "expiresIn",+ "notBefore",+ "noTimestamp",+ "audience",+ "issuer",+ "subject",+ "jwtid"+ ];+ module.exports = function(payload, secretOrPrivateKey, options, callback) {+ if (typeof options === "function") {+ callback = options;+ options = {};+ } else {+ options = options || {};+ }+ const isObjectPayload = typeof payload === "object" && !Buffer.isBuffer(payload);+ const header = Object.assign({+ alg: options.algorithm || "HS256",+ typ: isObjectPayload ? "JWT" : void 0,+ kid: options.keyid+ }, options.header);+ function failure(err) {+ if (callback) {+ return callback(err);+ }+ throw err;+ }+ if (!secretOrPrivateKey && options.algorithm !== "none") {+ return failure(new Error("secretOrPrivateKey must have a value"));+ }+ if (secretOrPrivateKey != null && !(secretOrPrivateKey instanceof KeyObject)) {+ try {+ secretOrPrivateKey = createPrivateKey(secretOrPrivateKey);+ } catch (_) {+ try {+ secretOrPrivateKey = createSecretKey(typeof secretOrPrivateKey === "string" ? Buffer.from(secretOrPrivateKey) : secretOrPrivateKey);+ } catch (_2) {+ return failure(new Error("secretOrPrivateKey is not valid key material"));+ }+ }+ }+ if (header.alg.startsWith("HS") && secretOrPrivateKey.type !== "secret") {+ return failure(new Error(`secretOrPrivateKey must be a symmetric key when using ${header.alg}`));+ } else if (/^(?:RS|PS|ES)/.test(header.alg)) {+ if (secretOrPrivateKey.type !== "private") {+ return failure(new Error(`secretOrPrivateKey must be an asymmetric key when using ${header.alg}`));+ }+ if (!options.allowInsecureKeySizes && !header.alg.startsWith("ES") && secretOrPrivateKey.asymmetricKeyDetails !== void 0 && //KeyObject.asymmetricKeyDetails is supported in Node 15++ secretOrPrivateKey.asymmetricKeyDetails.modulusLength < 2048) {+ return failure(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));+ }+ }+ if (typeof payload === "undefined") {+ return failure(new Error("payload is required"));+ } else if (isObjectPayload) {+ try {+ validatePayload(payload);+ } catch (error2) {+ return failure(error2);+ }+ if (!options.mutatePayload) {+ payload = Object.assign({}, payload);+ }+ } else {+ const invalid_options = options_for_objects.filter(function(opt) {+ return typeof options[opt] !== "undefined";+ });+ if (invalid_options.length > 0) {+ return failure(new Error("invalid " + invalid_options.join(",") + " option for " + typeof payload + " payload"));+ }+ }+ if (typeof payload.exp !== "undefined" && typeof options.expiresIn !== "undefined") {+ return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));+ }+ if (typeof payload.nbf !== "undefined" && typeof options.notBefore !== "undefined") {+ return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));+ }+ try {+ validateOptions(options);+ } catch (error2) {+ return failure(error2);+ }+ if (!options.allowInvalidAsymmetricKeyTypes) {+ try {+ validateAsymmetricKey(header.alg, secretOrPrivateKey);+ } catch (error2) {+ return failure(error2);+ }+ }+ const timestamp = payload.iat || Math.floor(Date.now() / 1e3);+ if (options.noTimestamp) {+ delete payload.iat;+ } else if (isObjectPayload) {+ payload.iat = timestamp;+ }+ if (typeof options.notBefore !== "undefined") {+ try {+ payload.nbf = timespan(options.notBefore, timestamp);+ } catch (err) {+ return failure(err);+ }+ if (typeof payload.nbf === "undefined") {+ return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));+ }+ }+ if (typeof options.expiresIn !== "undefined" && typeof payload === "object") {+ try {+ payload.exp = timespan(options.expiresIn, timestamp);+ } catch (err) {+ return failure(err);+ }+ if (typeof payload.exp === "undefined") {+ return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));+ }+ }+ Object.keys(options_to_payload).forEach(function(key) {+ const claim = options_to_payload[key];+ if (typeof options[key] !== "undefined") {+ if (typeof payload[claim] !== "undefined") {+ return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));+ }+ payload[claim] = options[key];+ }+ });+ const encoding = options.encoding || "utf8";+ if (typeof callback === "function") {+ callback = callback && once(callback);+ jws.createSign({+ header,+ privateKey: secretOrPrivateKey,+ payload,+ encoding+ }).once("error", callback).once("done", function(signature) {+ if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {+ return callback(new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`));+ }+ callback(null, signature);+ });+ } else {+ let signature = jws.sign({ header, payload, secret: secretOrPrivateKey, encoding });+ if (!options.allowInsecureKeySizes && /^(?:RS|PS)/.test(header.alg) && signature.length < 256) {+ throw new Error(`secretOrPrivateKey has a minimum key size of 2048 bits for ${header.alg}`);+ }+ return signature;+ }+ };+ }+});++// node_modules/jsonwebtoken/index.js+var require_jsonwebtoken = __commonJS({+ "node_modules/jsonwebtoken/index.js"(exports, module) {+ module.exports = {+ decode: require_decode(),+ verify: require_verify(),+ sign: require_sign(),+ JsonWebTokenError: require_JsonWebTokenError(),+ NotBeforeError: require_NotBeforeError(),+ TokenExpiredError: require_TokenExpiredError()+ };+ }+});++// node_modules/@azure/msal-node/dist/error/ClientAuthErrorCodes.mjs+var userTimeoutReached, invalidAssertion, deviceCodePollingCancelled, deviceCodeExpired, deviceCodeUnknownError;+var init_ClientAuthErrorCodes2 = __esm({+ "node_modules/@azure/msal-node/dist/error/ClientAuthErrorCodes.mjs"() {+ "use strict";+ userTimeoutReached = "user_timeout_reached";+ invalidAssertion = "invalid_assertion";+ deviceCodePollingCancelled = "device_code_polling_cancelled";+ deviceCodeExpired = "device_code_expired";+ deviceCodeUnknownError = "device_code_unknown_error";+ }+});++// node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs+var import_jsonwebtoken, ClientAssertion;+var init_ClientAssertion = __esm({+ "node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs"() {+ "use strict";+ import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1);+ init_index_node();+ init_EncodingUtils();+ init_Constants2();+ init_ClientAuthErrorCodes2();+ ClientAssertion = class _ClientAssertion {+ /**+ * Initialize the ClientAssertion class from the clientAssertion passed by the user+ * @param assertion - refer https://tools.ietf.org/html/rfc7521+ */+ static fromAssertion(assertion) {+ const clientAssertion = new _ClientAssertion();+ clientAssertion.jwt = assertion;+ return clientAssertion;+ }+ /**+ * @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint+ * Initialize the ClientAssertion class from the certificate passed by the user+ * @param thumbprint - identifier of a certificate+ * @param privateKey - secret key+ * @param publicCertificate - electronic document provided to prove the ownership of the public key+ */+ static fromCertificate(thumbprint, privateKey, publicCertificate) {+ const clientAssertion = new _ClientAssertion();+ clientAssertion.privateKey = privateKey;+ clientAssertion.thumbprint = thumbprint;+ clientAssertion.useSha256 = false;+ if (publicCertificate) {+ clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);+ }+ return clientAssertion;+ }+ /**+ * Initialize the ClientAssertion class from the certificate passed by the user+ * @param thumbprint - identifier of a certificate+ * @param privateKey - secret key+ * @param publicCertificate - electronic document provided to prove the ownership of the public key+ */+ static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) {+ const clientAssertion = new _ClientAssertion();+ clientAssertion.privateKey = privateKey;+ clientAssertion.thumbprint = thumbprint;+ clientAssertion.useSha256 = true;+ if (publicCertificate) {+ clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);+ }+ return clientAssertion;+ }+ /**+ * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is+ * @param cryptoProvider - library's crypto helper+ * @param issuer - iss claim+ * @param jwtAudience - aud claim+ */+ getJwt(cryptoProvider, issuer, jwtAudience) {+ if (this.privateKey && this.thumbprint) {+ if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {+ return this.jwt;+ }+ return this.createJwt(cryptoProvider, issuer, jwtAudience);+ }+ if (this.jwt) {+ return this.jwt;+ }+ throw createClientAuthError(invalidAssertion, "");+ }+ /**+ * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3+ */+ createJwt(cryptoProvider, issuer, jwtAudience) {+ this.issuer = issuer;+ this.jwtAudience = jwtAudience;+ const issuedAt = TimeUtils_exports.nowSeconds();+ this.expirationTime = issuedAt + 600;+ const algorithm = this.useSha256 ? JwtConstants.PSS_256 : JwtConstants.RSA_256;+ const header = {+ alg: algorithm+ };+ const thumbprintHeader = this.useSha256 ? JwtConstants.X5T_256 : JwtConstants.X5T;+ Object.assign(header, {+ [thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, Constants_exports.EncodingTypes.HEX)+ });+ if (this.publicCertificate) {+ Object.assign(header, {+ [JwtConstants.X5C]: this.publicCertificate+ });+ }+ const payload = {+ [JwtConstants.AUDIENCE]: this.jwtAudience,+ [JwtConstants.EXPIRATION_TIME]: this.expirationTime,+ [JwtConstants.ISSUER]: this.issuer,+ [JwtConstants.SUBJECT]: this.issuer,+ [JwtConstants.NOT_BEFORE]: issuedAt,+ [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid()+ };+ this.jwt = import_jsonwebtoken.default.sign(payload, this.privateKey, { header });+ return this.jwt;+ }+ /**+ * Utility API to check expiration+ */+ isExpired() {+ return this.expirationTime < TimeUtils_exports.nowSeconds();+ }+ /**+ * Extracts the raw certs from a given certificate string and returns them in an array.+ * @param publicCertificate - electronic document provided to prove the ownership of the public key+ */+ static parseCertificate(publicCertificate) {+ const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;+ const certs = [];+ let matches;+ while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {+ certs.push(matches[1].replace(/\r*\n/g, ""));+ }+ return certs;+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/packageMetadata.mjs+var name2, version3;+var init_packageMetadata2 = __esm({+ "node_modules/@azure/msal-node/dist/packageMetadata.mjs"() {+ "use strict";+ name2 = "@azure/msal-node";+ version3 = "5.3.1";+ }+});++// node_modules/@azure/msal-node/dist/client/BaseClient.mjs+var BaseClient;+var init_BaseClient = __esm({+ "node_modules/@azure/msal-node/dist/client/BaseClient.mjs"() {+ "use strict";+ init_index_node();+ init_packageMetadata2();+ BaseClient = class {+ constructor(configuration) {+ this.config = buildClientConfiguration(configuration);+ this.logger = new Logger(this.config.loggerOptions, name2, version3);+ this.cryptoUtils = this.config.cryptoInterface;+ this.cacheManager = this.config.storageInterface;+ this.networkClient = this.config.networkInterface;+ this.serverTelemetryManager = this.config.serverTelemetryManager;+ this.authority = this.config.authOptions.authority;+ this.performanceClient = new StubPerformanceClient();+ }+ /**+ * Creates default headers for requests to token endpoint+ */+ createTokenRequestHeaders(ccsCred) {+ return Token_exports.createTokenRequestHeaders(this.logger, false, ccsCred);+ }+ /**+ * Http post to token endpoint+ * @param tokenEndpoint+ * @param queryString+ * @param headers+ * @param thumbprint+ */+ async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId) {+ return Token_exports.executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);+ }+ /**+ * Wraps sendPostRequestAsync with necessary preflight and postflight logic+ * @param thumbprint - Request thumbprint for throttling+ * @param tokenEndpoint - Endpoint to make the POST to+ * @param options - Body and Headers to include on the POST request+ * @param correlationId - CorrelationId for telemetry+ */+ async sendPostRequest(thumbprint, tokenEndpoint, options, correlationId) {+ return Token_exports.sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient);+ }+ /**+ * Creates query string for the /token request+ * @param request+ */+ createTokenQueryParameters(request) {+ return Token_exports.createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs+var UsernamePasswordClient;+var init_UsernamePasswordClient = __esm({+ "node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ init_BaseClient();+ UsernamePasswordClient = class extends BaseClient {+ constructor(configuration) {+ super(configuration);+ }+ /**+ * API to acquire a token by passing the username and password to the service in exchage of credentials+ * password_grant+ * @param request - CommonUsernamePasswordRequest+ */+ async acquireToken(request) {+ this.logger.info("in acquireToken call in username-password client", request.correlationId);+ const reqTimestamp = TimeUtils_exports.nowSeconds();+ const response = await this.executeTokenRequest(this.authority, request);+ const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);+ responseHandler.validateTokenResponse(response.body, request.correlationId);+ const tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, ApiId.acquireTokenByUsernamePassword);+ return tokenResponse;+ }+ /**+ * Executes POST request to token endpoint+ * @param authority - authority object+ * @param request - CommonUsernamePasswordRequest provided by the developer+ */+ async executeTokenRequest(authority, request) {+ const queryParametersString = this.createTokenQueryParameters(request);+ const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);+ const requestBody = await this.createTokenRequestBody(request);+ const headers = this.createTokenRequestHeaders({+ credential: request.username,+ type: CcsCredentialType.UPN+ });+ const thumbprint = {+ clientId: this.config.authOptions.clientId,+ authority: authority.canonicalAuthority,+ scopes: request.scopes,+ claims: request.claims,+ authenticationScheme: request.authenticationScheme,+ resourceRequestMethod: request.resourceRequestMethod,+ resourceRequestUri: request.resourceRequestUri,+ shrClaims: request.shrClaims,+ sshKid: request.sshKid+ };+ return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);+ }+ /**+ * Generates a map for all the params to be sent to the service+ * @param request - CommonUsernamePasswordRequest provided by the developer+ */+ async createTokenRequestBody(request) {+ const parameters = /* @__PURE__ */ new Map();+ RequestParameterBuilder_exports.addClientId(parameters, this.config.authOptions.clientId);+ RequestParameterBuilder_exports.addUsername(parameters, request.username);+ RequestParameterBuilder_exports.addPassword(parameters, request.password);+ RequestParameterBuilder_exports.addScopes(parameters, request.scopes, request.correlationId);+ RequestParameterBuilder_exports.addResponseType(parameters, Constants_exports.OAuthResponseType.IDTOKEN_TOKEN);+ RequestParameterBuilder_exports.addGrantType(parameters, Constants_exports.GrantType.RESOURCE_OWNER_PASSWORD_GRANT);+ RequestParameterBuilder_exports.addClientInfo(parameters);+ RequestParameterBuilder_exports.addLibraryInfo(parameters, this.config.libraryInfo);+ RequestParameterBuilder_exports.addApplicationTelemetry(parameters, this.config.telemetry.application);+ RequestParameterBuilder_exports.addThrottling(parameters);+ if (this.serverTelemetryManager) {+ RequestParameterBuilder_exports.addServerTelemetry(parameters, this.serverTelemetryManager);+ }+ const correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();+ RequestParameterBuilder_exports.addCorrelationId(parameters, correlationId);+ if (this.config.clientCredentials.clientSecret) {+ RequestParameterBuilder_exports.addClientSecret(parameters, this.config.clientCredentials.clientSecret);+ }+ const clientAssertion = this.config.clientCredentials.clientAssertion;+ if (clientAssertion) {+ RequestParameterBuilder_exports.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));+ RequestParameterBuilder_exports.addClientAssertionType(parameters, clientAssertion.assertionType);+ }+ if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {+ RequestParameterBuilder_exports.addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities);+ }+ if (this.config.systemOptions.preventCorsPreflight && request.username) {+ RequestParameterBuilder_exports.addCcsUpn(parameters, request.username);+ }+ return UrlUtils_exports.mapToQueryString(parameters);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/protocol/Authorize.mjs+function getAuthCodeRequestUrl(config2, authority, request, logger2) {+ const parameters = Authorize_exports.getStandardAuthorizeRequestParameters({+ ...config2.auth,+ authority,+ redirectUri: request.redirectUri || ""+ }, request, logger2);+ RequestParameterBuilder_exports.addLibraryInfo(parameters, {+ sku: Constants.MSAL_SKU,+ version: version3,+ cpu: process.arch || "",+ os: process.platform || ""+ });+ if (config2.system.protocolMode !== ProtocolMode.OIDC) {+ RequestParameterBuilder_exports.addApplicationTelemetry(parameters, config2.telemetry.application);+ }+ RequestParameterBuilder_exports.addResponseType(parameters, Constants_exports.OAuthResponseType.CODE);+ if (request.codeChallenge && request.codeChallengeMethod) {+ RequestParameterBuilder_exports.addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod);+ }+ RequestParameterBuilder_exports.addExtraParameters(parameters, request.extraQueryParameters || {});+ return Authorize_exports.getAuthorizeUrl(authority, parameters);+}+var init_Authorize2 = __esm({+ "node_modules/@azure/msal-node/dist/protocol/Authorize.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ init_packageMetadata2();+ }+});++// node_modules/@azure/msal-node/dist/client/ClientApplication.mjs+var ClientApplication;+var init_ClientApplication = __esm({+ "node_modules/@azure/msal-node/dist/client/ClientApplication.mjs"() {+ "use strict";+ init_index_node();+ init_Configuration();+ init_CryptoProvider();+ init_NodeStorage();+ init_Constants2();+ init_TokenCache();+ init_ClientAssertion();+ init_packageMetadata2();+ init_NodeAuthError();+ init_UsernamePasswordClient();+ init_Authorize2();+ ClientApplication = class {+ /**+ * Constructor for the ClientApplication+ */+ constructor(configuration) {+ this.config = buildAppConfiguration(configuration);+ this.cryptoProvider = new CryptoProvider();+ this.logger = new Logger(this.config.system.loggerOptions, name2, version3);+ this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth));+ this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin);+ }+ /**+ * Creates the URL of the authorization request, letting the user input credentials and consent to the+ * application. The URL targets the /authorize endpoint of the authority configured in the+ * application object.+ *+ * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI+ * sent in the request and should contain an authorization code, which can then be used to acquire tokens via+ * `acquireTokenByCode(AuthorizationCodeRequest)`.+ */+ async getAuthCodeUrl(request) {+ this.logger.info("getAuthCodeUrl called", request.correlationId || "");+ const validRequest = {+ ...request,+ ...await this.initializeBaseRequest(request),+ responseMode: request.responseMode || Constants_exports.ResponseMode.QUERY,+ authenticationScheme: Constants_exports.AuthenticationScheme.BEARER,+ state: request.state || "",+ nonce: request.nonce || ""+ };+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ return getAuthCodeRequestUrl(this.config, discoveredAuthority, validRequest, this.logger);+ }+ /**+ * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0+ * Authorization Code flow.+ *+ * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0+ * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and+ * AuthorizationCodeRequest are the same.+ */+ async acquireTokenByCode(request, authCodePayLoad) {+ this.logger.info("acquireTokenByCode called", request.correlationId || "");+ if (request.state && authCodePayLoad) {+ this.logger.info("acquireTokenByCode - validating state", request.correlationId || "");+ this.validateState(request.state, authCodePayLoad.state || "", request.correlationId || "");+ authCodePayLoad = { ...authCodePayLoad, state: "" };+ }+ const validRequest = {+ ...request,+ ...await this.initializeBaseRequest(request),+ authenticationScheme: Constants_exports.AuthenticationScheme.BEARER+ };+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);+ try {+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ const authClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager);+ const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig, new StubPerformanceClient());+ this.logger.verbose("Auth code client created", validRequest.correlationId);+ return await authorizationCodeClient.acquireToken(validRequest, ApiId.acquireTokenByCode, authCodePayLoad);+ } catch (e) {+ if (e instanceof AuthError) {+ e.correlationId = validRequest.correlationId;+ }+ serverTelemetryManager.cacheFailedRequest(e);+ throw e;+ }+ }+ /**+ * Acquires a token by exchanging the refresh token provided for a new set of tokens.+ *+ * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is+ * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will+ * handle the caching and refreshing of tokens automatically.+ */+ async acquireTokenByRefreshToken(request) {+ this.logger.info("acquireTokenByRefreshToken called", request.correlationId || "");+ const validRequest = {+ ...request,+ ...await this.initializeBaseRequest(request),+ authenticationScheme: Constants_exports.AuthenticationScheme.BEARER+ };+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);+ try {+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ const refreshTokenClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager);+ const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig, new StubPerformanceClient());+ this.logger.verbose("Refresh token client created", validRequest.correlationId);+ return await refreshTokenClient.acquireToken(validRequest, ApiId.acquireTokenByRefreshToken);+ } catch (e) {+ if (e instanceof AuthError) {+ e.correlationId = validRequest.correlationId;+ }+ serverTelemetryManager.cacheFailedRequest(e);+ throw e;+ }+ }+ /**+ * Acquires a token silently when a user specifies the account the token is requested for.+ *+ * This API expects the user to provide an account object and looks into the cache to retrieve the token if present.+ * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token.+ * In case the refresh_token is expired or not found, an error is thrown+ * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).+ */+ async acquireTokenSilent(request) {+ const validRequest = {+ ...request,+ ...await this.initializeBaseRequest(request),+ forceRefresh: request.forceRefresh || false+ };+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);+ try {+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ const clientConfiguration = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager);+ const silentFlowClient = new SilentFlowClient(clientConfiguration, new StubPerformanceClient());+ this.logger.verbose("Silent flow client created", validRequest.correlationId);+ try {+ await this.tokenCache.overwriteCache();+ return await this.acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration);+ } catch (error2) {+ if (error2 instanceof ClientAuthError && error2.errorCode === ClientAuthErrorCodes_exports.tokenRefreshRequired) {+ const refreshTokenClient = new RefreshTokenClient(clientConfiguration, new StubPerformanceClient());+ return refreshTokenClient.acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);+ }+ throw error2;+ }+ } catch (error2) {+ if (error2 instanceof AuthError) {+ error2.correlationId = validRequest.correlationId;+ }+ serverTelemetryManager.cacheFailedRequest(error2);+ throw error2;+ }+ }+ async acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration) {+ const [authResponse, cacheOutcome] = await silentFlowClient.acquireCachedToken({+ ...validRequest,+ scopes: validRequest.scopes?.length ? validRequest.scopes : [...Constants_exports.OIDC_DEFAULT_SCOPES]+ });+ if (cacheOutcome === Constants_exports.CacheOutcome.PROACTIVELY_REFRESHED) {+ this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.", validRequest.correlationId);+ const refreshTokenClient = new RefreshTokenClient(clientConfiguration, new StubPerformanceClient());+ try {+ await refreshTokenClient.acquireTokenByRefreshToken(validRequest, ApiId.acquireTokenSilent);+ } catch {+ }+ }+ return authResponse;+ }+ /**+ * Acquires tokens with password grant by exchanging client applications username and password for credentials+ *+ * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely.+ * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4+ * Microsoft's documentation and recommendations are at:+ * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword+ *+ * @param request - UsenamePasswordRequest+ * @deprecated - Use a more secure flow instead+ */+ async acquireTokenByUsernamePassword(request) {+ this.logger.info("acquireTokenByUsernamePassword called", request.correlationId || "");+ const validRequest = {+ ...request,+ ...await this.initializeBaseRequest(request)+ };+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);+ try {+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager);+ const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig);+ this.logger.verbose("Username password client created", validRequest.correlationId);+ return await usernamePasswordClient.acquireToken(validRequest);+ } catch (e) {+ if (e instanceof AuthError) {+ e.correlationId = validRequest.correlationId;+ }+ serverTelemetryManager.cacheFailedRequest(e);+ throw e;+ }+ }+ /**+ * Gets the token cache for the application.+ */+ getTokenCache() {+ this.logger.info("getTokenCache called", "");+ return this.tokenCache;+ }+ /**+ * Validates OIDC state by comparing the user cached state with the state received from the server.+ *+ * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against+ * CSRF attacks.+ * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6.+ * @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow+ * @param cachedState - This string is sent back by the server with the authorization code+ */+ validateState(state, cachedState, correlationId) {+ if (!state) {+ throw NodeAuthError.createStateNotFoundError(correlationId);+ }+ if (state !== cachedState) {+ throw createClientAuthError(ClientAuthErrorCodes_exports.stateMismatch, correlationId);+ }+ }+ /**+ * Returns the logger instance+ */+ getLogger() {+ return this.logger;+ }+ /**+ * Replaces the default logger set in configurations with new Logger with new configurations+ * @param logger - Logger instance+ */+ setLogger(logger2) {+ this.logger = logger2;+ }+ /**+ * Builds the common configuration to be passed to the common component based on the platform configurarion+ * @param authority - user passed authority in configuration+ * @param serverTelemetryManager - initializes servertelemetry if passed+ */+ async buildOauthClientConfiguration(discoveredAuthority, requestCorrelationId, redirectUri, serverTelemetryManager) {+ this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);+ this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId);+ serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);+ const clientConfiguration = {+ authOptions: {+ clientId: this.config.auth.clientId,+ authority: discoveredAuthority,+ clientCapabilities: this.config.auth.clientCapabilities,+ redirectUri,+ isMcp: this.config.auth.isMcp+ },+ loggerOptions: {+ logLevel: this.config.system.loggerOptions.logLevel,+ loggerCallback: this.config.system.loggerOptions.loggerCallback,+ piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled,+ correlationId: requestCorrelationId+ },+ cryptoInterface: this.cryptoProvider,+ networkInterface: this.config.system.networkClient,+ storageInterface: this.storage,+ serverTelemetryManager,+ clientCredentials: {+ clientSecret: this.clientSecret,+ clientAssertion: await this.getClientAssertion(discoveredAuthority)+ },+ libraryInfo: {+ sku: Constants.MSAL_SKU,+ version: version3,+ cpu: process.arch || "",+ os: process.platform || ""+ },+ telemetry: this.config.telemetry,+ persistencePlugin: this.config.cache.cachePlugin,+ serializableCache: this.tokenCache+ };+ return clientConfiguration;+ }+ async getClientAssertion(authority) {+ if (this.developerProvidedClientAssertion) {+ this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint));+ }+ return this.clientAssertion && {+ assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),+ assertionType: Constants.JWT_BEARER_ASSERTION_TYPE+ };+ }+ /**+ * Generates a request with the default scopes & generates a correlationId.+ * @param authRequest - BaseAuthRequest for initialization+ */+ async initializeBaseRequest(authRequest) {+ const correlationId = authRequest.correlationId || this.cryptoProvider.createNewGuid();+ this.logger.verbose("initializeRequestScopes called", correlationId);+ if (authRequest.authenticationScheme && authRequest.authenticationScheme === Constants_exports.AuthenticationScheme.POP) {+ this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", correlationId);+ }+ authRequest.authenticationScheme = Constants_exports.AuthenticationScheme.BEARER;+ return {+ ...authRequest,+ scopes: [+ ...authRequest && authRequest.scopes || [],+ ...Constants_exports.OIDC_DEFAULT_SCOPES+ ],+ correlationId,+ authority: authRequest.authority || this.config.auth.authority+ };+ }+ /**+ * Initializes the server telemetry payload+ * @param apiId - Id for a specific request+ * @param correlationId - GUID+ * @param forceRefresh - boolean to indicate network call+ */+ initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {+ const telemetryPayload = {+ clientId: this.config.auth.clientId,+ correlationId,+ apiId,+ forceRefresh: forceRefresh || false+ };+ return new ServerTelemetryManager(telemetryPayload, this.storage);+ }+ /**+ * Create authority instance. If authority not passed in request, default to authority set on the application+ * object. If no authority set in application object, then default to common authority.+ * @param authorityString - authority from user configuration+ */+ async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) {+ this.logger.verbose("createAuthority called", requestCorrelationId);+ const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions || this.config.auth.azureCloudOptions);+ const authorityOptions = {+ protocolMode: this.config.system.protocolMode,+ knownAuthorities: this.config.auth.knownAuthorities,+ cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,+ authorityMetadata: this.config.auth.authorityMetadata,+ azureRegionConfiguration+ };+ return AuthorityFactory_exports.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId, new StubPerformanceClient());+ }+ /**+ * Clear the cache except for authority metadata.+ */+ clearCache() {+ this.storage.clear();+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs+import http from "http";+var LoopbackClient;+var init_LoopbackClient = __esm({+ "node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs"() {+ "use strict";+ init_index_node();+ init_NodeAuthError();+ init_Constants2();+ LoopbackClient = class {+ /**+ * Spins up a loopback server which returns the server response when the localhost redirectUri is hit+ * @param successTemplate+ * @param errorTemplate+ * @returns+ */+ async listenForAuthCode(successTemplate, errorTemplate) {+ if (this.server) {+ throw NodeAuthError.createLoopbackServerAlreadyExistsError();+ }+ return new Promise((resolve2, reject) => {+ this.server = http.createServer((req, res) => {+ const url = req.url;+ if (!url) {+ res.end(errorTemplate || "Error occurred loading redirectUrl");+ reject(NodeAuthError.createUnableToLoadRedirectUrlError());+ return;+ } else if (url === Constants_exports.FORWARD_SLASH) {+ res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");+ return;+ }+ const redirectUri = this.getRedirectUri();+ const parsedUrl = new URL(url, redirectUri);+ const authCodeResponse = UrlUtils_exports.getDeserializedResponse(parsedUrl.search) || {};+ if (authCodeResponse.code) {+ res.writeHead(Constants_exports.HTTP_REDIRECT, {+ location: redirectUri+ });+ res.end();+ }+ if (authCodeResponse.error) {+ res.end(errorTemplate || `Error occurred: ${authCodeResponse.error}`);+ }+ resolve2(authCodeResponse);+ });+ this.server.listen(0, "127.0.0.1");+ });+ }+ /**+ * Get the port that the loopback server is running on+ * @returns+ */+ getRedirectUri() {+ if (!this.server || !this.server.listening) {+ throw NodeAuthError.createNoLoopbackServerExistsError();+ }+ const address = this.server.address();+ if (!address || typeof address === "string" || !address.port) {+ this.closeServer();+ throw NodeAuthError.createInvalidLoopbackAddressTypeError();+ }+ const port = address && address.port;+ return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;+ }+ /**+ * Close the loopback server+ */+ closeServer() {+ if (this.server) {+ this.server.close();+ if (typeof this.server.closeAllConnections === "function") {+ this.server.closeAllConnections();+ }+ this.server.unref();+ this.server = void 0;+ }+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs+var DeviceCodeClient;+var init_DeviceCodeClient = __esm({+ "node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ init_ClientAuthErrorCodes2();+ init_BaseClient();+ DeviceCodeClient = class extends BaseClient {+ constructor(configuration) {+ super(configuration);+ }+ /**+ * Gets device code from device code endpoint, calls back to with device code response, and+ * polls token endpoint to exchange device code for tokens+ * @param request - developer provided CommonDeviceCodeRequest+ */+ async acquireToken(request) {+ const deviceCodeResponse = await this.getDeviceCode(request);+ request.deviceCodeCallback(deviceCodeResponse);+ const reqTimestamp = TimeUtils_exports.nowSeconds();+ const response = await this.acquireTokenWithDeviceCode(request, deviceCodeResponse);+ const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin);+ responseHandler.validateTokenResponse(response, request.correlationId);+ return responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request, ApiId.acquireTokenByDeviceCode);+ }+ /**+ * Creates device code request and executes http GET+ * @param request - developer provided CommonDeviceCodeRequest+ */+ async getDeviceCode(request) {+ const queryParametersString = this.createExtraQueryParameters(request);+ const endpoint = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString);+ const queryString = this.createQueryString(request);+ const headers = this.createTokenRequestHeaders();+ const thumbprint = {+ clientId: this.config.authOptions.clientId,+ authority: request.authority,+ scopes: request.scopes,+ claims: request.claims,+ authenticationScheme: request.authenticationScheme,+ resourceRequestMethod: request.resourceRequestMethod,+ resourceRequestUri: request.resourceRequestUri,+ shrClaims: request.shrClaims,+ sshKid: request.sshKid+ };+ return this.executePostRequestToDeviceCodeEndpoint(endpoint, queryString, headers, thumbprint, request.correlationId);+ }+ /**+ * Creates query string for the device code request+ * @param request - developer provided CommonDeviceCodeRequest+ */+ createExtraQueryParameters(request) {+ const parameters = /* @__PURE__ */ new Map();+ if (request.extraQueryParameters) {+ RequestParameterBuilder_exports.addExtraParameters(parameters, request.extraQueryParameters);+ }+ return UrlUtils_exports.mapToQueryString(parameters);+ }+ /**+ * Executes POST request to device code endpoint+ * @param deviceCodeEndpoint - token endpoint+ * @param queryString - string to be used in the body of the request+ * @param headers - headers for the request+ * @param thumbprint - unique request thumbprint+ * @param correlationId - correlation id to be used in the request+ */+ async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) {+ const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message } } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, {+ body: queryString,+ headers+ }, correlationId);+ return {+ userCode,+ deviceCode,+ verificationUri,+ expiresIn,+ interval,+ message+ };+ }+ /**+ * Create device code endpoint query parameters and returns string+ * @param request - developer provided CommonDeviceCodeRequest+ */+ createQueryString(request) {+ const parameters = /* @__PURE__ */ new Map();+ RequestParameterBuilder_exports.addScopes(parameters, request.scopes, request.correlationId);+ RequestParameterBuilder_exports.addClientId(parameters, this.config.authOptions.clientId);+ if (request.extraQueryParameters) {+ RequestParameterBuilder_exports.addExtraParameters(parameters, request.extraQueryParameters);+ }+ if (request.claims || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {+ RequestParameterBuilder_exports.addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities);+ }+ return UrlUtils_exports.mapToQueryString(parameters);+ }+ /**+ * Breaks the polling with specific conditions+ * @param deviceCodeExpirationTime - expiration time for the device code request+ * @param correlationId - correlation id of the request+ * @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime+ * @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request+ */+ continuePolling(deviceCodeExpirationTime, correlationId, userSpecifiedTimeout, userSpecifiedCancelFlag) {+ if (userSpecifiedCancelFlag) {+ this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true", correlationId);+ throw createClientAuthError(deviceCodePollingCancelled, correlationId);+ } else if (userSpecifiedTimeout && userSpecifiedTimeout < deviceCodeExpirationTime && TimeUtils_exports.nowSeconds() > userSpecifiedTimeout) {+ this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`, correlationId);+ throw createClientAuthError(userTimeoutReached, correlationId);+ } else if (TimeUtils_exports.nowSeconds() > deviceCodeExpirationTime) {+ if (userSpecifiedTimeout) {+ this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`, correlationId);+ }+ this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`, correlationId);+ throw createClientAuthError(deviceCodeExpired, correlationId);+ }+ return true;+ }+ /**+ * Creates token request with device code response and polls token endpoint at interval set by the device code response+ * @param request - developer provided CommonDeviceCodeRequest+ * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint+ */+ async acquireTokenWithDeviceCode(request, deviceCodeResponse) {+ const queryParametersString = this.createTokenQueryParameters(request);+ const endpoint = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString);+ const requestBody = this.createTokenRequestBody(request, deviceCodeResponse);+ const headers = this.createTokenRequestHeaders();+ const userSpecifiedTimeout = request.timeout ? TimeUtils_exports.nowSeconds() + request.timeout : void 0;+ const deviceCodeExpirationTime = TimeUtils_exports.nowSeconds() + deviceCodeResponse.expiresIn;+ const pollingIntervalMilli = deviceCodeResponse.interval * 1e3;+ while (this.continuePolling(deviceCodeExpirationTime, request.correlationId, userSpecifiedTimeout, request.cancel)) {+ const thumbprint = {+ clientId: this.config.authOptions.clientId,+ authority: request.authority,+ scopes: request.scopes,+ claims: request.claims,+ authenticationScheme: request.authenticationScheme,+ resourceRequestMethod: request.resourceRequestMethod,+ resourceRequestUri: request.resourceRequestUri,+ shrClaims: request.shrClaims,+ sshKid: request.sshKid+ };+ const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId);+ if (response.body && response.body.error) {+ if (response.body.error === Constants_exports.AUTHORIZATION_PENDING) {+ this.logger.info("Authorization pending. Continue polling.", request.correlationId);+ await TimeUtils_exports.delay(pollingIntervalMilli);+ } else {+ this.logger.info("Unexpected error in polling from the server", request.correlationId);+ throw createAuthError(AuthErrorCodes_exports.postRequestFailed, request.correlationId, response.body.error);+ }+ } else {+ this.logger.verbose("Authorization completed successfully. Polling stopped.", request.correlationId);+ return response.body;+ }+ }+ this.logger.error("Polling stopped for unknown reasons.", request.correlationId);+ throw createClientAuthError(deviceCodeUnknownError, request.correlationId);+ }+ /**+ * Creates query parameters and converts to string.+ * @param request - developer provided CommonDeviceCodeRequest+ * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint+ */+ createTokenRequestBody(request, deviceCodeResponse) {+ const parameters = /* @__PURE__ */ new Map();+ RequestParameterBuilder_exports.addScopes(parameters, request.scopes, request.correlationId);+ RequestParameterBuilder_exports.addClientId(parameters, this.config.authOptions.clientId);+ RequestParameterBuilder_exports.addGrantType(parameters, Constants_exports.GrantType.DEVICE_CODE_GRANT);+ RequestParameterBuilder_exports.addDeviceCode(parameters, deviceCodeResponse.deviceCode);+ const correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();+ RequestParameterBuilder_exports.addCorrelationId(parameters, correlationId);+ RequestParameterBuilder_exports.addClientInfo(parameters);+ RequestParameterBuilder_exports.addLibraryInfo(parameters, this.config.libraryInfo);+ RequestParameterBuilder_exports.addApplicationTelemetry(parameters, this.config.telemetry.application);+ RequestParameterBuilder_exports.addThrottling(parameters);+ if (this.serverTelemetryManager) {+ RequestParameterBuilder_exports.addServerTelemetry(parameters, this.serverTelemetryManager);+ }+ if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {+ RequestParameterBuilder_exports.addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities);+ }+ return UrlUtils_exports.mapToQueryString(parameters);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs+var PublicClientApplication;+var init_PublicClientApplication = __esm({+ "node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs"() {+ "use strict";+ init_Constants2();+ init_index_node();+ init_ClientApplication();+ init_NodeAuthError();+ init_LoopbackClient();+ init_DeviceCodeClient();+ init_packageMetadata2();+ PublicClientApplication = class extends ClientApplication {+ /**+ * Important attributes in the Configuration object for auth are:+ * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal.+ * - authority: the authority URL for your application.+ *+ * AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}.+ * - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).+ * - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.+ * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.+ * - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.+ *+ * Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered+ * its own authority. You will have to set the all of the knownAuthorities at the time of the client application+ * construction.+ *+ * ADFS authorities are of the form https://\{instance\}/adfs.+ */+ constructor(configuration) {+ super(configuration);+ if (this.config.broker.nativeBrokerPlugin) {+ if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) {+ this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin;+ this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions);+ } else {+ this.logger.warning("NativeBroker implementation was provided but the broker is unavailable.", "");+ }+ }+ this.skus = ServerTelemetryManager.makeExtraSkuString({+ libraryName: Constants.MSAL_SKU,+ libraryVersion: version3+ });+ }+ /**+ * Acquires a token from the authority using OAuth2.0 device code flow.+ * This flow is designed for devices that do not have access to a browser or have input constraints.+ * The authorization server issues a DeviceCode object with a verification code, an end-user code,+ * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be+ * instructed to use another device to navigate to the verification URI to input credentials.+ * Since the client cannot receive incoming requests, it polls the authorization server repeatedly+ * until the end-user completes input of credentials.+ */+ async acquireTokenByDeviceCode(request) {+ this.logger.info("acquireTokenByDeviceCode called", request.correlationId || "");+ enforceResourceParameter(this.config.auth.isMcp, request);+ const validRequest = Object.assign(request, await this.initializeBaseRequest(request));+ const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);+ try {+ const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, void 0, request.azureCloudOptions);+ const deviceCodeConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager);+ const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig);+ this.logger.verbose("Device code client created", validRequest.correlationId);+ return await deviceCodeClient.acquireToken(validRequest);+ } catch (e) {+ if (e instanceof AuthError) {+ e.correlationId = validRequest.correlationId;+ }+ serverTelemetryManager.cacheFailedRequest(e);+ throw e;+ }+ }+ /**+ * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token.+ */+ async acquireTokenInteractive(request) {+ const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();+ this.logger.trace("acquireTokenInteractive called", correlationId);+ enforceResourceParameter(this.config.auth.isMcp, request);+ const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request;+ if (this.nativeBrokerPlugin) {+ const brokerRequest = {+ ...remainingProperties,+ clientId: this.config.auth.clientId,+ scopes: request.scopes || Constants_exports.OIDC_DEFAULT_SCOPES,+ redirectUri: request.redirectUri || "",+ authority: request.authority || this.config.auth.authority,+ correlationId,+ extraParameters: {+ ...remainingProperties.extraQueryParameters,+ ...remainingProperties.extraParameters,+ [AADServerParamKeys_exports.X_CLIENT_EXTRA_SKU]: this.skus+ },+ accountId: remainingProperties.account?.nativeAccountId+ };+ return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle);+ }+ if (request.redirectUri) {+ if (!this.config.broker.nativeBrokerPlugin) {+ throw NodeAuthError.createRedirectUriNotSupportedError(correlationId);+ }+ request.redirectUri = "";+ }+ const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();+ const loopbackClient = customLoopbackClient || new LoopbackClient();+ let authCodeResponse = {};+ let authCodeListenerError = null;+ try {+ const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate).then((response) => {+ authCodeResponse = response;+ }).catch((e) => {+ authCodeListenerError = e;+ });+ const redirectUri = await this.waitForRedirectUri(loopbackClient, correlationId);+ const validRequest = {+ ...remainingProperties,+ correlationId,+ scopes: request.scopes || Constants_exports.OIDC_DEFAULT_SCOPES,+ redirectUri,+ responseMode: Constants_exports.ResponseMode.QUERY,+ codeChallenge: challenge,+ codeChallengeMethod: Constants_exports.CodeChallengeMethodValues.S256+ };+ const authCodeUrl = await this.getAuthCodeUrl(validRequest);+ await openBrowser(authCodeUrl);+ await authCodeListener;+ if (authCodeListenerError) {+ throw authCodeListenerError;+ }+ if (authCodeResponse.error) {+ throw new ServerError(authCodeResponse.error, correlationId, authCodeResponse.error_description, authCodeResponse.suberror);+ } else if (!authCodeResponse.code) {+ throw NodeAuthError.createNoAuthCodeInResponseError(correlationId);+ }+ const clientInfo = authCodeResponse.client_info;+ const tokenRequest = {+ code: authCodeResponse.code,+ codeVerifier: verifier,+ clientInfo: clientInfo || "",+ ...validRequest+ };+ return await this.acquireTokenByCode(tokenRequest);+ } finally {+ loopbackClient.closeServer();+ }+ }+ /**+ * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker.+ * @param request - developer provided SilentFlowRequest+ * @returns+ */+ async acquireTokenSilent(request) {+ const correlationId = request.correlationId || this.cryptoProvider.createNewGuid();+ this.logger.trace("acquireTokenSilent called", correlationId);+ enforceResourceParameter(this.config.auth.isMcp, request);+ if (this.nativeBrokerPlugin) {+ const brokerRequest = {+ ...request,+ clientId: this.config.auth.clientId,+ scopes: request.scopes || Constants_exports.OIDC_DEFAULT_SCOPES,+ redirectUri: request.redirectUri || "",+ authority: request.authority || this.config.auth.authority,+ correlationId,+ extraParameters: {+ ...request.extraQueryParameters,+ ...request.extraParameters,+ [AADServerParamKeys_exports.X_CLIENT_EXTRA_SKU]: this.skus+ },+ accountId: request.account.nativeAccountId,+ forceRefresh: request.forceRefresh || false+ };+ return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest);+ }+ if (request.redirectUri) {+ if (!this.config.broker.nativeBrokerPlugin) {+ throw NodeAuthError.createRedirectUriNotSupportedError(correlationId);+ }+ request.redirectUri = "";+ }+ return super.acquireTokenSilent(request);+ }+ /**+ * Acquires a token by exchanging the authorization code received from the first step of OAuth 2.0 Authorization Code Flow.+ * In MCP mode, a resource parameter is required on the request.+ */+ async acquireTokenByCode(request, authCodePayLoad) {+ enforceResourceParameter(this.config.auth.isMcp, request);+ return super.acquireTokenByCode(request, authCodePayLoad);+ }+ /**+ * Acquires a token by exchanging the refresh token provided for a new set of tokens.+ * In MCP mode, a resource parameter is required on the request.+ */+ async acquireTokenByRefreshToken(request) {+ enforceResourceParameter(this.config.auth.isMcp, request);+ return super.acquireTokenByRefreshToken(request);+ }+ /**+ * Removes cache artifacts associated with the given account+ * @param request - developer provided SignOutRequest+ * @returns+ */+ async signOut(request) {+ if (this.nativeBrokerPlugin && request.account.nativeAccountId) {+ const signoutRequest = {+ clientId: this.config.auth.clientId,+ accountId: request.account.nativeAccountId,+ correlationId: request.correlationId || this.cryptoProvider.createNewGuid()+ };+ await this.nativeBrokerPlugin.signOut(signoutRequest);+ }+ await this.getTokenCache().removeAccount(request.account, request.correlationId);+ }+ /**+ * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker.+ * @returns+ */+ async getAllAccounts() {+ if (this.nativeBrokerPlugin) {+ const correlationId = this.cryptoProvider.createNewGuid();+ return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId);+ }+ return this.getTokenCache().getAllAccounts();+ }+ /**+ * Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.+ * @param loopbackClient - developer provided custom loopback server implementation+ * @param correlationId - correlation id of the request+ * @returns+ */+ async waitForRedirectUri(loopbackClient, correlationId) {+ return new Promise((resolve2, reject) => {+ let ticks = 0;+ const id = setInterval(() => {+ if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {+ clearInterval(id);+ reject(NodeAuthError.createLoopbackServerTimeoutError(correlationId));+ return;+ }+ try {+ const r = loopbackClient.getRedirectUri();+ clearInterval(id);+ resolve2(r);+ return;+ } catch (e) {+ if (e instanceof AuthError && e.errorCode === NodeAuthErrorMessage.noLoopbackServerExists.code) {+ ticks++;+ return;+ }+ clearInterval(id);+ reject(e);+ return;+ }+ }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);+ });+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs+var init_ClientCredentialClient = __esm({+ "node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs"() {+ "use strict";+ init_Constants2();+ init_BaseClient();+ }+});++// node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs+var init_OnBehalfOfClient = __esm({+ "node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs"() {+ "use strict";+ init_Constants2();+ init_EncodingUtils();+ init_BaseClient();+ }+});++// node_modules/@azure/msal-node/dist/client/UserFederatedIdentityCredentialClient.mjs+var init_UserFederatedIdentityCredentialClient = __esm({+ "node_modules/@azure/msal-node/dist/client/UserFederatedIdentityCredentialClient.mjs"() {+ "use strict";+ init_Constants2();+ init_BaseClient();+ }+});++// node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs+var init_ConfidentialClientApplication = __esm({+ "node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs"() {+ "use strict";+ init_ClientApplication();+ init_ClientAssertion();+ init_Constants2();+ init_ClientCredentialClient();+ init_OnBehalfOfClient();+ init_UserFederatedIdentityCredentialClient();+ init_ClientAuthErrorCodes2();+ }+});++// node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs+function isIso8601(dateString) {+ if (typeof dateString !== "string") {+ return false;+ }+ const date3 = new Date(dateString);+ return !isNaN(date3.getTime()) && date3.toISOString() === dateString;+}+var init_TimeUtils2 = __esm({+ "node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs+var HttpClientWithRetries;+var init_HttpClientWithRetries = __esm({+ "node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ HttpClientWithRetries = class {+ constructor(httpClientNoRetries, retryPolicy, logger2) {+ this.httpClientNoRetries = httpClientNoRetries;+ this.retryPolicy = retryPolicy;+ this.logger = logger2;+ }+ async sendNetworkRequestAsyncHelper(httpMethod, url, options) {+ if (httpMethod === HttpMethod2.GET) {+ return this.httpClientNoRetries.sendGetRequestAsync(url, options);+ } else {+ return this.httpClientNoRetries.sendPostRequestAsync(url, options);+ }+ }+ async sendNetworkRequestAsync(httpMethod, url, options) {+ let response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options);+ if ("isNewRequest" in this.retryPolicy) {+ this.retryPolicy.isNewRequest = true;+ }+ let currentRetry = 0;+ while (await this.retryPolicy.pauseForRetry(response.status, currentRetry, this.logger, response.headers[Constants_exports.HeaderNames.RETRY_AFTER])) {+ response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options);+ currentRetry++;+ }+ return response;+ }+ async sendGetRequestAsync(url, options) {+ return this.sendNetworkRequestAsync(HttpMethod2.GET, url, options);+ }+ async sendPostRequestAsync(url, options) {+ return this.sendNetworkRequestAsync(HttpMethod2.POST, url, options);+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs+var ManagedIdentityUserAssignedIdQueryParameterNames, BaseManagedIdentitySource;+var init_BaseManagedIdentitySource = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs"() {+ "use strict";+ init_index_node();+ init_Constants2();+ init_ManagedIdentityError();+ init_TimeUtils2();+ init_HttpClientWithRetries();+ init_ManagedIdentityErrorCodes();+ ManagedIdentityUserAssignedIdQueryParameterNames = {+ MANAGED_IDENTITY_CLIENT_ID_2017: "clientid",+ MANAGED_IDENTITY_CLIENT_ID: "client_id",+ MANAGED_IDENTITY_OBJECT_ID: "object_id",+ MANAGED_IDENTITY_RESOURCE_ID_IMDS: "msi_res_id",+ MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS: "mi_res_id"+ };+ BaseManagedIdentitySource = class {+ /**+ * Creates an instance of BaseManagedIdentitySource.+ *+ * @param logger - Logger instance for diagnostic information+ * @param nodeStorage - Storage interface for caching tokens+ * @param networkClient - Network client for making HTTP requests+ * @param cryptoProvider - Cryptographic provider for token operations+ * @param disableInternalRetries - Whether to disable automatic retry logic+ */+ constructor(logger2, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) {+ this.logger = logger2;+ this.nodeStorage = nodeStorage;+ this.networkClient = networkClient;+ this.cryptoProvider = cryptoProvider;+ this.disableInternalRetries = disableInternalRetries;+ }+ /**+ * Generates a new correlation ID for request tracing.+ *+ * @returns A new GUID string for use as a correlation or request ID+ */+ createCorrelationId() {+ return this.cryptoProvider.createNewGuid();+ }+ /**+ * Processes the network response and converts it to a standardized server token response.+ * This async version allows for source-specific response processing logic while maintaining+ * backward compatibility with the synchronous version.+ *+ * @param response - The network response containing the managed identity token+ * @param _networkClient - Network client used for the request (unused in base implementation)+ * @param _networkRequest - The original network request parameters (unused in base implementation)+ * @param _networkRequestOptions - The network request options (unused in base implementation)+ *+ * @returns Promise resolving to a standardized server authorization token response+ */+ async getServerTokenResponseAsync(response, _networkClient, _networkRequest, _networkRequestOptions) {+ return this.getServerTokenResponse(response);+ }+ /**+ * Converts a managed identity token response to a standardized server authorization token response.+ * Handles time format conversion, expiration calculation, and error mapping to ensure+ * compatibility with the MSAL response handling pipeline.+ *+ * @param response - The network response containing the managed identity token+ *+ * @returns Standardized server authorization token response with normalized fields+ */+ getServerTokenResponse(response) {+ let refreshIn, expiresIn;+ if (response.body.expires_on) {+ if (isIso8601(response.body.expires_on)) {+ response.body.expires_on = new Date(response.body.expires_on).getTime() / 1e3;+ }+ expiresIn = response.body.expires_on - TimeUtils_exports.nowSeconds();+ if (expiresIn > 2 * 3600) {+ refreshIn = expiresIn / 2;+ }+ }+ const serverTokenResponse = {+ status: response.status,+ // success+ access_token: response.body.access_token,+ expires_in: expiresIn,+ scope: response.body.resource,+ token_type: response.body.token_type,+ refresh_in: refreshIn,+ // error+ correlation_id: response.body.correlation_id || response.body.correlationId,+ error: typeof response.body.error === "string" ? response.body.error : response.body.error?.code,+ error_description: response.body.message || (typeof response.body.error === "string" ? response.body.error_description : response.body.error?.message),+ error_codes: response.body.error_codes,+ timestamp: response.body.timestamp,+ trace_id: response.body.trace_id+ };+ return serverTokenResponse;+ }+ /**+ * Acquires an access token using the managed identity endpoint for the specified resource.+ * This is the primary method for token acquisition, handling the complete flow from+ * request creation through response processing and token caching.+ *+ * @param managedIdentityRequest - The managed identity request containing resource and optional parameters+ * @param managedIdentityId - The managed identity configuration (system or user-assigned)+ * @param fakeAuthority - Authority instance used for token caching (managed identity uses a placeholder authority)+ * @param refreshAccessToken - Whether this is a token refresh operation+ *+ * @returns Promise resolving to an authentication result containing the access token and metadata+ *+ * @throws {AuthError} When network requests fail or token validation fails+ * @throws {ClientAuthError} When network errors occur during the request+ */+ async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) {+ const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId);+ if (managedIdentityRequest.revokedTokenSha256Hash) {+ this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`, "");+ networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash;+ }+ if (managedIdentityRequest.clientCapabilities?.length) {+ const clientCapabilities = managedIdentityRequest.clientCapabilities.toString();+ this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`, "");+ networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities;+ }+ const headers = networkRequest.headers;+ headers[Constants_exports.HeaderNames.CONTENT_TYPE] = Constants_exports.URL_FORM_CONTENT_TYPE;+ const networkRequestOptions = { headers };+ if (Object.keys(networkRequest.bodyParameters).length) {+ networkRequestOptions.body = networkRequest.computeParametersBodyString();+ }+ const networkClientHelper = this.disableInternalRetries ? this.networkClient : new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger);+ const reqTimestamp = TimeUtils_exports.nowSeconds();+ let response;+ try {+ if (networkRequest.httpMethod === HttpMethod2.POST) {+ response = await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions);+ } else {+ response = await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions);+ }+ } catch (error2) {+ if (error2 instanceof AuthError) {+ throw error2;+ } else {+ throw createClientAuthError(ClientAuthErrorCodes_exports.networkError, managedIdentityRequest.correlationId);+ }+ }+ const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, new StubPerformanceClient(), null, null);+ const serverTokenResponse = await this.getServerTokenResponseAsync(response, networkClientHelper, networkRequest, networkRequestOptions);+ responseHandler.validateTokenResponse(serverTokenResponse, serverTokenResponse.correlation_id || "", refreshAccessToken);+ return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest, ApiId.acquireTokenWithManagedIdentity);+ }+ /**+ * Determines the appropriate query parameter name for user-assigned managed identity+ * based on the identity type, API version, and endpoint characteristics.+ * Different Azure services and API versions use different parameter names for the same identity types.+ *+ * @param managedIdentityIdType - The type of user-assigned managed identity (client ID, object ID, or resource ID)+ * @param isImds - Whether the request is being made to the IMDS (Instance Metadata Service) endpoint+ * @param usesApi2017 - Whether the endpoint uses the 2017-09-01 API version (affects client ID parameter name)+ *+ * @returns The correct query parameter name for the specified identity type and endpoint+ *+ * @throws {ManagedIdentityError} When an invalid managed identity ID type is provided+ */+ getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) {+ switch (managedIdentityIdType) {+ case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID:+ this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`, "");+ return usesApi2017 ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017 : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID;+ case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID:+ this.logger.info("[Managed Identity] Adding user assigned resource id to the request.", "");+ return isImds ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS;+ case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID:+ this.logger.info("[Managed Identity] Adding user assigned object id to the request.", "");+ return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID;+ default:+ throw createManagedIdentityError(invalidManagedIdentityIdType, "");+ }+ }+ };+ BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger2) => {+ try {+ return new UrlString(envVariable, "").urlString;+ } catch (error2) {+ logger2.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`, "");+ throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName], "");+ }+ };+ }+});++// node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs+var init_LinearRetryStrategy = __esm({+ "node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs+var DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON;+var init_DefaultManagedIdentityRetryPolicy = __esm({+ "node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs"() {+ "use strict";+ init_index_node();+ init_LinearRetryStrategy();+ DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON = [+ Constants_exports.HTTP_NOT_FOUND,+ Constants_exports.HTTP_REQUEST_TIMEOUT,+ Constants_exports.HTTP_TOO_MANY_REQUESTS,+ Constants_exports.HTTP_SERVER_ERROR,+ Constants_exports.HTTP_SERVICE_UNAVAILABLE,+ Constants_exports.HTTP_GATEWAY_TIMEOUT+ ];+ }+});++// node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs+var init_ManagedIdentityRequestParameters = __esm({+ "node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs"() {+ "use strict";+ init_DefaultManagedIdentityRetryPolicy();+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs+var init_AppService = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs"() {+ "use strict";+ init_BaseManagedIdentitySource();+ init_Constants2();+ init_ManagedIdentityRequestParameters();+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs+var SUPPORTED_AZURE_ARC_PLATFORMS, AZURE_ARC_FILE_DETECTION;+var init_AzureArc = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs"() {+ "use strict";+ init_ManagedIdentityRequestParameters();+ init_BaseManagedIdentitySource();+ init_ManagedIdentityError();+ init_Constants2();+ init_ManagedIdentityErrorCodes();+ SUPPORTED_AZURE_ARC_PLATFORMS = {+ win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`,+ linux: "/var/opt/azcmagent/tokens/"+ };+ AZURE_ARC_FILE_DETECTION = {+ win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`,+ linux: "/opt/azcmagent/bin/himds"+ };+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs+var init_CloudShell = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs"() {+ "use strict";+ init_ManagedIdentityRequestParameters();+ init_BaseManagedIdentitySource();+ init_Constants2();+ init_ManagedIdentityError();+ init_ManagedIdentityErrorCodes();+ }+});++// node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs+var init_ExponentialRetryStrategy = __esm({+ "node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs+var HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY, HTTP_STATUS_GONE_RETRY_AFTER_MS;+var init_ImdsRetryPolicy = __esm({+ "node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs"() {+ "use strict";+ init_index_node();+ init_ExponentialRetryStrategy();+ HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY = [+ Constants_exports.HTTP_NOT_FOUND,+ Constants_exports.HTTP_REQUEST_TIMEOUT,+ Constants_exports.HTTP_GONE,+ Constants_exports.HTTP_TOO_MANY_REQUESTS+ ];+ HTTP_STATUS_GONE_RETRY_AFTER_MS = 10 * 1e3;+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs+var IMDS_TOKEN_PATH, DEFAULT_IMDS_ENDPOINT;+var init_Imds = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs"() {+ "use strict";+ init_ManagedIdentityRequestParameters();+ init_BaseManagedIdentitySource();+ init_Constants2();+ init_ImdsRetryPolicy();+ init_packageMetadata2();+ IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token";+ DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`;+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs+var init_ServiceFabric = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs"() {+ "use strict";+ init_ManagedIdentityRequestParameters();+ init_BaseManagedIdentitySource();+ init_Constants2();+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs+var MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR;+var init_MachineLearning = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs"() {+ "use strict";+ init_BaseManagedIdentitySource();+ init_Constants2();+ init_ManagedIdentityRequestParameters();+ MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`;+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs+var init_ManagedIdentityClient = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs"() {+ "use strict";+ init_AppService();+ init_AzureArc();+ init_CloudShell();+ init_Imds();+ init_ServiceFabric();+ init_ManagedIdentityError();+ init_Constants2();+ init_MachineLearning();+ init_ManagedIdentityErrorCodes();+ }+});++// node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs+var SOURCES_THAT_SUPPORT_TOKEN_REVOCATION;+var init_ManagedIdentityApplication = __esm({+ "node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs"() {+ "use strict";+ init_Configuration();+ init_packageMetadata2();+ init_CryptoProvider();+ init_ClientCredentialClient();+ init_ManagedIdentityClient();+ init_NodeStorage();+ init_Constants2();+ init_HashUtils();+ SOURCES_THAT_SUPPORT_TOKEN_REVOCATION = [ManagedIdentitySourceNames.SERVICE_FABRIC];+ }+});++// node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs+var init_DistributedCachePlugin = __esm({+ "node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs"() {+ "use strict";+ }+});++// node_modules/@azure/msal-node/dist/index.mjs+var PromptValue2, ResponseMode2;+var init_dist = __esm({+ "node_modules/@azure/msal-node/dist/index.mjs"() {+ "use strict";+ init_internals();+ init_index_node();+ init_index_node();+ init_PublicClientApplication();+ init_ConfidentialClientApplication();+ init_ManagedIdentityApplication();+ init_ClientAssertion();+ init_TokenCache();+ init_DistributedCachePlugin();+ init_Constants2();+ init_CryptoProvider();+ init_packageMetadata2();+ PromptValue2 = Constants_exports.PromptValue;+ ResponseMode2 = Constants_exports.ResponseMode;+ }+});++// packages/core/dist/auth/msal-disk-cache.js+import * as fs2 from "node:fs";+import * as path2 from "node:path";+import * as os2 from "node:os";+function defaultMsalCacheDir() {+ const envOverride = process.env.FLOWAGENT_MSAL_CACHE_DIR;+ if (envOverride)+ return envOverride;+ const platform = process.platform;+ if (platform === "win32") {+ const base = process.env.LOCALAPPDATA || path2.join(os2.homedir(), "AppData", "Local");+ return path2.join(base, "flowagent", "msal-cache");+ }+ if (platform === "darwin") {+ return path2.join(os2.homedir(), "Library", "Caches", "flowagent", "msal-cache");+ }+ const xdg = process.env.XDG_CACHE_HOME || path2.join(os2.homedir(), ".cache");+ return path2.join(xdg, "flowagent", "msal-cache");+}+function createMsalDiskCachePlugin(opts) {+ const cacheDir = opts.cacheDir ?? defaultMsalCacheDir();+ const disabled = opts.disabled === true || process.env.FLOWAGENT_DISABLE_MSAL_CACHE === "1" || process.env.FLOWAGENT_DISABLE_MSAL_CACHE === "true";+ const safeIdentity = opts.identity.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64);+ const cacheFile = path2.join(cacheDir, `${safeIdentity || "common"}.json`);+ return {+ beforeCacheAccess: async (ctx) => {+ if (disabled)+ return;+ try {+ if (fs2.existsSync(cacheFile)) {+ const data = fs2.readFileSync(cacheFile, { encoding: "utf-8" });+ if (data.trim().length > 0) {+ ctx.tokenCache.deserialize(data);+ }+ }+ } catch {+ }+ },+ afterCacheAccess: async (ctx) => {+ if (disabled)+ return;+ if (!ctx.cacheHasChanged)+ return;+ try {+ fs2.mkdirSync(cacheDir, { recursive: true });+ const serialized = ctx.tokenCache.serialize();+ const tmp = `${cacheFile}.tmp`;+ fs2.writeFileSync(tmp, serialized, { encoding: "utf-8", mode: 384 });+ fs2.renameSync(tmp, cacheFile);+ } catch {+ }+ }+ };+}+var init_msal_disk_cache = __esm({+ "packages/core/dist/auth/msal-disk-cache.js"() {+ "use strict";+ }+});++// packages/core/dist/auth/msal-auth.js+var msal_auth_exports = {};+__export(msal_auth_exports, {+ MsalTokenProvider: () => MsalTokenProvider+});+import { execFile as execFile2 } from "node:child_process";+function escapeHtml(s) {+ return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");+}+var DEFAULT_CLIENT_ID, MsalTokenProvider;+var init_msal_auth = __esm({+ "packages/core/dist/auth/msal-auth.js"() {+ "use strict";+ init_dist();+ init_msal_disk_cache();+ DEFAULT_CLIENT_ID = "9cee029c-6210-4654-90bb-17e6e9d36617";+ MsalTokenProvider = class {+ pca;+ account = null;+ constructor(clientId = DEFAULT_CLIENT_ID, tenantId) {+ const tenant = tenantId || process.env.PA_TENANT_ID || "common";+ const config2 = {+ auth: {+ clientId,+ authority: `https://login.microsoftonline.com/${tenant}`+ },+ // L2 disk cache for MSAL refresh tokens — eliminates the 30–90 s/call+ // overhead of fresh CLI subprocesses re-running browser auth. See+ // msal-disk-cache.ts for the security model and opt-out env vars.+ cache: {+ cachePlugin: createMsalDiskCachePlugin({ identity: tenant })+ }+ };+ this.pca = new PublicClientApplication(config2);+ }+ async getAccessToken(resource) {+ const scopes = resource ? [`${resource}/.default`] : ["https://api.powerplatform.com/.default"];+ const resourceDisplay = resource ?? "https://api.powerplatform.com";+ if (!this.account) {+ try {+ const cache = this.pca.getTokenCache();+ const accounts = await cache.getAllAccounts();+ if (accounts.length > 0) {+ const preferred = process.env.PA_TENANT_ID ? accounts.find((a) => a.tenantId === process.env.PA_TENANT_ID) : null;+ this.account = preferred ?? accounts[0];+ }+ } catch {+ }+ }+ if (this.account) {+ try {+ const result2 = await this.pca.acquireTokenSilent({+ scopes,+ account: this.account+ });+ if (result2?.accessToken)+ return result2.accessToken;+ } catch (err) {+ if (!(err instanceof InteractionRequiredAuthError)) {+ }+ }+ }+ process.stderr.write("Opening browser for Power Platform authentication...\n");+ const successTemplate = `<!doctype html><html><head><meta charset="utf-8"><title>FlowAgent CLI \u2014 Signed in</title>+<style>+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 2em; max-width: 560px; margin: 4em auto; color: #1f1f1f; }+ h2 { color: #107c10; margin: 0 0 0.5em; }+ .row { margin: 0.4em 0; }+ .label { color: #605e5c; display: inline-block; min-width: 80px; }+ .value { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 0.95em; }+ .note { margin-top: 1.5em; padding-top: 1em; border-top: 1px solid #edebe9; color: #605e5c; font-size: 0.9em; }+</style></head><body>+ <h2>\u2713 FlowAgent CLI signed in</h2>+ <div class="row"><span class="label">App:</span> <span class="value">FlowAgent (Power Platform Tools)</span></div>+ <div class="row"><span class="label">Resource:</span> <span class="value">${escapeHtml(resourceDisplay)}</span></div>+ <p class="note">You can close this tab. This is FlowAgent's own access token \u2014 no connector connection was created here. To create a connection (e.g. SharePoint, Teams), run <code>flowagent create-connection --connector=<name></code>.</p>+</body></html>`;+ const result = await this.pca.acquireTokenInteractive({+ scopes,+ openBrowser: (url) => this.openBrowser(url),+ successTemplate,+ errorTemplate: '<!doctype html><html><body style="font-family:sans-serif;padding:2em"><h2 style="color:#a4262c">FlowAgent CLI sign-in failed</h2><p>Check the CLI output for details, then re-run the command.</p></body></html>'+ });+ if (!result?.accessToken) {+ throw new Error("MSAL interactive auth did not return an access token.");+ }+ this.account = result.account;+ if (result.account?.username) {+ process.stderr.write(`Signed in as ${result.account.username} (resource: ${resourceDisplay})+`);+ }+ return result.accessToken;+ }+ openBrowser(url) {+ return new Promise((resolve2, reject) => {+ const platform = process.platform;+ if (platform === "win32") {+ execFile2("powershell.exe", ["-NoProfile", "-Command", `Start-Process '${url.replace(/'/g, "''")}'`], (err) => {+ if (err) {+ process.stderr.write(`Open this URL manually:+${url}+`);+ }+ resolve2();+ });+ } else {+ const cmd = platform === "darwin" ? "open" : "xdg-open";+ execFile2(cmd, [url], (err) => {+ if (err) {+ process.stderr.write(`Open this URL manually:+${url}+`);+ }+ resolve2();+ });+ }+ });+ }+ };+ }+});++// packages/core/dist/trigger-emulators.js+var trigger_emulators_exports = {};+__export(trigger_emulators_exports, {+ TRIGGER_EMULATORS: () => TRIGGER_EMULATORS,+ listSupportedEmulators: () => listSupportedEmulators,+ lookupTriggerEmulator: () => lookupTriggerEmulator+});+function lookupTriggerEmulator(connector, triggerOperation) {+ const key = `${connector}/${triggerOperation}`;+ if (TRIGGER_EMULATORS[key])+ return TRIGGER_EMULATORS[key];+ for (const entry of Object.values(TRIGGER_EMULATORS)) {+ if (entry.triggerOperation === triggerOperation)+ return entry;+ }+ return null;+}+function listSupportedEmulators() {+ return Object.values(TRIGGER_EMULATORS);+}+var TRIGGER_EMULATORS;+var init_trigger_emulators = __esm({+ "packages/core/dist/trigger-emulators.js"() {+ "use strict";+ TRIGGER_EMULATORS = {+ "shared_sharepointonline/GetOnNewItems": {+ triggerOperation: "GetOnNewItems",+ connector: "shared_sharepointonline",+ emulatorOperation: "PostItem",+ livenessImpact: "Creates 1 SharePoint list item in the target list.",+ defaultPayload: {+ // Caller MUST supply siteUrl, listId. Item fields default to a marker.+ item: { Title: "_flowagent-test trigger emulation" }+ },+ notes: "The created item will trigger any active GetOnNewItems polling."+ },+ "shared_sharepointonline/GetOnUpdatedItems": {+ triggerOperation: "GetOnUpdatedItems",+ connector: "shared_sharepointonline",+ emulatorOperation: "PatchItem",+ livenessImpact: "Updates 1 SharePoint list item. Requires existing itemId.",+ defaultPayload: { item: { Title: "_flowagent-test updated" } }+ },+ "shared_sharepointonline/GetOnNewFile": {+ triggerOperation: "GetOnNewFile",+ connector: "shared_sharepointonline",+ emulatorOperation: "CreateFile",+ livenessImpact: "Uploads 1 small file to the target document library.",+ defaultPayload: {+ name: "_flowagent-test.txt",+ body: "FlowAgent trigger emulation"+ }+ },+ "shared_office365/OnNewEmail": {+ triggerOperation: "OnNewEmail",+ connector: "shared_office365",+ emulatorOperation: "SendEmailV2",+ livenessImpact: "Sends 1 email (defaults to self).",+ defaultPayload: {+ emailMessage: {+ To: "_self_",+ // Special marker; emulate_live_trigger resolves to caller's UPN+ Subject: "_flowagent-test trigger emulation",+ Body: "<p>This is a FlowAgent trigger emulation. Safe to delete.</p>",+ Importance: "Low"+ }+ }+ },+ "shared_office365/OnFlaggedEmail": {+ triggerOperation: "OnFlaggedEmail",+ connector: "shared_office365",+ emulatorOperation: "FlagEmail",+ livenessImpact: "Flags 1 email in the user's inbox. Requires existing messageId.",+ defaultPayload: { flag: { flagStatus: "flagged" } }+ },+ "shared_teams/WhenNewChannelMessage": {+ triggerOperation: "WhenNewChannelMessage",+ connector: "shared_teams",+ emulatorOperation: "PostMessageToChannelV3",+ livenessImpact: "Posts 1 message to the target Teams channel.",+ defaultPayload: {+ body: { content: "_flowagent-test trigger emulation. Safe to delete." }+ },+ notes: "Prefer a _flowagent-test channel; do not post to a production channel without explicit override."+ },+ "shared_commondataserviceforapps/WhenARowIsCreated": {+ triggerOperation: "WhenARowIsCreated",+ connector: "shared_commondataserviceforapps",+ emulatorOperation: "CreateRecord",+ livenessImpact: "Creates 1 Dataverse row in the target table.",+ defaultPayload: { item: { name: "_flowagent-test trigger emulation" } }+ },+ "shared_commondataserviceforapps/WhenARowIsUpdated": {+ triggerOperation: "WhenARowIsUpdated",+ connector: "shared_commondataserviceforapps",+ emulatorOperation: "UpdateRecord",+ livenessImpact: "Updates 1 Dataverse row. Requires existing recordId.",+ defaultPayload: { item: { name: "_flowagent-test updated" } }+ },+ "shared_outlook/OnNewEvent": {+ triggerOperation: "OnNewEvent",+ connector: "shared_outlook",+ emulatorOperation: "V4CreateEventCalendarView",+ livenessImpact: "Creates 1 calendar event (defaults to 15 min, today).",+ defaultPayload: {+ event: {+ Subject: "_flowagent-test trigger emulation",+ Body: { Content: "Safe to delete.", ContentType: "text" }+ }+ }+ }+ };+ }+});++// node_modules/ajv/dist/compile/codegen/code.js+var require_code = __commonJS({+ "node_modules/ajv/dist/compile/codegen/code.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;+ var _CodeOrName = class {+ };+ exports._CodeOrName = _CodeOrName;+ exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;+ var Name = class extends _CodeOrName {+ constructor(s) {+ super();+ if (!exports.IDENTIFIER.test(s))+ throw new Error("CodeGen: name must be a valid identifier");+ this.str = s;+ }+ toString() {+ return this.str;+ }+ emptyStr() {+ return false;+ }+ get names() {+ return { [this.str]: 1 };+ }+ };+ exports.Name = Name;+ var _Code = class extends _CodeOrName {+ constructor(code) {+ super();+ this._items = typeof code === "string" ? [code] : code;+ }+ toString() {+ return this.str;+ }+ emptyStr() {+ if (this._items.length > 1)+ return false;+ const item = this._items[0];+ return item === "" || item === '""';+ }+ get str() {+ var _a;+ return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");+ }+ get names() {+ var _a;+ return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => {+ if (c instanceof Name)+ names[c.str] = (names[c.str] || 0) + 1;+ return names;+ }, {});+ }+ };+ exports._Code = _Code;+ exports.nil = new _Code("");+ function _(strs, ...args) {+ const code = [strs[0]];+ let i = 0;+ while (i < args.length) {+ addCodeArg(code, args[i]);+ code.push(strs[++i]);+ }+ return new _Code(code);+ }+ exports._ = _;+ var plus = new _Code("+");+ function str(strs, ...args) {+ const expr = [safeStringify(strs[0])];+ let i = 0;+ while (i < args.length) {+ expr.push(plus);+ addCodeArg(expr, args[i]);+ expr.push(plus, safeStringify(strs[++i]));+ }+ optimize(expr);+ return new _Code(expr);+ }+ exports.str = str;+ function addCodeArg(code, arg) {+ if (arg instanceof _Code)+ code.push(...arg._items);+ else if (arg instanceof Name)+ code.push(arg);+ else+ code.push(interpolate(arg));+ }+ exports.addCodeArg = addCodeArg;+ function optimize(expr) {+ let i = 1;+ while (i < expr.length - 1) {+ if (expr[i] === plus) {+ const res = mergeExprItems(expr[i - 1], expr[i + 1]);+ if (res !== void 0) {+ expr.splice(i - 1, 3, res);+ continue;+ }+ expr[i++] = "+";+ }+ i++;+ }+ }+ function mergeExprItems(a, b) {+ if (b === '""')+ return a;+ if (a === '""')+ return b;+ if (typeof a == "string") {+ if (b instanceof Name || a[a.length - 1] !== '"')+ return;+ if (typeof b != "string")+ return `${a.slice(0, -1)}${b}"`;+ if (b[0] === '"')+ return a.slice(0, -1) + b.slice(1);+ return;+ }+ if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))+ return `"${a}${b.slice(1)}`;+ return;+ }+ function strConcat(c1, c2) {+ return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;+ }+ exports.strConcat = strConcat;+ function interpolate(x) {+ return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);+ }+ function stringify(x) {+ return new _Code(safeStringify(x));+ }+ exports.stringify = stringify;+ function safeStringify(x) {+ return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");+ }+ exports.safeStringify = safeStringify;+ function getProperty(key) {+ return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;+ }+ exports.getProperty = getProperty;+ function getEsmExportName(key) {+ if (typeof key == "string" && exports.IDENTIFIER.test(key)) {+ return new _Code(`${key}`);+ }+ throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);+ }+ exports.getEsmExportName = getEsmExportName;+ function regexpCode(rx) {+ return new _Code(rx.toString());+ }+ exports.regexpCode = regexpCode;+ }+});++// node_modules/ajv/dist/compile/codegen/scope.js+var require_scope = __commonJS({+ "node_modules/ajv/dist/compile/codegen/scope.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;+ var code_1 = require_code();+ var ValueError = class extends Error {+ constructor(name3) {+ super(`CodeGen: "code" for ${name3} not defined`);+ this.value = name3.value;+ }+ };+ var UsedValueState;+ (function(UsedValueState2) {+ UsedValueState2[UsedValueState2["Started"] = 0] = "Started";+ UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";+ })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));+ exports.varKinds = {+ const: new code_1.Name("const"),+ let: new code_1.Name("let"),+ var: new code_1.Name("var")+ };+ var Scope = class {+ constructor({ prefixes, parent } = {}) {+ this._names = {};+ this._prefixes = prefixes;+ this._parent = parent;+ }+ toName(nameOrPrefix) {+ return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);+ }+ name(prefix) {+ return new code_1.Name(this._newName(prefix));+ }+ _newName(prefix) {+ const ng = this._names[prefix] || this._nameGroup(prefix);+ return `${prefix}${ng.index++}`;+ }+ _nameGroup(prefix) {+ var _a, _b;+ if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {+ throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);+ }+ return this._names[prefix] = { prefix, index: 0 };+ }+ };+ exports.Scope = Scope;+ var ValueScopeName = class extends code_1.Name {+ constructor(prefix, nameStr) {+ super(nameStr);+ this.prefix = prefix;+ }+ setValue(value, { property, itemIndex }) {+ this.value = value;+ this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;+ }+ };+ exports.ValueScopeName = ValueScopeName;+ var line = (0, code_1._)`\n`;+ var ValueScope = class extends Scope {+ constructor(opts) {+ super(opts);+ this._values = {};+ this._scope = opts.scope;+ this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };+ }+ get() {+ return this._scope;+ }+ name(prefix) {+ return new ValueScopeName(prefix, this._newName(prefix));+ }+ value(nameOrPrefix, value) {+ var _a;+ if (value.ref === void 0)+ throw new Error("CodeGen: ref must be passed in value");+ const name3 = this.toName(nameOrPrefix);+ const { prefix } = name3;+ const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;+ let vs = this._values[prefix];+ if (vs) {+ const _name = vs.get(valueKey);+ if (_name)+ return _name;+ } else {+ vs = this._values[prefix] = /* @__PURE__ */ new Map();+ }+ vs.set(valueKey, name3);+ const s = this._scope[prefix] || (this._scope[prefix] = []);+ const itemIndex = s.length;+ s[itemIndex] = value.ref;+ name3.setValue(value, { property: prefix, itemIndex });+ return name3;+ }+ getValue(prefix, keyOrRef) {+ const vs = this._values[prefix];+ if (!vs)+ return;+ return vs.get(keyOrRef);+ }+ scopeRefs(scopeName, values = this._values) {+ return this._reduceValues(values, (name3) => {+ if (name3.scopePath === void 0)+ throw new Error(`CodeGen: name "${name3}" has no value`);+ return (0, code_1._)`${scopeName}${name3.scopePath}`;+ });+ }+ scopeCode(values = this._values, usedValues, getCode) {+ return this._reduceValues(values, (name3) => {+ if (name3.value === void 0)+ throw new Error(`CodeGen: name "${name3}" has no value`);+ return name3.value.code;+ }, usedValues, getCode);+ }+ _reduceValues(values, valueCode, usedValues = {}, getCode) {+ let code = code_1.nil;+ for (const prefix in values) {+ const vs = values[prefix];+ if (!vs)+ continue;+ const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();+ vs.forEach((name3) => {+ if (nameSet.has(name3))+ return;+ nameSet.set(name3, UsedValueState.Started);+ let c = valueCode(name3);+ if (c) {+ const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;+ code = (0, code_1._)`${code}${def} ${name3} = ${c};${this.opts._n}`;+ } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name3)) {+ code = (0, code_1._)`${code}${c}${this.opts._n}`;+ } else {+ throw new ValueError(name3);+ }+ nameSet.set(name3, UsedValueState.Completed);+ });+ }+ return code;+ }+ };+ exports.ValueScope = ValueScope;+ }+});++// node_modules/ajv/dist/compile/codegen/index.js+var require_codegen = __commonJS({+ "node_modules/ajv/dist/compile/codegen/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;+ var code_1 = require_code();+ var scope_1 = require_scope();+ var code_2 = require_code();+ Object.defineProperty(exports, "_", { enumerable: true, get: function() {+ return code_2._;+ } });+ Object.defineProperty(exports, "str", { enumerable: true, get: function() {+ return code_2.str;+ } });+ Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {+ return code_2.strConcat;+ } });+ Object.defineProperty(exports, "nil", { enumerable: true, get: function() {+ return code_2.nil;+ } });+ Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {+ return code_2.getProperty;+ } });+ Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {+ return code_2.stringify;+ } });+ Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {+ return code_2.regexpCode;+ } });+ Object.defineProperty(exports, "Name", { enumerable: true, get: function() {+ return code_2.Name;+ } });+ var scope_2 = require_scope();+ Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {+ return scope_2.Scope;+ } });+ Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {+ return scope_2.ValueScope;+ } });+ Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {+ return scope_2.ValueScopeName;+ } });+ Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {+ return scope_2.varKinds;+ } });+ exports.operators = {+ GT: new code_1._Code(">"),+ GTE: new code_1._Code(">="),+ LT: new code_1._Code("<"),+ LTE: new code_1._Code("<="),+ EQ: new code_1._Code("==="),+ NEQ: new code_1._Code("!=="),+ NOT: new code_1._Code("!"),+ OR: new code_1._Code("||"),+ AND: new code_1._Code("&&"),+ ADD: new code_1._Code("+")+ };+ var Node = class {+ optimizeNodes() {+ return this;+ }+ optimizeNames(_names, _constants) {+ return this;+ }+ };+ var Def = class extends Node {+ constructor(varKind, name3, rhs) {+ super();+ this.varKind = varKind;+ this.name = name3;+ this.rhs = rhs;+ }+ render({ es5, _n }) {+ const varKind = es5 ? scope_1.varKinds.var : this.varKind;+ const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;+ return `${varKind} ${this.name}${rhs};` + _n;+ }+ optimizeNames(names, constants) {+ if (!names[this.name.str])+ return;+ if (this.rhs)+ this.rhs = optimizeExpr(this.rhs, names, constants);+ return this;+ }+ get names() {+ return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};+ }+ };+ var Assign = class extends Node {+ constructor(lhs, rhs, sideEffects) {+ super();+ this.lhs = lhs;+ this.rhs = rhs;+ this.sideEffects = sideEffects;+ }+ render({ _n }) {+ return `${this.lhs} = ${this.rhs};` + _n;+ }+ optimizeNames(names, constants) {+ if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)+ return;+ this.rhs = optimizeExpr(this.rhs, names, constants);+ return this;+ }+ get names() {+ const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };+ return addExprNames(names, this.rhs);+ }+ };+ var AssignOp = class extends Assign {+ constructor(lhs, op, rhs, sideEffects) {+ super(lhs, rhs, sideEffects);+ this.op = op;+ }+ render({ _n }) {+ return `${this.lhs} ${this.op}= ${this.rhs};` + _n;+ }+ };+ var Label = class extends Node {+ constructor(label) {+ super();+ this.label = label;+ this.names = {};+ }+ render({ _n }) {+ return `${this.label}:` + _n;+ }+ };+ var Break = class extends Node {+ constructor(label) {+ super();+ this.label = label;+ this.names = {};+ }+ render({ _n }) {+ const label = this.label ? ` ${this.label}` : "";+ return `break${label};` + _n;+ }+ };+ var Throw = class extends Node {+ constructor(error2) {+ super();+ this.error = error2;+ }+ render({ _n }) {+ return `throw ${this.error};` + _n;+ }+ get names() {+ return this.error.names;+ }+ };+ var AnyCode = class extends Node {+ constructor(code) {+ super();+ this.code = code;+ }+ render({ _n }) {+ return `${this.code};` + _n;+ }+ optimizeNodes() {+ return `${this.code}` ? this : void 0;+ }+ optimizeNames(names, constants) {+ this.code = optimizeExpr(this.code, names, constants);+ return this;+ }+ get names() {+ return this.code instanceof code_1._CodeOrName ? this.code.names : {};+ }+ };+ var ParentNode = class extends Node {+ constructor(nodes = []) {+ super();+ this.nodes = nodes;+ }+ render(opts) {+ return this.nodes.reduce((code, n) => code + n.render(opts), "");+ }+ optimizeNodes() {+ const { nodes } = this;+ let i = nodes.length;+ while (i--) {+ const n = nodes[i].optimizeNodes();+ if (Array.isArray(n))+ nodes.splice(i, 1, ...n);+ else if (n)+ nodes[i] = n;+ else+ nodes.splice(i, 1);+ }+ return nodes.length > 0 ? this : void 0;+ }+ optimizeNames(names, constants) {+ const { nodes } = this;+ let i = nodes.length;+ while (i--) {+ const n = nodes[i];+ if (n.optimizeNames(names, constants))+ continue;+ subtractNames(names, n.names);+ nodes.splice(i, 1);+ }+ return nodes.length > 0 ? this : void 0;+ }+ get names() {+ return this.nodes.reduce((names, n) => addNames(names, n.names), {});+ }+ };+ var BlockNode = class extends ParentNode {+ render(opts) {+ return "{" + opts._n + super.render(opts) + "}" + opts._n;+ }+ };+ var Root = class extends ParentNode {+ };+ var Else = class extends BlockNode {+ };+ Else.kind = "else";+ var If = class _If extends BlockNode {+ constructor(condition, nodes) {+ super(nodes);+ this.condition = condition;+ }+ render(opts) {+ let code = `if(${this.condition})` + super.render(opts);+ if (this.else)+ code += "else " + this.else.render(opts);+ return code;+ }+ optimizeNodes() {+ super.optimizeNodes();+ const cond = this.condition;+ if (cond === true)+ return this.nodes;+ let e = this.else;+ if (e) {+ const ns = e.optimizeNodes();+ e = this.else = Array.isArray(ns) ? new Else(ns) : ns;+ }+ if (e) {+ if (cond === false)+ return e instanceof _If ? e : e.nodes;+ if (this.nodes.length)+ return this;+ return new _If(not(cond), e instanceof _If ? [e] : e.nodes);+ }+ if (cond === false || !this.nodes.length)+ return void 0;+ return this;+ }+ optimizeNames(names, constants) {+ var _a;+ this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);+ if (!(super.optimizeNames(names, constants) || this.else))+ return;+ this.condition = optimizeExpr(this.condition, names, constants);+ return this;+ }+ get names() {+ const names = super.names;+ addExprNames(names, this.condition);+ if (this.else)+ addNames(names, this.else.names);+ return names;+ }+ };+ If.kind = "if";+ var For = class extends BlockNode {+ };+ For.kind = "for";+ var ForLoop = class extends For {+ constructor(iteration) {+ super();+ this.iteration = iteration;+ }+ render(opts) {+ return `for(${this.iteration})` + super.render(opts);+ }+ optimizeNames(names, constants) {+ if (!super.optimizeNames(names, constants))+ return;+ this.iteration = optimizeExpr(this.iteration, names, constants);+ return this;+ }+ get names() {+ return addNames(super.names, this.iteration.names);+ }+ };+ var ForRange = class extends For {+ constructor(varKind, name3, from, to) {+ super();+ this.varKind = varKind;+ this.name = name3;+ this.from = from;+ this.to = to;+ }+ render(opts) {+ const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;+ const { name: name3, from, to } = this;+ return `for(${varKind} ${name3}=${from}; ${name3}<${to}; ${name3}++)` + super.render(opts);+ }+ get names() {+ const names = addExprNames(super.names, this.from);+ return addExprNames(names, this.to);+ }+ };+ var ForIter = class extends For {+ constructor(loop, varKind, name3, iterable) {+ super();+ this.loop = loop;+ this.varKind = varKind;+ this.name = name3;+ this.iterable = iterable;+ }+ render(opts) {+ return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);+ }+ optimizeNames(names, constants) {+ if (!super.optimizeNames(names, constants))+ return;+ this.iterable = optimizeExpr(this.iterable, names, constants);+ return this;+ }+ get names() {+ return addNames(super.names, this.iterable.names);+ }+ };+ var Func = class extends BlockNode {+ constructor(name3, args, async) {+ super();+ this.name = name3;+ this.args = args;+ this.async = async;+ }+ render(opts) {+ const _async = this.async ? "async " : "";+ return `${_async}function ${this.name}(${this.args})` + super.render(opts);+ }+ };+ Func.kind = "func";+ var Return = class extends ParentNode {+ render(opts) {+ return "return " + super.render(opts);+ }+ };+ Return.kind = "return";+ var Try = class extends BlockNode {+ render(opts) {+ let code = "try" + super.render(opts);+ if (this.catch)+ code += this.catch.render(opts);+ if (this.finally)+ code += this.finally.render(opts);+ return code;+ }+ optimizeNodes() {+ var _a, _b;+ super.optimizeNodes();+ (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();+ return this;+ }+ optimizeNames(names, constants) {+ var _a, _b;+ super.optimizeNames(names, constants);+ (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);+ return this;+ }+ get names() {+ const names = super.names;+ if (this.catch)+ addNames(names, this.catch.names);+ if (this.finally)+ addNames(names, this.finally.names);+ return names;+ }+ };+ var Catch = class extends BlockNode {+ constructor(error2) {+ super();+ this.error = error2;+ }+ render(opts) {+ return `catch(${this.error})` + super.render(opts);+ }+ };+ Catch.kind = "catch";+ var Finally = class extends BlockNode {+ render(opts) {+ return "finally" + super.render(opts);+ }+ };+ Finally.kind = "finally";+ var CodeGen = class {+ constructor(extScope, opts = {}) {+ this._values = {};+ this._blockStarts = [];+ this._constants = {};+ this.opts = { ...opts, _n: opts.lines ? "\n" : "" };+ this._extScope = extScope;+ this._scope = new scope_1.Scope({ parent: extScope });+ this._nodes = [new Root()];+ }+ toString() {+ return this._root.render(this.opts);+ }+ // returns unique name in the internal scope+ name(prefix) {+ return this._scope.name(prefix);+ }+ // reserves unique name in the external scope+ scopeName(prefix) {+ return this._extScope.name(prefix);+ }+ // reserves unique name in the external scope and assigns value to it+ scopeValue(prefixOrName, value) {+ const name3 = this._extScope.value(prefixOrName, value);+ const vs = this._values[name3.prefix] || (this._values[name3.prefix] = /* @__PURE__ */ new Set());+ vs.add(name3);+ return name3;+ }+ getScopeValue(prefix, keyOrRef) {+ return this._extScope.getValue(prefix, keyOrRef);+ }+ // return code that assigns values in the external scope to the names that are used internally+ // (same names that were returned by gen.scopeName or gen.scopeValue)+ scopeRefs(scopeName) {+ return this._extScope.scopeRefs(scopeName, this._values);+ }+ scopeCode() {+ return this._extScope.scopeCode(this._values);+ }+ _def(varKind, nameOrPrefix, rhs, constant) {+ const name3 = this._scope.toName(nameOrPrefix);+ if (rhs !== void 0 && constant)+ this._constants[name3.str] = rhs;+ this._leafNode(new Def(varKind, name3, rhs));+ return name3;+ }+ // `const` declaration (`var` in es5 mode)+ const(nameOrPrefix, rhs, _constant) {+ return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);+ }+ // `let` declaration with optional assignment (`var` in es5 mode)+ let(nameOrPrefix, rhs, _constant) {+ return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);+ }+ // `var` declaration with optional assignment+ var(nameOrPrefix, rhs, _constant) {+ return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);+ }+ // assignment code+ assign(lhs, rhs, sideEffects) {+ return this._leafNode(new Assign(lhs, rhs, sideEffects));+ }+ // `+=` code+ add(lhs, rhs) {+ return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));+ }+ // appends passed SafeExpr to code or executes Block+ code(c) {+ if (typeof c == "function")+ c();+ else if (c !== code_1.nil)+ this._leafNode(new AnyCode(c));+ return this;+ }+ // returns code for object literal for the passed argument list of key-value pairs+ object(...keyValues) {+ const code = ["{"];+ for (const [key, value] of keyValues) {+ if (code.length > 1)+ code.push(",");+ code.push(key);+ if (key !== value || this.opts.es5) {+ code.push(":");+ (0, code_1.addCodeArg)(code, value);+ }+ }+ code.push("}");+ return new code_1._Code(code);+ }+ // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)+ if(condition, thenBody, elseBody) {+ this._blockNode(new If(condition));+ if (thenBody && elseBody) {+ this.code(thenBody).else().code(elseBody).endIf();+ } else if (thenBody) {+ this.code(thenBody).endIf();+ } else if (elseBody) {+ throw new Error('CodeGen: "else" body without "then" body');+ }+ return this;+ }+ // `else if` clause - invalid without `if` or after `else` clauses+ elseIf(condition) {+ return this._elseNode(new If(condition));+ }+ // `else` clause - only valid after `if` or `else if` clauses+ else() {+ return this._elseNode(new Else());+ }+ // end `if` statement (needed if gen.if was used only with condition)+ endIf() {+ return this._endBlockNode(If, Else);+ }+ _for(node, forBody) {+ this._blockNode(node);+ if (forBody)+ this.code(forBody).endFor();+ return this;+ }+ // a generic `for` clause (or statement if `forBody` is passed)+ for(iteration, forBody) {+ return this._for(new ForLoop(iteration), forBody);+ }+ // `for` statement for a range of values+ forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {+ const name3 = this._scope.toName(nameOrPrefix);+ return this._for(new ForRange(varKind, name3, from, to), () => forBody(name3));+ }+ // `for-of` statement (in es5 mode replace with a normal for loop)+ forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {+ const name3 = this._scope.toName(nameOrPrefix);+ if (this.opts.es5) {+ const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);+ return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => {+ this.var(name3, (0, code_1._)`${arr}[${i}]`);+ forBody(name3);+ });+ }+ return this._for(new ForIter("of", varKind, name3, iterable), () => forBody(name3));+ }+ // `for-in` statement.+ // With option `ownProperties` replaced with a `for-of` loop for object keys+ forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {+ if (this.opts.ownProperties) {+ return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);+ }+ const name3 = this._scope.toName(nameOrPrefix);+ return this._for(new ForIter("in", varKind, name3, obj), () => forBody(name3));+ }+ // end `for` loop+ endFor() {+ return this._endBlockNode(For);+ }+ // `label` statement+ label(label) {+ return this._leafNode(new Label(label));+ }+ // `break` statement+ break(label) {+ return this._leafNode(new Break(label));+ }+ // `return` statement+ return(value) {+ const node = new Return();+ this._blockNode(node);+ this.code(value);+ if (node.nodes.length !== 1)+ throw new Error('CodeGen: "return" should have one node');+ return this._endBlockNode(Return);+ }+ // `try` statement+ try(tryBody, catchCode, finallyCode) {+ if (!catchCode && !finallyCode)+ throw new Error('CodeGen: "try" without "catch" and "finally"');+ const node = new Try();+ this._blockNode(node);+ this.code(tryBody);+ if (catchCode) {+ const error2 = this.name("e");+ this._currNode = node.catch = new Catch(error2);+ catchCode(error2);+ }+ if (finallyCode) {+ this._currNode = node.finally = new Finally();+ this.code(finallyCode);+ }+ return this._endBlockNode(Catch, Finally);+ }+ // `throw` statement+ throw(error2) {+ return this._leafNode(new Throw(error2));+ }+ // start self-balancing block+ block(body, nodeCount) {+ this._blockStarts.push(this._nodes.length);+ if (body)+ this.code(body).endBlock(nodeCount);+ return this;+ }+ // end the current self-balancing block+ endBlock(nodeCount) {+ const len = this._blockStarts.pop();+ if (len === void 0)+ throw new Error("CodeGen: not in self-balancing block");+ const toClose = this._nodes.length - len;+ if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {+ throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);+ }+ this._nodes.length = len;+ return this;+ }+ // `function` heading (or definition if funcBody is passed)+ func(name3, args = code_1.nil, async, funcBody) {+ this._blockNode(new Func(name3, args, async));+ if (funcBody)+ this.code(funcBody).endFunc();+ return this;+ }+ // end function definition+ endFunc() {+ return this._endBlockNode(Func);+ }+ optimize(n = 1) {+ while (n-- > 0) {+ this._root.optimizeNodes();+ this._root.optimizeNames(this._root.names, this._constants);+ }+ }+ _leafNode(node) {+ this._currNode.nodes.push(node);+ return this;+ }+ _blockNode(node) {+ this._currNode.nodes.push(node);+ this._nodes.push(node);+ }+ _endBlockNode(N1, N2) {+ const n = this._currNode;+ if (n instanceof N1 || N2 && n instanceof N2) {+ this._nodes.pop();+ return this;+ }+ throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);+ }+ _elseNode(node) {+ const n = this._currNode;+ if (!(n instanceof If)) {+ throw new Error('CodeGen: "else" without "if"');+ }+ this._currNode = n.else = node;+ return this;+ }+ get _root() {+ return this._nodes[0];+ }+ get _currNode() {+ const ns = this._nodes;+ return ns[ns.length - 1];+ }+ set _currNode(node) {+ const ns = this._nodes;+ ns[ns.length - 1] = node;+ }+ };+ exports.CodeGen = CodeGen;+ function addNames(names, from) {+ for (const n in from)+ names[n] = (names[n] || 0) + (from[n] || 0);+ return names;+ }+ function addExprNames(names, from) {+ return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;+ }+ function optimizeExpr(expr, names, constants) {+ if (expr instanceof code_1.Name)+ return replaceName(expr);+ if (!canOptimize(expr))+ return expr;+ return new code_1._Code(expr._items.reduce((items, c) => {+ if (c instanceof code_1.Name)+ c = replaceName(c);+ if (c instanceof code_1._Code)+ items.push(...c._items);+ else+ items.push(c);+ return items;+ }, []));+ function replaceName(n) {+ const c = constants[n.str];+ if (c === void 0 || names[n.str] !== 1)+ return n;+ delete names[n.str];+ return c;+ }+ function canOptimize(e) {+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);+ }+ }+ function subtractNames(names, from) {+ for (const n in from)+ names[n] = (names[n] || 0) - (from[n] || 0);+ }+ function not(x) {+ return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;+ }+ exports.not = not;+ var andCode = mappend(exports.operators.AND);+ function and(...args) {+ return args.reduce(andCode);+ }+ exports.and = and;+ var orCode = mappend(exports.operators.OR);+ function or(...args) {+ return args.reduce(orCode);+ }+ exports.or = or;+ function mappend(op) {+ return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;+ }+ function par(x) {+ return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;+ }+ }+});++// node_modules/ajv/dist/compile/util.js+var require_util = __commonJS({+ "node_modules/ajv/dist/compile/util.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;+ var codegen_1 = require_codegen();+ var code_1 = require_code();+ function toHash(arr) {+ const hash = {};+ for (const item of arr)+ hash[item] = true;+ return hash;+ }+ exports.toHash = toHash;+ function alwaysValidSchema(it, schema) {+ if (typeof schema == "boolean")+ return schema;+ if (Object.keys(schema).length === 0)+ return true;+ checkUnknownRules(it, schema);+ return !schemaHasRules(schema, it.self.RULES.all);+ }+ exports.alwaysValidSchema = alwaysValidSchema;+ function checkUnknownRules(it, schema = it.schema) {+ const { opts, self } = it;+ if (!opts.strictSchema)+ return;+ if (typeof schema === "boolean")+ return;+ const rules = self.RULES.keywords;+ for (const key in schema) {+ if (!rules[key])+ checkStrictMode(it, `unknown keyword: "${key}"`);+ }+ }+ exports.checkUnknownRules = checkUnknownRules;+ function schemaHasRules(schema, rules) {+ if (typeof schema == "boolean")+ return !schema;+ for (const key in schema)+ if (rules[key])+ return true;+ return false;+ }+ exports.schemaHasRules = schemaHasRules;+ function schemaHasRulesButRef(schema, RULES) {+ if (typeof schema == "boolean")+ return !schema;+ for (const key in schema)+ if (key !== "$ref" && RULES.all[key])+ return true;+ return false;+ }+ exports.schemaHasRulesButRef = schemaHasRulesButRef;+ function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {+ if (!$data) {+ if (typeof schema == "number" || typeof schema == "boolean")+ return schema;+ if (typeof schema == "string")+ return (0, codegen_1._)`${schema}`;+ }+ return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;+ }+ exports.schemaRefOrVal = schemaRefOrVal;+ function unescapeFragment(str) {+ return unescapeJsonPointer(decodeURIComponent(str));+ }+ exports.unescapeFragment = unescapeFragment;+ function escapeFragment(str) {+ return encodeURIComponent(escapeJsonPointer(str));+ }+ exports.escapeFragment = escapeFragment;+ function escapeJsonPointer(str) {+ if (typeof str == "number")+ return `${str}`;+ return str.replace(/~/g, "~0").replace(/\//g, "~1");+ }+ exports.escapeJsonPointer = escapeJsonPointer;+ function unescapeJsonPointer(str) {+ return str.replace(/~1/g, "/").replace(/~0/g, "~");+ }+ exports.unescapeJsonPointer = unescapeJsonPointer;+ function eachItem(xs, f) {+ if (Array.isArray(xs)) {+ for (const x of xs)+ f(x);+ } else {+ f(xs);+ }+ }+ exports.eachItem = eachItem;+ function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) {+ return (gen, from, to, toName) => {+ const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to);+ return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;+ };+ }+ exports.mergeEvaluated = {+ props: makeMergeEvaluated({+ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {+ gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));+ }),+ mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {+ if (from === true) {+ gen.assign(to, true);+ } else {+ gen.assign(to, (0, codegen_1._)`${to} || {}`);+ setEvaluated(gen, to, from);+ }+ }),+ mergeValues: (from, to) => from === true ? true : { ...from, ...to },+ resultToName: evaluatedPropsToName+ }),+ items: makeMergeEvaluated({+ mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),+ mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),+ mergeValues: (from, to) => from === true ? true : Math.max(from, to),+ resultToName: (gen, items) => gen.var("items", items)+ })+ };+ function evaluatedPropsToName(gen, ps) {+ if (ps === true)+ return gen.var("props", true);+ const props = gen.var("props", (0, codegen_1._)`{}`);+ if (ps !== void 0)+ setEvaluated(gen, props, ps);+ return props;+ }+ exports.evaluatedPropsToName = evaluatedPropsToName;+ function setEvaluated(gen, props, ps) {+ Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));+ }+ exports.setEvaluated = setEvaluated;+ var snippets = {};+ function useFunc(gen, f) {+ return gen.scopeValue("func", {+ ref: f,+ code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))+ });+ }+ exports.useFunc = useFunc;+ var Type;+ (function(Type2) {+ Type2[Type2["Num"] = 0] = "Num";+ Type2[Type2["Str"] = 1] = "Str";+ })(Type || (exports.Type = Type = {}));+ function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {+ if (dataProp instanceof codegen_1.Name) {+ const isNumber = dataPropType === Type.Num;+ return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;+ }+ return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);+ }+ exports.getErrorPath = getErrorPath;+ function checkStrictMode(it, msg, mode = it.opts.strictSchema) {+ if (!mode)+ return;+ msg = `strict mode: ${msg}`;+ if (mode === true)+ throw new Error(msg);+ it.self.logger.warn(msg);+ }+ exports.checkStrictMode = checkStrictMode;+ }+});++// node_modules/ajv/dist/compile/names.js+var require_names = __commonJS({+ "node_modules/ajv/dist/compile/names.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var names = {+ // validation function arguments+ data: new codegen_1.Name("data"),+ // data passed to validation function+ // args passed from referencing schema+ valCxt: new codegen_1.Name("valCxt"),+ // validation/data context - should not be used directly, it is destructured to the names below+ instancePath: new codegen_1.Name("instancePath"),+ parentData: new codegen_1.Name("parentData"),+ parentDataProperty: new codegen_1.Name("parentDataProperty"),+ rootData: new codegen_1.Name("rootData"),+ // root data - same as the data passed to the first/top validation function+ dynamicAnchors: new codegen_1.Name("dynamicAnchors"),+ // used to support recursiveRef and dynamicRef+ // function scoped variables+ vErrors: new codegen_1.Name("vErrors"),+ // null or array of validation errors+ errors: new codegen_1.Name("errors"),+ // counter of validation errors+ this: new codegen_1.Name("this"),+ // "globals"+ self: new codegen_1.Name("self"),+ scope: new codegen_1.Name("scope"),+ // JTD serialize/parse name for JSON string and position+ json: new codegen_1.Name("json"),+ jsonPos: new codegen_1.Name("jsonPos"),+ jsonLen: new codegen_1.Name("jsonLen"),+ jsonPart: new codegen_1.Name("jsonPart")+ };+ exports.default = names;+ }+});++// node_modules/ajv/dist/compile/errors.js+var require_errors = __commonJS({+ "node_modules/ajv/dist/compile/errors.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var names_1 = require_names();+ exports.keywordError = {+ message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`+ };+ exports.keyword$DataError = {+ message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`+ };+ function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) {+ const { it } = cxt;+ const { gen, compositeRule, allErrors } = it;+ const errObj = errorObjectCode(cxt, error2, errorPaths);+ if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {+ addError(gen, errObj);+ } else {+ returnErrors(it, (0, codegen_1._)`[${errObj}]`);+ }+ }+ exports.reportError = reportError;+ function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) {+ const { it } = cxt;+ const { gen, compositeRule, allErrors } = it;+ const errObj = errorObjectCode(cxt, error2, errorPaths);+ addError(gen, errObj);+ if (!(compositeRule || allErrors)) {+ returnErrors(it, names_1.default.vErrors);+ }+ }+ exports.reportExtraError = reportExtraError;+ function resetErrorsCount(gen, errsCount) {+ gen.assign(names_1.default.errors, errsCount);+ gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));+ }+ exports.resetErrorsCount = resetErrorsCount;+ function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {+ if (errsCount === void 0)+ throw new Error("ajv implementation error");+ const err = gen.name("err");+ gen.forRange("i", errsCount, names_1.default.errors, (i) => {+ gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);+ gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));+ gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);+ if (it.opts.verbose) {+ gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);+ gen.assign((0, codegen_1._)`${err}.data`, data);+ }+ });+ }+ exports.extendErrors = extendErrors;+ function addError(gen, errObj) {+ const err = gen.const("err", errObj);+ gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);+ gen.code((0, codegen_1._)`${names_1.default.errors}++`);+ }+ function returnErrors(it, errs) {+ const { gen, validateName, schemaEnv } = it;+ if (schemaEnv.$async) {+ gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);+ } else {+ gen.assign((0, codegen_1._)`${validateName}.errors`, errs);+ gen.return(false);+ }+ }+ var E = {+ keyword: new codegen_1.Name("keyword"),+ schemaPath: new codegen_1.Name("schemaPath"),+ // also used in JTD errors+ params: new codegen_1.Name("params"),+ propertyName: new codegen_1.Name("propertyName"),+ message: new codegen_1.Name("message"),+ schema: new codegen_1.Name("schema"),+ parentSchema: new codegen_1.Name("parentSchema")+ };+ function errorObjectCode(cxt, error2, errorPaths) {+ const { createErrors } = cxt.it;+ if (createErrors === false)+ return (0, codegen_1._)`{}`;+ return errorObject(cxt, error2, errorPaths);+ }+ function errorObject(cxt, error2, errorPaths = {}) {+ const { gen, it } = cxt;+ const keyValues = [+ errorInstancePath(it, errorPaths),+ errorSchemaPath(cxt, errorPaths)+ ];+ extraErrorProps(cxt, error2, keyValues);+ return gen.object(...keyValues);+ }+ function errorInstancePath({ errorPath }, { instancePath }) {+ const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;+ return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];+ }+ function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {+ let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;+ if (schemaPath) {+ schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;+ }+ return [E.schemaPath, schPath];+ }+ function extraErrorProps(cxt, { params, message }, keyValues) {+ const { keyword, data, schemaValue, it } = cxt;+ const { opts, propertyName, topSchemaRef, schemaPath } = it;+ keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);+ if (opts.messages) {+ keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);+ }+ if (opts.verbose) {+ keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);+ }+ if (propertyName)+ keyValues.push([E.propertyName, propertyName]);+ }+ }+});++// node_modules/ajv/dist/compile/validate/boolSchema.js+var require_boolSchema = __commonJS({+ "node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;+ var errors_1 = require_errors();+ var codegen_1 = require_codegen();+ var names_1 = require_names();+ var boolError = {+ message: "boolean schema is false"+ };+ function topBoolOrEmptySchema(it) {+ const { gen, schema, validateName } = it;+ if (schema === false) {+ falseSchemaError(it, false);+ } else if (typeof schema == "object" && schema.$async === true) {+ gen.return(names_1.default.data);+ } else {+ gen.assign((0, codegen_1._)`${validateName}.errors`, null);+ gen.return(true);+ }+ }+ exports.topBoolOrEmptySchema = topBoolOrEmptySchema;+ function boolOrEmptySchema(it, valid) {+ const { gen, schema } = it;+ if (schema === false) {+ gen.var(valid, false);+ falseSchemaError(it);+ } else {+ gen.var(valid, true);+ }+ }+ exports.boolOrEmptySchema = boolOrEmptySchema;+ function falseSchemaError(it, overrideAllErrors) {+ const { gen, data } = it;+ const cxt = {+ gen,+ keyword: "false schema",+ data,+ schema: false,+ schemaCode: false,+ schemaValue: false,+ params: {},+ it+ };+ (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);+ }+ }+});++// node_modules/ajv/dist/compile/rules.js+var require_rules = __commonJS({+ "node_modules/ajv/dist/compile/rules.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.getRules = exports.isJSONType = void 0;+ var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];+ var jsonTypes = new Set(_jsonTypes);+ function isJSONType(x) {+ return typeof x == "string" && jsonTypes.has(x);+ }+ exports.isJSONType = isJSONType;+ function getRules() {+ const groups = {+ number: { type: "number", rules: [] },+ string: { type: "string", rules: [] },+ array: { type: "array", rules: [] },+ object: { type: "object", rules: [] }+ };+ return {+ types: { ...groups, integer: true, boolean: true, null: true },+ rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],+ post: { rules: [] },+ all: {},+ keywords: {}+ };+ }+ exports.getRules = getRules;+ }+});++// node_modules/ajv/dist/compile/validate/applicability.js+var require_applicability = __commonJS({+ "node_modules/ajv/dist/compile/validate/applicability.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;+ function schemaHasRulesForType({ schema, self }, type) {+ const group = self.RULES.types[type];+ return group && group !== true && shouldUseGroup(schema, group);+ }+ exports.schemaHasRulesForType = schemaHasRulesForType;+ function shouldUseGroup(schema, group) {+ return group.rules.some((rule) => shouldUseRule(schema, rule));+ }+ exports.shouldUseGroup = shouldUseGroup;+ function shouldUseRule(schema, rule) {+ var _a;+ return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));+ }+ exports.shouldUseRule = shouldUseRule;+ }+});++// node_modules/ajv/dist/compile/validate/dataType.js+var require_dataType = __commonJS({+ "node_modules/ajv/dist/compile/validate/dataType.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;+ var rules_1 = require_rules();+ var applicability_1 = require_applicability();+ var errors_1 = require_errors();+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var DataType;+ (function(DataType2) {+ DataType2[DataType2["Correct"] = 0] = "Correct";+ DataType2[DataType2["Wrong"] = 1] = "Wrong";+ })(DataType || (exports.DataType = DataType = {}));+ function getSchemaTypes(schema) {+ const types = getJSONTypes(schema.type);+ const hasNull = types.includes("null");+ if (hasNull) {+ if (schema.nullable === false)+ throw new Error("type: null contradicts nullable: false");+ } else {+ if (!types.length && schema.nullable !== void 0) {+ throw new Error('"nullable" cannot be used without "type"');+ }+ if (schema.nullable === true)+ types.push("null");+ }+ return types;+ }+ exports.getSchemaTypes = getSchemaTypes;+ function getJSONTypes(ts) {+ const types = Array.isArray(ts) ? ts : ts ? [ts] : [];+ if (types.every(rules_1.isJSONType))+ return types;+ throw new Error("type must be JSONType or JSONType[]: " + types.join(","));+ }+ exports.getJSONTypes = getJSONTypes;+ function coerceAndCheckDataType(it, types) {+ const { gen, data, opts } = it;+ const coerceTo = coerceToTypes(types, opts.coerceTypes);+ const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));+ if (checkTypes) {+ const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);+ gen.if(wrongType, () => {+ if (coerceTo.length)+ coerceData(it, types, coerceTo);+ else+ reportTypeError(it);+ });+ }+ return checkTypes;+ }+ exports.coerceAndCheckDataType = coerceAndCheckDataType;+ var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);+ function coerceToTypes(types, coerceTypes) {+ return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];+ }+ function coerceData(it, types, coerceTo) {+ const { gen, data, opts } = it;+ const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);+ const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);+ if (opts.coerceTypes === "array") {+ gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));+ }+ gen.if((0, codegen_1._)`${coerced} !== undefined`);+ for (const t of coerceTo) {+ if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {+ coerceSpecificType(t);+ }+ }+ gen.else();+ reportTypeError(it);+ gen.endIf();+ gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {+ gen.assign(data, coerced);+ assignParentData(it, coerced);+ });+ function coerceSpecificType(t) {+ switch (t) {+ case "string":+ gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);+ return;+ case "number":+ gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null+ || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);+ return;+ case "integer":+ gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null+ || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);+ return;+ case "boolean":+ gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);+ return;+ case "null":+ gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);+ gen.assign(coerced, null);+ return;+ case "array":+ gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"+ || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);+ }+ }+ }+ function assignParentData({ gen, parentData, parentDataProperty }, expr) {+ gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));+ }+ function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {+ const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;+ let cond;+ switch (dataType) {+ case "null":+ return (0, codegen_1._)`${data} ${EQ} null`;+ case "array":+ cond = (0, codegen_1._)`Array.isArray(${data})`;+ break;+ case "object":+ cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;+ break;+ case "integer":+ cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);+ break;+ case "number":+ cond = numCond();+ break;+ default:+ return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`;+ }+ return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);+ function numCond(_cond = codegen_1.nil) {+ return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);+ }+ }+ exports.checkDataType = checkDataType;+ function checkDataTypes(dataTypes, data, strictNums, correct) {+ if (dataTypes.length === 1) {+ return checkDataType(dataTypes[0], data, strictNums, correct);+ }+ let cond;+ const types = (0, util_1.toHash)(dataTypes);+ if (types.array && types.object) {+ const notObj = (0, codegen_1._)`typeof ${data} != "object"`;+ cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;+ delete types.null;+ delete types.array;+ delete types.object;+ } else {+ cond = codegen_1.nil;+ }+ if (types.number)+ delete types.integer;+ for (const t in types)+ cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));+ return cond;+ }+ exports.checkDataTypes = checkDataTypes;+ var typeError = {+ message: ({ schema }) => `must be ${schema}`,+ params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`+ };+ function reportTypeError(it) {+ const cxt = getTypeErrorContext(it);+ (0, errors_1.reportError)(cxt, typeError);+ }+ exports.reportTypeError = reportTypeError;+ function getTypeErrorContext(it) {+ const { gen, data, schema } = it;+ const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");+ return {+ gen,+ keyword: "type",+ data,+ schema: schema.type,+ schemaCode,+ schemaValue: schemaCode,+ parentSchema: schema,+ params: {},+ it+ };+ }+ }+});++// node_modules/ajv/dist/compile/validate/defaults.js+var require_defaults = __commonJS({+ "node_modules/ajv/dist/compile/validate/defaults.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.assignDefaults = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ function assignDefaults(it, ty) {+ const { properties, items } = it.schema;+ if (ty === "object" && properties) {+ for (const key in properties) {+ assignDefault(it, key, properties[key].default);+ }+ } else if (ty === "array" && Array.isArray(items)) {+ items.forEach((sch, i) => assignDefault(it, i, sch.default));+ }+ }+ exports.assignDefaults = assignDefaults;+ function assignDefault(it, prop, defaultValue) {+ const { gen, compositeRule, data, opts } = it;+ if (defaultValue === void 0)+ return;+ const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;+ if (compositeRule) {+ (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);+ return;+ }+ let condition = (0, codegen_1._)`${childData} === undefined`;+ if (opts.useDefaults === "empty") {+ condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;+ }+ gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);+ }+ }+});++// node_modules/ajv/dist/vocabularies/code.js+var require_code2 = __commonJS({+ "node_modules/ajv/dist/vocabularies/code.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var names_1 = require_names();+ var util_2 = require_util();+ function checkReportMissingProp(cxt, prop) {+ const { gen, data, it } = cxt;+ gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {+ cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);+ cxt.error();+ });+ }+ exports.checkReportMissingProp = checkReportMissingProp;+ function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {+ return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));+ }+ exports.checkMissingProp = checkMissingProp;+ function reportMissingProp(cxt, missing) {+ cxt.setParams({ missingProperty: missing }, true);+ cxt.error();+ }+ exports.reportMissingProp = reportMissingProp;+ function hasPropFunc(gen) {+ return gen.scopeValue("func", {+ // eslint-disable-next-line @typescript-eslint/unbound-method+ ref: Object.prototype.hasOwnProperty,+ code: (0, codegen_1._)`Object.prototype.hasOwnProperty`+ });+ }+ exports.hasPropFunc = hasPropFunc;+ function isOwnProperty(gen, data, property) {+ return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;+ }+ exports.isOwnProperty = isOwnProperty;+ function propertyInData(gen, data, property, ownProperties) {+ const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;+ return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;+ }+ exports.propertyInData = propertyInData;+ function noPropertyInData(gen, data, property, ownProperties) {+ const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;+ return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;+ }+ exports.noPropertyInData = noPropertyInData;+ function allSchemaProperties(schemaMap) {+ return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];+ }+ exports.allSchemaProperties = allSchemaProperties;+ function schemaProperties(it, schemaMap) {+ return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));+ }+ exports.schemaProperties = schemaProperties;+ function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {+ const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;+ const valCxt = [+ [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],+ [names_1.default.parentData, it.parentData],+ [names_1.default.parentDataProperty, it.parentDataProperty],+ [names_1.default.rootData, names_1.default.rootData]+ ];+ if (it.opts.dynamicRef)+ valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);+ const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;+ return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;+ }+ exports.callValidateCode = callValidateCode;+ var newRegExp = (0, codegen_1._)`new RegExp`;+ function usePattern({ gen, it: { opts } }, pattern) {+ const u = opts.unicodeRegExp ? "u" : "";+ const { regExp } = opts.code;+ const rx = regExp(pattern, u);+ return gen.scopeValue("pattern", {+ key: rx.toString(),+ ref: rx,+ code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`+ });+ }+ exports.usePattern = usePattern;+ function validateArray(cxt) {+ const { gen, data, keyword, it } = cxt;+ const valid = gen.name("valid");+ if (it.allErrors) {+ const validArr = gen.let("valid", true);+ validateItems(() => gen.assign(validArr, false));+ return validArr;+ }+ gen.var(valid, true);+ validateItems(() => gen.break());+ return valid;+ function validateItems(notValid) {+ const len = gen.const("len", (0, codegen_1._)`${data}.length`);+ gen.forRange("i", 0, len, (i) => {+ cxt.subschema({+ keyword,+ dataProp: i,+ dataPropType: util_1.Type.Num+ }, valid);+ gen.if((0, codegen_1.not)(valid), notValid);+ });+ }+ }+ exports.validateArray = validateArray;+ function validateUnion(cxt) {+ const { gen, schema, keyword, it } = cxt;+ if (!Array.isArray(schema))+ throw new Error("ajv implementation error");+ const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));+ if (alwaysValid && !it.opts.unevaluated)+ return;+ const valid = gen.let("valid", false);+ const schValid = gen.name("_valid");+ gen.block(() => schema.forEach((_sch, i) => {+ const schCxt = cxt.subschema({+ keyword,+ schemaProp: i,+ compositeRule: true+ }, schValid);+ gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);+ const merged = cxt.mergeValidEvaluated(schCxt, schValid);+ if (!merged)+ gen.if((0, codegen_1.not)(valid));+ }));+ cxt.result(valid, () => cxt.reset(), () => cxt.error(true));+ }+ exports.validateUnion = validateUnion;+ }+});++// node_modules/ajv/dist/compile/validate/keyword.js+var require_keyword = __commonJS({+ "node_modules/ajv/dist/compile/validate/keyword.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;+ var codegen_1 = require_codegen();+ var names_1 = require_names();+ var code_1 = require_code2();+ var errors_1 = require_errors();+ function macroKeywordCode(cxt, def) {+ const { gen, keyword, schema, parentSchema, it } = cxt;+ const macroSchema = def.macro.call(it.self, schema, parentSchema, it);+ const schemaRef = useKeyword(gen, keyword, macroSchema);+ if (it.opts.validateSchema !== false)+ it.self.validateSchema(macroSchema, true);+ const valid = gen.name("valid");+ cxt.subschema({+ schema: macroSchema,+ schemaPath: codegen_1.nil,+ errSchemaPath: `${it.errSchemaPath}/${keyword}`,+ topSchemaRef: schemaRef,+ compositeRule: true+ }, valid);+ cxt.pass(valid, () => cxt.error(true));+ }+ exports.macroKeywordCode = macroKeywordCode;+ function funcKeywordCode(cxt, def) {+ var _a;+ const { gen, keyword, schema, parentSchema, $data, it } = cxt;+ checkAsyncKeyword(it, def);+ const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;+ const validateRef = useKeyword(gen, keyword, validate);+ const valid = gen.let("valid");+ cxt.block$data(valid, validateKeyword);+ cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);+ function validateKeyword() {+ if (def.errors === false) {+ assignValid();+ if (def.modifying)+ modifyData(cxt);+ reportErrs(() => cxt.error());+ } else {+ const ruleErrs = def.async ? validateAsync() : validateSync();+ if (def.modifying)+ modifyData(cxt);+ reportErrs(() => addErrs(cxt, ruleErrs));+ }+ }+ function validateAsync() {+ const ruleErrs = gen.let("ruleErrs", null);+ gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));+ return ruleErrs;+ }+ function validateSync() {+ const validateErrs = (0, codegen_1._)`${validateRef}.errors`;+ gen.assign(validateErrs, null);+ assignValid(codegen_1.nil);+ return validateErrs;+ }+ function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {+ const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;+ const passSchema = !("compile" in def && !$data || def.schema === false);+ gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);+ }+ function reportErrs(errors) {+ var _a2;+ gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors);+ }+ }+ exports.funcKeywordCode = funcKeywordCode;+ function modifyData(cxt) {+ const { gen, data, it } = cxt;+ gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));+ }+ function addErrs(cxt, errs) {+ const { gen } = cxt;+ gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {+ gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);+ (0, errors_1.extendErrors)(cxt);+ }, () => cxt.error());+ }+ function checkAsyncKeyword({ schemaEnv }, def) {+ if (def.async && !schemaEnv.$async)+ throw new Error("async keyword in sync schema");+ }+ function useKeyword(gen, keyword, result) {+ if (result === void 0)+ throw new Error(`keyword "${keyword}" failed to compile`);+ return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });+ }+ function validSchemaType(schema, schemaType, allowUndefined = false) {+ return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");+ }+ exports.validSchemaType = validSchemaType;+ function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {+ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {+ throw new Error("ajv implementation error");+ }+ const deps = def.dependencies;+ if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {+ throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);+ }+ if (def.validateSchema) {+ const valid = def.validateSchema(schema[keyword]);+ if (!valid) {+ const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors);+ if (opts.validateSchema === "log")+ self.logger.error(msg);+ else+ throw new Error(msg);+ }+ }+ }+ exports.validateKeywordUsage = validateKeywordUsage;+ }+});++// node_modules/ajv/dist/compile/validate/subschema.js+var require_subschema = __commonJS({+ "node_modules/ajv/dist/compile/validate/subschema.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {+ if (keyword !== void 0 && schema !== void 0) {+ throw new Error('both "keyword" and "schema" passed, only one allowed');+ }+ if (keyword !== void 0) {+ const sch = it.schema[keyword];+ return schemaProp === void 0 ? {+ schema: sch,+ schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,+ errSchemaPath: `${it.errSchemaPath}/${keyword}`+ } : {+ schema: sch[schemaProp],+ schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,+ errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`+ };+ }+ if (schema !== void 0) {+ if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {+ throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');+ }+ return {+ schema,+ schemaPath,+ topSchemaRef,+ errSchemaPath+ };+ }+ throw new Error('either "keyword" or "schema" must be passed');+ }+ exports.getSubschema = getSubschema;+ function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {+ if (data !== void 0 && dataProp !== void 0) {+ throw new Error('both "data" and "dataProp" passed, only one allowed');+ }+ const { gen } = it;+ if (dataProp !== void 0) {+ const { errorPath, dataPathArr, opts } = it;+ const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);+ dataContextProps(nextData);+ subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;+ subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;+ subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];+ }+ if (data !== void 0) {+ const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);+ dataContextProps(nextData);+ if (propertyName !== void 0)+ subschema.propertyName = propertyName;+ }+ if (dataTypes)+ subschema.dataTypes = dataTypes;+ function dataContextProps(_nextData) {+ subschema.data = _nextData;+ subschema.dataLevel = it.dataLevel + 1;+ subschema.dataTypes = [];+ it.definedProperties = /* @__PURE__ */ new Set();+ subschema.parentData = it.data;+ subschema.dataNames = [...it.dataNames, _nextData];+ }+ }+ exports.extendSubschemaData = extendSubschemaData;+ function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {+ if (compositeRule !== void 0)+ subschema.compositeRule = compositeRule;+ if (createErrors !== void 0)+ subschema.createErrors = createErrors;+ if (allErrors !== void 0)+ subschema.allErrors = allErrors;+ subschema.jtdDiscriminator = jtdDiscriminator;+ subschema.jtdMetadata = jtdMetadata;+ }+ exports.extendSubschemaMode = extendSubschemaMode;+ }+});++// node_modules/fast-deep-equal/index.js+var require_fast_deep_equal = __commonJS({+ "node_modules/fast-deep-equal/index.js"(exports, module) {+ "use strict";+ module.exports = function equal(a, b) {+ if (a === b) return true;+ if (a && b && typeof a == "object" && typeof b == "object") {+ if (a.constructor !== b.constructor) return false;+ var length, i, keys;+ if (Array.isArray(a)) {+ length = a.length;+ if (length != b.length) return false;+ for (i = length; i-- !== 0; )+ if (!equal(a[i], b[i])) return false;+ return true;+ }+ if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;+ if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();+ if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();+ keys = Object.keys(a);+ length = keys.length;+ if (length !== Object.keys(b).length) return false;+ for (i = length; i-- !== 0; )+ if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;+ for (i = length; i-- !== 0; ) {+ var key = keys[i];+ if (!equal(a[key], b[key])) return false;+ }+ return true;+ }+ return a !== a && b !== b;+ };+ }+});++// node_modules/json-schema-traverse/index.js+var require_json_schema_traverse = __commonJS({+ "node_modules/json-schema-traverse/index.js"(exports, module) {+ "use strict";+ var traverse = module.exports = function(schema, opts, cb) {+ if (typeof opts == "function") {+ cb = opts;+ opts = {};+ }+ cb = opts.cb || cb;+ var pre = typeof cb == "function" ? cb : cb.pre || function() {+ };+ var post = cb.post || function() {+ };+ _traverse(opts, pre, post, schema, "", schema);+ };+ traverse.keywords = {+ additionalItems: true,+ items: true,+ contains: true,+ additionalProperties: true,+ propertyNames: true,+ not: true,+ if: true,+ then: true,+ else: true+ };+ traverse.arrayKeywords = {+ items: true,+ allOf: true,+ anyOf: true,+ oneOf: true+ };+ traverse.propsKeywords = {+ $defs: true,+ definitions: true,+ properties: true,+ patternProperties: true,+ dependencies: true+ };+ traverse.skipKeywords = {+ default: true,+ enum: true,+ const: true,+ required: true,+ maximum: true,+ minimum: true,+ exclusiveMaximum: true,+ exclusiveMinimum: true,+ multipleOf: true,+ maxLength: true,+ minLength: true,+ pattern: true,+ format: true,+ maxItems: true,+ minItems: true,+ uniqueItems: true,+ maxProperties: true,+ minProperties: true+ };+ function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {+ if (schema && typeof schema == "object" && !Array.isArray(schema)) {+ pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);+ for (var key in schema) {+ var sch = schema[key];+ if (Array.isArray(sch)) {+ if (key in traverse.arrayKeywords) {+ for (var i = 0; i < sch.length; i++)+ _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);+ }+ } else if (key in traverse.propsKeywords) {+ if (sch && typeof sch == "object") {+ for (var prop in sch)+ _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);+ }+ } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {+ _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);+ }+ }+ post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);+ }+ }+ function escapeJsonPtr(str) {+ return str.replace(/~/g, "~0").replace(/\//g, "~1");+ }+ }+});++// node_modules/ajv/dist/compile/resolve.js+var require_resolve = __commonJS({+ "node_modules/ajv/dist/compile/resolve.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;+ var util_1 = require_util();+ var equal = require_fast_deep_equal();+ var traverse = require_json_schema_traverse();+ var SIMPLE_INLINED = /* @__PURE__ */ new Set([+ "type",+ "format",+ "pattern",+ "maxLength",+ "minLength",+ "maxProperties",+ "minProperties",+ "maxItems",+ "minItems",+ "maximum",+ "minimum",+ "uniqueItems",+ "multipleOf",+ "required",+ "enum",+ "const"+ ]);+ function inlineRef(schema, limit = true) {+ if (typeof schema == "boolean")+ return true;+ if (limit === true)+ return !hasRef(schema);+ if (!limit)+ return false;+ return countKeys(schema) <= limit;+ }+ exports.inlineRef = inlineRef;+ var REF_KEYWORDS = /* @__PURE__ */ new Set([+ "$ref",+ "$recursiveRef",+ "$recursiveAnchor",+ "$dynamicRef",+ "$dynamicAnchor"+ ]);+ function hasRef(schema) {+ for (const key in schema) {+ if (REF_KEYWORDS.has(key))+ return true;+ const sch = schema[key];+ if (Array.isArray(sch) && sch.some(hasRef))+ return true;+ if (typeof sch == "object" && hasRef(sch))+ return true;+ }+ return false;+ }+ function countKeys(schema) {+ let count = 0;+ for (const key in schema) {+ if (key === "$ref")+ return Infinity;+ count++;+ if (SIMPLE_INLINED.has(key))+ continue;+ if (typeof schema[key] == "object") {+ (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));+ }+ if (count === Infinity)+ return Infinity;+ }+ return count;+ }+ function getFullPath(resolver, id = "", normalize) {+ if (normalize !== false)+ id = normalizeId(id);+ const p = resolver.parse(id);+ return _getFullPath(resolver, p);+ }+ exports.getFullPath = getFullPath;+ function _getFullPath(resolver, p) {+ const serialized = resolver.serialize(p);+ return serialized.split("#")[0] + "#";+ }+ exports._getFullPath = _getFullPath;+ var TRAILING_SLASH_HASH = /#\/?$/;+ function normalizeId(id) {+ return id ? id.replace(TRAILING_SLASH_HASH, "") : "";+ }+ exports.normalizeId = normalizeId;+ function resolveUrl(resolver, baseId, id) {+ id = normalizeId(id);+ return resolver.resolve(baseId, id);+ }+ exports.resolveUrl = resolveUrl;+ var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;+ function getSchemaRefs(schema, baseId) {+ if (typeof schema == "boolean")+ return {};+ const { schemaId, uriResolver } = this.opts;+ const schId = normalizeId(schema[schemaId] || baseId);+ const baseIds = { "": schId };+ const pathPrefix = getFullPath(uriResolver, schId, false);+ const localRefs = {};+ const schemaRefs = /* @__PURE__ */ new Set();+ traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {+ if (parentJsonPtr === void 0)+ return;+ const fullPath = pathPrefix + jsonPtr;+ let innerBaseId = baseIds[parentJsonPtr];+ if (typeof sch[schemaId] == "string")+ innerBaseId = addRef.call(this, sch[schemaId]);+ addAnchor.call(this, sch.$anchor);+ addAnchor.call(this, sch.$dynamicAnchor);+ baseIds[jsonPtr] = innerBaseId;+ function addRef(ref) {+ const _resolve = this.opts.uriResolver.resolve;+ ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);+ if (schemaRefs.has(ref))+ throw ambiguos(ref);+ schemaRefs.add(ref);+ let schOrRef = this.refs[ref];+ if (typeof schOrRef == "string")+ schOrRef = this.refs[schOrRef];+ if (typeof schOrRef == "object") {+ checkAmbiguosRef(sch, schOrRef.schema, ref);+ } else if (ref !== normalizeId(fullPath)) {+ if (ref[0] === "#") {+ checkAmbiguosRef(sch, localRefs[ref], ref);+ localRefs[ref] = sch;+ } else {+ this.refs[ref] = fullPath;+ }+ }+ return ref;+ }+ function addAnchor(anchor) {+ if (typeof anchor == "string") {+ if (!ANCHOR.test(anchor))+ throw new Error(`invalid anchor "${anchor}"`);+ addRef.call(this, `#${anchor}`);+ }+ }+ });+ return localRefs;+ function checkAmbiguosRef(sch1, sch2, ref) {+ if (sch2 !== void 0 && !equal(sch1, sch2))+ throw ambiguos(ref);+ }+ function ambiguos(ref) {+ return new Error(`reference "${ref}" resolves to more than one schema`);+ }+ }+ exports.getSchemaRefs = getSchemaRefs;+ }+});++// node_modules/ajv/dist/compile/validate/index.js+var require_validate = __commonJS({+ "node_modules/ajv/dist/compile/validate/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;+ var boolSchema_1 = require_boolSchema();+ var dataType_1 = require_dataType();+ var applicability_1 = require_applicability();+ var dataType_2 = require_dataType();+ var defaults_1 = require_defaults();+ var keyword_1 = require_keyword();+ var subschema_1 = require_subschema();+ var codegen_1 = require_codegen();+ var names_1 = require_names();+ var resolve_1 = require_resolve();+ var util_1 = require_util();+ var errors_1 = require_errors();+ function validateFunctionCode(it) {+ if (isSchemaObj(it)) {+ checkKeywords(it);+ if (schemaCxtHasRules(it)) {+ topSchemaObjCode(it);+ return;+ }+ }+ validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));+ }+ exports.validateFunctionCode = validateFunctionCode;+ function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {+ if (opts.code.es5) {+ gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {+ gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);+ destructureValCxtES5(gen, opts);+ gen.code(body);+ });+ } else {+ gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));+ }+ }+ function destructureValCxt(opts) {+ return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;+ }+ function destructureValCxtES5(gen, opts) {+ gen.if(names_1.default.valCxt, () => {+ gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);+ gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);+ gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);+ gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);+ if (opts.dynamicRef)+ gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);+ }, () => {+ gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);+ gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);+ gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);+ gen.var(names_1.default.rootData, names_1.default.data);+ if (opts.dynamicRef)+ gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);+ });+ }+ function topSchemaObjCode(it) {+ const { schema, opts, gen } = it;+ validateFunction(it, () => {+ if (opts.$comment && schema.$comment)+ commentKeyword(it);+ checkNoDefault(it);+ gen.let(names_1.default.vErrors, null);+ gen.let(names_1.default.errors, 0);+ if (opts.unevaluated)+ resetEvaluated(it);+ typeAndKeywords(it);+ returnResults(it);+ });+ return;+ }+ function resetEvaluated(it) {+ const { gen, validateName } = it;+ it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);+ gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));+ gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));+ }+ function funcSourceUrl(schema, opts) {+ const schId = typeof schema == "object" && schema[opts.schemaId];+ return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;+ }+ function subschemaCode(it, valid) {+ if (isSchemaObj(it)) {+ checkKeywords(it);+ if (schemaCxtHasRules(it)) {+ subSchemaObjCode(it, valid);+ return;+ }+ }+ (0, boolSchema_1.boolOrEmptySchema)(it, valid);+ }+ function schemaCxtHasRules({ schema, self }) {+ if (typeof schema == "boolean")+ return !schema;+ for (const key in schema)+ if (self.RULES.all[key])+ return true;+ return false;+ }+ function isSchemaObj(it) {+ return typeof it.schema != "boolean";+ }+ function subSchemaObjCode(it, valid) {+ const { schema, gen, opts } = it;+ if (opts.$comment && schema.$comment)+ commentKeyword(it);+ updateContext(it);+ checkAsyncSchema(it);+ const errsCount = gen.const("_errs", names_1.default.errors);+ typeAndKeywords(it, errsCount);+ gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);+ }+ function checkKeywords(it) {+ (0, util_1.checkUnknownRules)(it);+ checkRefsAndKeywords(it);+ }+ function typeAndKeywords(it, errsCount) {+ if (it.opts.jtd)+ return schemaKeywords(it, [], false, errsCount);+ const types = (0, dataType_1.getSchemaTypes)(it.schema);+ const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);+ schemaKeywords(it, types, !checkedTypes, errsCount);+ }+ function checkRefsAndKeywords(it) {+ const { schema, errSchemaPath, opts, self } = it;+ if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {+ self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);+ }+ }+ function checkNoDefault(it) {+ const { schema, opts } = it;+ if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {+ (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");+ }+ }+ function updateContext(it) {+ const schId = it.schema[it.opts.schemaId];+ if (schId)+ it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);+ }+ function checkAsyncSchema(it) {+ if (it.schema.$async && !it.schemaEnv.$async)+ throw new Error("async schema in sync schema");+ }+ function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {+ const msg = schema.$comment;+ if (opts.$comment === true) {+ gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);+ } else if (typeof opts.$comment == "function") {+ const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;+ const rootName = gen.scopeValue("root", { ref: schemaEnv.root });+ gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);+ }+ }+ function returnResults(it) {+ const { gen, schemaEnv, validateName, ValidationError, opts } = it;+ if (schemaEnv.$async) {+ gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));+ } else {+ gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);+ if (opts.unevaluated)+ assignEvaluated(it);+ gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);+ }+ }+ function assignEvaluated({ gen, evaluated, props, items }) {+ if (props instanceof codegen_1.Name)+ gen.assign((0, codegen_1._)`${evaluated}.props`, props);+ if (items instanceof codegen_1.Name)+ gen.assign((0, codegen_1._)`${evaluated}.items`, items);+ }+ function schemaKeywords(it, types, typeErrors, errsCount) {+ const { gen, schema, data, allErrors, opts, self } = it;+ const { RULES } = self;+ if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {+ gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));+ return;+ }+ if (!opts.jtd)+ checkStrictTypes(it, types);+ gen.block(() => {+ for (const group of RULES.rules)+ groupKeywords(group);+ groupKeywords(RULES.post);+ });+ function groupKeywords(group) {+ if (!(0, applicability_1.shouldUseGroup)(schema, group))+ return;+ if (group.type) {+ gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));+ iterateKeywords(it, group);+ if (types.length === 1 && types[0] === group.type && typeErrors) {+ gen.else();+ (0, dataType_2.reportTypeError)(it);+ }+ gen.endIf();+ } else {+ iterateKeywords(it, group);+ }+ if (!allErrors)+ gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);+ }+ }+ function iterateKeywords(it, group) {+ const { gen, schema, opts: { useDefaults } } = it;+ if (useDefaults)+ (0, defaults_1.assignDefaults)(it, group.type);+ gen.block(() => {+ for (const rule of group.rules) {+ if ((0, applicability_1.shouldUseRule)(schema, rule)) {+ keywordCode(it, rule.keyword, rule.definition, group.type);+ }+ }+ });+ }+ function checkStrictTypes(it, types) {+ if (it.schemaEnv.meta || !it.opts.strictTypes)+ return;+ checkContextTypes(it, types);+ if (!it.opts.allowUnionTypes)+ checkMultipleTypes(it, types);+ checkKeywordTypes(it, it.dataTypes);+ }+ function checkContextTypes(it, types) {+ if (!types.length)+ return;+ if (!it.dataTypes.length) {+ it.dataTypes = types;+ return;+ }+ types.forEach((t) => {+ if (!includesType(it.dataTypes, t)) {+ strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);+ }+ });+ narrowSchemaTypes(it, types);+ }+ function checkMultipleTypes(it, ts) {+ if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {+ strictTypesError(it, "use allowUnionTypes to allow union type keyword");+ }+ }+ function checkKeywordTypes(it, ts) {+ const rules = it.self.RULES.all;+ for (const keyword in rules) {+ const rule = rules[keyword];+ if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {+ const { type } = rule.definition;+ if (type.length && !type.some((t) => hasApplicableType(ts, t))) {+ strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);+ }+ }+ }+ }+ function hasApplicableType(schTs, kwdT) {+ return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");+ }+ function includesType(ts, t) {+ return ts.includes(t) || t === "integer" && ts.includes("number");+ }+ function narrowSchemaTypes(it, withTypes) {+ const ts = [];+ for (const t of it.dataTypes) {+ if (includesType(withTypes, t))+ ts.push(t);+ else if (withTypes.includes("integer") && t === "number")+ ts.push("integer");+ }+ it.dataTypes = ts;+ }+ function strictTypesError(it, msg) {+ const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;+ msg += ` at "${schemaPath}" (strictTypes)`;+ (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);+ }+ var KeywordCxt = class {+ constructor(it, def, keyword) {+ (0, keyword_1.validateKeywordUsage)(it, def, keyword);+ this.gen = it.gen;+ this.allErrors = it.allErrors;+ this.keyword = keyword;+ this.data = it.data;+ this.schema = it.schema[keyword];+ this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;+ this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);+ this.schemaType = def.schemaType;+ this.parentSchema = it.schema;+ this.params = {};+ this.it = it;+ this.def = def;+ if (this.$data) {+ this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));+ } else {+ this.schemaCode = this.schemaValue;+ if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {+ throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);+ }+ }+ if ("code" in def ? def.trackErrors : def.errors !== false) {+ this.errsCount = it.gen.const("_errs", names_1.default.errors);+ }+ }+ result(condition, successAction, failAction) {+ this.failResult((0, codegen_1.not)(condition), successAction, failAction);+ }+ failResult(condition, successAction, failAction) {+ this.gen.if(condition);+ if (failAction)+ failAction();+ else+ this.error();+ if (successAction) {+ this.gen.else();+ successAction();+ if (this.allErrors)+ this.gen.endIf();+ } else {+ if (this.allErrors)+ this.gen.endIf();+ else+ this.gen.else();+ }+ }+ pass(condition, failAction) {+ this.failResult((0, codegen_1.not)(condition), void 0, failAction);+ }+ fail(condition) {+ if (condition === void 0) {+ this.error();+ if (!this.allErrors)+ this.gen.if(false);+ return;+ }+ this.gen.if(condition);+ this.error();+ if (this.allErrors)+ this.gen.endIf();+ else+ this.gen.else();+ }+ fail$data(condition) {+ if (!this.$data)+ return this.fail(condition);+ const { schemaCode } = this;+ this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);+ }+ error(append, errorParams, errorPaths) {+ if (errorParams) {+ this.setParams(errorParams);+ this._error(append, errorPaths);+ this.setParams({});+ return;+ }+ this._error(append, errorPaths);+ }+ _error(append, errorPaths) {+ ;+ (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);+ }+ $dataError() {+ (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);+ }+ reset() {+ if (this.errsCount === void 0)+ throw new Error('add "trackErrors" to keyword definition');+ (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);+ }+ ok(cond) {+ if (!this.allErrors)+ this.gen.if(cond);+ }+ setParams(obj, assign) {+ if (assign)+ Object.assign(this.params, obj);+ else+ this.params = obj;+ }+ block$data(valid, codeBlock, $dataValid = codegen_1.nil) {+ this.gen.block(() => {+ this.check$data(valid, $dataValid);+ codeBlock();+ });+ }+ check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {+ if (!this.$data)+ return;+ const { gen, schemaCode, schemaType, def } = this;+ gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));+ if (valid !== codegen_1.nil)+ gen.assign(valid, true);+ if (schemaType.length || def.validateSchema) {+ gen.elseIf(this.invalid$data());+ this.$dataError();+ if (valid !== codegen_1.nil)+ gen.assign(valid, false);+ }+ gen.else();+ }+ invalid$data() {+ const { gen, schemaCode, schemaType, def, it } = this;+ return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());+ function wrong$DataType() {+ if (schemaType.length) {+ if (!(schemaCode instanceof codegen_1.Name))+ throw new Error("ajv implementation error");+ const st = Array.isArray(schemaType) ? schemaType : [schemaType];+ return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;+ }+ return codegen_1.nil;+ }+ function invalid$DataSchema() {+ if (def.validateSchema) {+ const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });+ return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;+ }+ return codegen_1.nil;+ }+ }+ subschema(appl, valid) {+ const subschema = (0, subschema_1.getSubschema)(this.it, appl);+ (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);+ (0, subschema_1.extendSubschemaMode)(subschema, appl);+ const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };+ subschemaCode(nextContext, valid);+ return nextContext;+ }+ mergeEvaluated(schemaCxt, toName) {+ const { it, gen } = this;+ if (!it.opts.unevaluated)+ return;+ if (it.props !== true && schemaCxt.props !== void 0) {+ it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);+ }+ if (it.items !== true && schemaCxt.items !== void 0) {+ it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);+ }+ }+ mergeValidEvaluated(schemaCxt, valid) {+ const { it, gen } = this;+ if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {+ gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));+ return true;+ }+ }+ };+ exports.KeywordCxt = KeywordCxt;+ function keywordCode(it, keyword, def, ruleType) {+ const cxt = new KeywordCxt(it, def, keyword);+ if ("code" in def) {+ def.code(cxt, ruleType);+ } else if (cxt.$data && def.validate) {+ (0, keyword_1.funcKeywordCode)(cxt, def);+ } else if ("macro" in def) {+ (0, keyword_1.macroKeywordCode)(cxt, def);+ } else if (def.compile || def.validate) {+ (0, keyword_1.funcKeywordCode)(cxt, def);+ }+ }+ var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;+ var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;+ function getData($data, { dataLevel, dataNames, dataPathArr }) {+ let jsonPointer;+ let data;+ if ($data === "")+ return names_1.default.rootData;+ if ($data[0] === "/") {+ if (!JSON_POINTER.test($data))+ throw new Error(`Invalid JSON-pointer: ${$data}`);+ jsonPointer = $data;+ data = names_1.default.rootData;+ } else {+ const matches = RELATIVE_JSON_POINTER.exec($data);+ if (!matches)+ throw new Error(`Invalid JSON-pointer: ${$data}`);+ const up = +matches[1];+ jsonPointer = matches[2];+ if (jsonPointer === "#") {+ if (up >= dataLevel)+ throw new Error(errorMsg("property/index", up));+ return dataPathArr[dataLevel - up];+ }+ if (up > dataLevel)+ throw new Error(errorMsg("data", up));+ data = dataNames[dataLevel - up];+ if (!jsonPointer)+ return data;+ }+ let expr = data;+ const segments = jsonPointer.split("/");+ for (const segment of segments) {+ if (segment) {+ data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;+ expr = (0, codegen_1._)`${expr} && ${data}`;+ }+ }+ return expr;+ function errorMsg(pointerType, up) {+ return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;+ }+ }+ exports.getData = getData;+ }+});++// node_modules/ajv/dist/runtime/validation_error.js+var require_validation_error = __commonJS({+ "node_modules/ajv/dist/runtime/validation_error.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var ValidationError = class extends Error {+ constructor(errors) {+ super("validation failed");+ this.errors = errors;+ this.ajv = this.validation = true;+ }+ };+ exports.default = ValidationError;+ }+});++// node_modules/ajv/dist/compile/ref_error.js+var require_ref_error = __commonJS({+ "node_modules/ajv/dist/compile/ref_error.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var resolve_1 = require_resolve();+ var MissingRefError = class extends Error {+ constructor(resolver, baseId, ref, msg) {+ super(msg || `can't resolve reference ${ref} from id ${baseId}`);+ this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);+ this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));+ }+ };+ exports.default = MissingRefError;+ }+});++// node_modules/ajv/dist/compile/index.js+var require_compile = __commonJS({+ "node_modules/ajv/dist/compile/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;+ var codegen_1 = require_codegen();+ var validation_error_1 = require_validation_error();+ var names_1 = require_names();+ var resolve_1 = require_resolve();+ var util_1 = require_util();+ var validate_1 = require_validate();+ var SchemaEnv = class {+ constructor(env) {+ var _a;+ this.refs = {};+ this.dynamicAnchors = {};+ let schema;+ if (typeof env.schema == "object")+ schema = env.schema;+ this.schema = env.schema;+ this.schemaId = env.schemaId;+ this.root = env.root || this;+ this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);+ this.schemaPath = env.schemaPath;+ this.localRefs = env.localRefs;+ this.meta = env.meta;+ this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;+ this.refs = {};+ }+ };+ exports.SchemaEnv = SchemaEnv;+ function compileSchema(sch) {+ const _sch = getCompilingSchema.call(this, sch);+ if (_sch)+ return _sch;+ const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);+ const { es5, lines } = this.opts.code;+ const { ownProperties } = this.opts;+ const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });+ let _ValidationError;+ if (sch.$async) {+ _ValidationError = gen.scopeValue("Error", {+ ref: validation_error_1.default,+ code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`+ });+ }+ const validateName = gen.scopeName("validate");+ sch.validateName = validateName;+ const schemaCxt = {+ gen,+ allErrors: this.opts.allErrors,+ data: names_1.default.data,+ parentData: names_1.default.parentData,+ parentDataProperty: names_1.default.parentDataProperty,+ dataNames: [names_1.default.data],+ dataPathArr: [codegen_1.nil],+ // TODO can its length be used as dataLevel if nil is removed?+ dataLevel: 0,+ dataTypes: [],+ definedProperties: /* @__PURE__ */ new Set(),+ topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),+ validateName,+ ValidationError: _ValidationError,+ schema: sch.schema,+ schemaEnv: sch,+ rootId,+ baseId: sch.baseId || rootId,+ schemaPath: codegen_1.nil,+ errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),+ errorPath: (0, codegen_1._)`""`,+ opts: this.opts,+ self: this+ };+ let sourceCode;+ try {+ this._compilations.add(sch);+ (0, validate_1.validateFunctionCode)(schemaCxt);+ gen.optimize(this.opts.code.optimize);+ const validateCode = gen.toString();+ sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;+ if (this.opts.code.process)+ sourceCode = this.opts.code.process(sourceCode, sch);+ const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);+ const validate = makeValidate(this, this.scope.get());+ this.scope.value(validateName, { ref: validate });+ validate.errors = null;+ validate.schema = sch.schema;+ validate.schemaEnv = sch;+ if (sch.$async)+ validate.$async = true;+ if (this.opts.code.source === true) {+ validate.source = { validateName, validateCode, scopeValues: gen._values };+ }+ if (this.opts.unevaluated) {+ const { props, items } = schemaCxt;+ validate.evaluated = {+ props: props instanceof codegen_1.Name ? void 0 : props,+ items: items instanceof codegen_1.Name ? void 0 : items,+ dynamicProps: props instanceof codegen_1.Name,+ dynamicItems: items instanceof codegen_1.Name+ };+ if (validate.source)+ validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);+ }+ sch.validate = validate;+ return sch;+ } catch (e) {+ delete sch.validate;+ delete sch.validateName;+ if (sourceCode)+ this.logger.error("Error compiling schema, function code:", sourceCode);+ throw e;+ } finally {+ this._compilations.delete(sch);+ }+ }+ exports.compileSchema = compileSchema;+ function resolveRef(root, baseId, ref) {+ var _a;+ ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);+ const schOrFunc = root.refs[ref];+ if (schOrFunc)+ return schOrFunc;+ let _sch = resolve2.call(this, root, ref);+ if (_sch === void 0) {+ const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];+ const { schemaId } = this.opts;+ if (schema)+ _sch = new SchemaEnv({ schema, schemaId, root, baseId });+ }+ if (_sch === void 0)+ return;+ return root.refs[ref] = inlineOrCompile.call(this, _sch);+ }+ exports.resolveRef = resolveRef;+ function inlineOrCompile(sch) {+ if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))+ return sch.schema;+ return sch.validate ? sch : compileSchema.call(this, sch);+ }+ function getCompilingSchema(schEnv) {+ for (const sch of this._compilations) {+ if (sameSchemaEnv(sch, schEnv))+ return sch;+ }+ }+ exports.getCompilingSchema = getCompilingSchema;+ function sameSchemaEnv(s1, s2) {+ return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;+ }+ function resolve2(root, ref) {+ let sch;+ while (typeof (sch = this.refs[ref]) == "string")+ ref = sch;+ return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);+ }+ function resolveSchema(root, ref) {+ const p = this.opts.uriResolver.parse(ref);+ const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);+ let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);+ if (Object.keys(root.schema).length > 0 && refPath === baseId) {+ return getJsonPointer.call(this, p, root);+ }+ const id = (0, resolve_1.normalizeId)(refPath);+ const schOrRef = this.refs[id] || this.schemas[id];+ if (typeof schOrRef == "string") {+ const sch = resolveSchema.call(this, root, schOrRef);+ if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")+ return;+ return getJsonPointer.call(this, p, sch);+ }+ if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")+ return;+ if (!schOrRef.validate)+ compileSchema.call(this, schOrRef);+ if (id === (0, resolve_1.normalizeId)(ref)) {+ const { schema } = schOrRef;+ const { schemaId } = this.opts;+ const schId = schema[schemaId];+ if (schId)+ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);+ return new SchemaEnv({ schema, schemaId, root, baseId });+ }+ return getJsonPointer.call(this, p, schOrRef);+ }+ exports.resolveSchema = resolveSchema;+ var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([+ "properties",+ "patternProperties",+ "enum",+ "dependencies",+ "definitions"+ ]);+ function getJsonPointer(parsedRef, { baseId, schema, root }) {+ var _a;+ if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")+ return;+ for (const part of parsedRef.fragment.slice(1).split("/")) {+ if (typeof schema === "boolean")+ return;+ const partSchema = schema[(0, util_1.unescapeFragment)(part)];+ if (partSchema === void 0)+ return;+ schema = partSchema;+ const schId = typeof schema === "object" && schema[this.opts.schemaId];+ if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {+ baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);+ }+ }+ let env;+ if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {+ const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);+ env = resolveSchema.call(this, root, $ref);+ }+ const { schemaId } = this.opts;+ env = env || new SchemaEnv({ schema, schemaId, root, baseId });+ if (env.schema !== env.root.schema)+ return env;+ return void 0;+ }+ }+});++// node_modules/ajv/dist/refs/data.json+var require_data = __commonJS({+ "node_modules/ajv/dist/refs/data.json"(exports, module) {+ module.exports = {+ $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",+ description: "Meta-schema for $data reference (JSON AnySchema extension proposal)",+ type: "object",+ required: ["$data"],+ properties: {+ $data: {+ type: "string",+ anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }]+ }+ },+ additionalProperties: false+ };+ }+});++// node_modules/fast-uri/lib/utils.js+var require_utils = __commonJS({+ "node_modules/fast-uri/lib/utils.js"(exports, module) {+ "use strict";+ var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);+ var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);+ var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);+ var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);+ var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);+ function stringArrayToHexStripped(input) {+ let acc = "";+ let code = 0;+ let i = 0;+ for (i = 0; i < input.length; i++) {+ code = input[i].charCodeAt(0);+ if (code === 48) {+ continue;+ }+ if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {+ return "";+ }+ acc += input[i];+ break;+ }+ for (i += 1; i < input.length; i++) {+ code = input[i].charCodeAt(0);+ if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {+ return "";+ }+ acc += input[i];+ }+ return acc;+ }+ var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);+ function consumeIsZone(buffer) {+ buffer.length = 0;+ return true;+ }+ function consumeHextets(buffer, address, output) {+ if (buffer.length) {+ const hex = stringArrayToHexStripped(buffer);+ if (hex !== "") {+ address.push(hex);+ } else {+ output.error = true;+ return false;+ }+ buffer.length = 0;+ }+ return true;+ }+ function getIPV6(input) {+ let tokenCount = 0;+ const output = { error: false, address: "", zone: "" };+ const address = [];+ const buffer = [];+ let endipv6Encountered = false;+ let endIpv6 = false;+ let consume = consumeHextets;+ for (let i = 0; i < input.length; i++) {+ const cursor = input[i];+ if (cursor === "[" || cursor === "]") {+ continue;+ }+ if (cursor === ":") {+ if (endipv6Encountered === true) {+ endIpv6 = true;+ }+ if (!consume(buffer, address, output)) {+ break;+ }+ if (++tokenCount > 7) {+ output.error = true;+ break;+ }+ if (i > 0 && input[i - 1] === ":") {+ endipv6Encountered = true;+ }+ address.push(":");+ continue;+ } else if (cursor === "%") {+ if (!consume(buffer, address, output)) {+ break;+ }+ consume = consumeIsZone;+ } else {+ buffer.push(cursor);+ continue;+ }+ }+ if (buffer.length) {+ if (consume === consumeIsZone) {+ output.zone = buffer.join("");+ } else if (endIpv6) {+ address.push(buffer.join(""));+ } else {+ address.push(stringArrayToHexStripped(buffer));+ }+ }+ output.address = address.join("");+ return output;+ }+ function normalizeIPv6(host) {+ if (findToken(host, ":") < 2) {+ return { host, isIPV6: false };+ }+ const ipv62 = getIPV6(host);+ if (!ipv62.error) {+ let newHost = ipv62.address;+ let escapedHost = ipv62.address;+ if (ipv62.zone) {+ newHost += "%" + ipv62.zone;+ escapedHost += "%25" + ipv62.zone;+ }+ return { host: newHost, isIPV6: true, escapedHost };+ } else {+ return { host, isIPV6: false };+ }+ }+ function findToken(str, token) {+ let ind = 0;+ for (let i = 0; i < str.length; i++) {+ if (str[i] === token) ind++;+ }+ return ind;+ }+ function removeDotSegments(path3) {+ let input = path3;+ const output = [];+ let nextSlash = -1;+ let len = 0;+ while (len = input.length) {+ if (len === 1) {+ if (input === ".") {+ break;+ } else if (input === "/") {+ output.push("/");+ break;+ } else {+ output.push(input);+ break;+ }+ } else if (len === 2) {+ if (input[0] === ".") {+ if (input[1] === ".") {+ break;+ } else if (input[1] === "/") {+ input = input.slice(2);+ continue;+ }+ } else if (input[0] === "/") {+ if (input[1] === "." || input[1] === "/") {+ output.push("/");+ break;+ }+ }+ } else if (len === 3) {+ if (input === "/..") {+ if (output.length !== 0) {+ output.pop();+ }+ output.push("/");+ break;+ }+ }+ if (input[0] === ".") {+ if (input[1] === ".") {+ if (input[2] === "/") {+ input = input.slice(3);+ continue;+ }+ } else if (input[1] === "/") {+ input = input.slice(2);+ continue;+ }+ } else if (input[0] === "/") {+ if (input[1] === ".") {+ if (input[2] === "/") {+ input = input.slice(2);+ continue;+ } else if (input[2] === ".") {+ if (input[3] === "/") {+ input = input.slice(3);+ if (output.length !== 0) {+ output.pop();+ }+ continue;+ }+ }+ }+ }+ if ((nextSlash = input.indexOf("/", 1)) === -1) {+ output.push(input);+ break;+ } else {+ output.push(input.slice(0, nextSlash));+ input = input.slice(nextSlash);+ }+ }+ return output.join("");+ }+ var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };+ var HOST_DELIM_RE = /[@/?#:]/g;+ var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;+ function reescapeHostDelimiters(host, isIP) {+ const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;+ re.lastIndex = 0;+ return host.replace(re, (ch) => HOST_DELIMS[ch]);+ }+ function normalizePercentEncoding(input, decodeUnreserved = false) {+ if (input.indexOf("%") === -1) {+ return input;+ }+ let output = "";+ for (let i = 0; i < input.length; i++) {+ if (input[i] === "%" && i + 2 < input.length) {+ const hex = input.slice(i + 1, i + 3);+ if (isHexPair(hex)) {+ const normalizedHex = hex.toUpperCase();+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));+ if (decodeUnreserved && isUnreserved(decoded)) {+ output += decoded;+ } else {+ output += "%" + normalizedHex;+ }+ i += 2;+ continue;+ }+ }+ output += input[i];+ }+ return output;+ }+ function normalizePathEncoding(input) {+ let output = "";+ for (let i = 0; i < input.length; i++) {+ if (input[i] === "%" && i + 2 < input.length) {+ const hex = input.slice(i + 1, i + 3);+ if (isHexPair(hex)) {+ const normalizedHex = hex.toUpperCase();+ const decoded = String.fromCharCode(parseInt(normalizedHex, 16));+ if (decoded !== "." && isUnreserved(decoded)) {+ output += decoded;+ } else {+ output += "%" + normalizedHex;+ }+ i += 2;+ continue;+ }+ }+ if (isPathCharacter(input[i])) {+ output += input[i];+ } else {+ output += escape(input[i]);+ }+ }+ return output;+ }+ function escapePreservingEscapes(input) {+ let output = "";+ for (let i = 0; i < input.length; i++) {+ if (input[i] === "%" && i + 2 < input.length) {+ const hex = input.slice(i + 1, i + 3);+ if (isHexPair(hex)) {+ output += "%" + hex.toUpperCase();+ i += 2;+ continue;+ }+ }+ output += escape(input[i]);+ }+ return output;+ }+ function recomposeAuthority(component) {+ const uriTokens = [];+ if (component.userinfo !== void 0) {+ uriTokens.push(component.userinfo);+ uriTokens.push("@");+ }+ if (component.host !== void 0) {+ let host = unescape(component.host);+ if (!isIPv4(host)) {+ const ipV6res = normalizeIPv6(host);+ if (ipV6res.isIPV6 === true) {+ host = `[${ipV6res.escapedHost}]`;+ } else {+ host = reescapeHostDelimiters(host, false);+ }+ }+ uriTokens.push(host);+ }+ if (typeof component.port === "number" || typeof component.port === "string") {+ uriTokens.push(":");+ uriTokens.push(String(component.port));+ }+ return uriTokens.length ? uriTokens.join("") : void 0;+ }+ module.exports = {+ nonSimpleDomain,+ recomposeAuthority,+ reescapeHostDelimiters,+ normalizePercentEncoding,+ normalizePathEncoding,+ escapePreservingEscapes,+ removeDotSegments,+ isIPv4,+ isUUID,+ normalizeIPv6,+ stringArrayToHexStripped+ };+ }+});++// node_modules/fast-uri/lib/schemes.js+var require_schemes = __commonJS({+ "node_modules/fast-uri/lib/schemes.js"(exports, module) {+ "use strict";+ var { isUUID } = require_utils();+ var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;+ var supportedSchemeNames = (+ /** @type {const} */+ [+ "http",+ "https",+ "ws",+ "wss",+ "urn",+ "urn:uuid"+ ]+ );+ function isValidSchemeName(name3) {+ return supportedSchemeNames.indexOf(+ /** @type {*} */+ name3+ ) !== -1;+ }+ function wsIsSecure(wsComponent) {+ if (wsComponent.secure === true) {+ return true;+ } else if (wsComponent.secure === false) {+ return false;+ } else if (wsComponent.scheme) {+ return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");+ } else {+ return false;+ }+ }+ function httpParse(component) {+ if (!component.host) {+ component.error = component.error || "HTTP URIs must have a host.";+ }+ return component;+ }+ function httpSerialize(component) {+ const secure = String(component.scheme).toLowerCase() === "https";+ if (component.port === (secure ? 443 : 80) || component.port === "") {+ component.port = void 0;+ }+ if (!component.path) {+ component.path = "/";+ }+ return component;+ }+ function wsParse(wsComponent) {+ wsComponent.secure = wsIsSecure(wsComponent);+ wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");+ wsComponent.path = void 0;+ wsComponent.query = void 0;+ return wsComponent;+ }+ function wsSerialize(wsComponent) {+ if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {+ wsComponent.port = void 0;+ }+ if (typeof wsComponent.secure === "boolean") {+ wsComponent.scheme = wsComponent.secure ? "wss" : "ws";+ wsComponent.secure = void 0;+ }+ if (wsComponent.resourceName) {+ const [path3, query] = wsComponent.resourceName.split("?");+ wsComponent.path = path3 && path3 !== "/" ? path3 : void 0;+ wsComponent.query = query;+ wsComponent.resourceName = void 0;+ }+ wsComponent.fragment = void 0;+ return wsComponent;+ }+ function urnParse(urnComponent, options) {+ if (!urnComponent.path) {+ urnComponent.error = "URN can not be parsed";+ return urnComponent;+ }+ const matches = urnComponent.path.match(URN_REG);+ if (matches) {+ const scheme = options.scheme || urnComponent.scheme || "urn";+ urnComponent.nid = matches[1].toLowerCase();+ urnComponent.nss = matches[2];+ const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;+ const schemeHandler = getSchemeHandler(urnScheme);+ urnComponent.path = void 0;+ if (schemeHandler) {+ urnComponent = schemeHandler.parse(urnComponent, options);+ }+ } else {+ urnComponent.error = urnComponent.error || "URN can not be parsed.";+ }+ return urnComponent;+ }+ function urnSerialize(urnComponent, options) {+ if (urnComponent.nid === void 0) {+ throw new Error("URN without nid cannot be serialized");+ }+ const scheme = options.scheme || urnComponent.scheme || "urn";+ const nid = urnComponent.nid.toLowerCase();+ const urnScheme = `${scheme}:${options.nid || nid}`;+ const schemeHandler = getSchemeHandler(urnScheme);+ if (schemeHandler) {+ urnComponent = schemeHandler.serialize(urnComponent, options);+ }+ const uriComponent = urnComponent;+ const nss = urnComponent.nss;+ uriComponent.path = `${nid || options.nid}:${nss}`;+ options.skipEscape = true;+ return uriComponent;+ }+ function urnuuidParse(urnComponent, options) {+ const uuidComponent = urnComponent;+ uuidComponent.uuid = uuidComponent.nss;+ uuidComponent.nss = void 0;+ if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {+ uuidComponent.error = uuidComponent.error || "UUID is not valid.";+ }+ return uuidComponent;+ }+ function urnuuidSerialize(uuidComponent) {+ const urnComponent = uuidComponent;+ urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();+ return urnComponent;+ }+ var http2 = (+ /** @type {SchemeHandler} */+ {+ scheme: "http",+ domainHost: true,+ parse: httpParse,+ serialize: httpSerialize+ }+ );+ var https = (+ /** @type {SchemeHandler} */+ {+ scheme: "https",+ domainHost: http2.domainHost,+ parse: httpParse,+ serialize: httpSerialize+ }+ );+ var ws = (+ /** @type {SchemeHandler} */+ {+ scheme: "ws",+ domainHost: true,+ parse: wsParse,+ serialize: wsSerialize+ }+ );+ var wss = (+ /** @type {SchemeHandler} */+ {+ scheme: "wss",+ domainHost: ws.domainHost,+ parse: ws.parse,+ serialize: ws.serialize+ }+ );+ var urn = (+ /** @type {SchemeHandler} */+ {+ scheme: "urn",+ parse: urnParse,+ serialize: urnSerialize,+ skipNormalize: true+ }+ );+ var urnuuid = (+ /** @type {SchemeHandler} */+ {+ scheme: "urn:uuid",+ parse: urnuuidParse,+ serialize: urnuuidSerialize,+ skipNormalize: true+ }+ );+ var SCHEMES = (+ /** @type {Record<SchemeName, SchemeHandler>} */+ {+ http: http2,+ https,+ ws,+ wss,+ urn,+ "urn:uuid": urnuuid+ }+ );+ Object.setPrototypeOf(SCHEMES, null);+ function getSchemeHandler(scheme) {+ return scheme && (SCHEMES[+ /** @type {SchemeName} */+ scheme+ ] || SCHEMES[+ /** @type {SchemeName} */+ scheme.toLowerCase()+ ]) || void 0;+ }+ module.exports = {+ wsIsSecure,+ SCHEMES,+ isValidSchemeName,+ getSchemeHandler+ };+ }+});++// node_modules/fast-uri/index.js+var require_fast_uri = __commonJS({+ "node_modules/fast-uri/index.js"(exports, module) {+ "use strict";+ var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();+ var { SCHEMES, getSchemeHandler } = require_schemes();+ function normalize(uri, options) {+ if (typeof uri === "string") {+ uri = /** @type {T} */+ normalizeString(uri, options);+ } else if (typeof uri === "object") {+ uri = /** @type {T} */+ parse3(serialize(uri, options), options);+ }+ return uri;+ }+ function resolve2(baseURI, relativeURI, options) {+ const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };+ const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true);+ schemelessOptions.skipEscape = true;+ return serialize(resolved, schemelessOptions);+ }+ function resolveComponent(base, relative, options, skipNormalization) {+ const target = {};+ if (!skipNormalization) {+ base = parse3(serialize(base, options), options);+ relative = parse3(serialize(relative, options), options);+ }+ options = options || {};+ if (!options.tolerant && relative.scheme) {+ target.scheme = relative.scheme;+ target.userinfo = relative.userinfo;+ target.host = relative.host;+ target.port = relative.port;+ target.path = removeDotSegments(relative.path || "");+ target.query = relative.query;+ } else {+ if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {+ target.userinfo = relative.userinfo;+ target.host = relative.host;+ target.port = relative.port;+ target.path = removeDotSegments(relative.path || "");+ target.query = relative.query;+ } else {+ if (!relative.path) {+ target.path = base.path;+ if (relative.query !== void 0) {+ target.query = relative.query;+ } else {+ target.query = base.query;+ }+ } else {+ if (relative.path[0] === "/") {+ target.path = removeDotSegments(relative.path);+ } else {+ if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {+ target.path = "/" + relative.path;+ } else if (!base.path) {+ target.path = relative.path;+ } else {+ target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;+ }+ target.path = removeDotSegments(target.path);+ }+ target.query = relative.query;+ }+ target.userinfo = base.userinfo;+ target.host = base.host;+ target.port = base.port;+ }+ target.scheme = base.scheme;+ }+ target.fragment = relative.fragment;+ return target;+ }+ function equal(uriA, uriB, options) {+ const normalizedA = normalizeComparableURI(uriA, options);+ const normalizedB = normalizeComparableURI(uriB, options);+ return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA.toLowerCase() === normalizedB.toLowerCase();+ }+ function serialize(cmpts, opts) {+ const component = {+ host: cmpts.host,+ scheme: cmpts.scheme,+ userinfo: cmpts.userinfo,+ port: cmpts.port,+ path: cmpts.path,+ query: cmpts.query,+ nid: cmpts.nid,+ nss: cmpts.nss,+ uuid: cmpts.uuid,+ fragment: cmpts.fragment,+ reference: cmpts.reference,+ resourceName: cmpts.resourceName,+ secure: cmpts.secure,+ error: ""+ };+ const options = Object.assign({}, opts);+ const uriTokens = [];+ const schemeHandler = getSchemeHandler(options.scheme || component.scheme);+ if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);+ if (component.path !== void 0) {+ if (!options.skipEscape) {+ component.path = escapePreservingEscapes(component.path);+ if (component.scheme !== void 0) {+ component.path = component.path.split("%3A").join(":");+ }+ } else {+ component.path = normalizePercentEncoding(component.path);+ }+ }+ if (options.reference !== "suffix" && component.scheme) {+ uriTokens.push(component.scheme, ":");+ }+ const authority = recomposeAuthority(component);+ if (authority !== void 0) {+ if (options.reference !== "suffix") {+ uriTokens.push("//");+ }+ uriTokens.push(authority);+ if (component.path && component.path[0] !== "/") {+ uriTokens.push("/");+ }+ }+ if (component.path !== void 0) {+ let s = component.path;+ if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {+ s = removeDotSegments(s);+ }+ if (authority === void 0 && s[0] === "/" && s[1] === "/") {+ s = "/%2F" + s.slice(2);+ }+ uriTokens.push(s);+ }+ if (component.query !== void 0) {+ uriTokens.push("?", component.query);+ }+ if (component.fragment !== void 0) {+ uriTokens.push("#", component.fragment);+ }+ return uriTokens.join("");+ }+ var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;+ function getParseError(parsed, matches) {+ if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") {+ return 'URI path must start with "/" when authority is present.';+ }+ if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {+ return "URI port is malformed.";+ }+ return void 0;+ }+ function parseWithStatus(uri, opts) {+ const options = Object.assign({}, opts);+ const parsed = {+ scheme: void 0,+ userinfo: void 0,+ host: "",+ port: void 0,+ path: "",+ query: void 0,+ fragment: void 0+ };+ let malformedAuthorityOrPort = false;+ let isIP = false;+ if (options.reference === "suffix") {+ if (options.scheme) {+ uri = options.scheme + ":" + uri;+ } else {+ uri = "//" + uri;+ }+ }+ const matches = uri.match(URI_PARSE);+ if (matches) {+ parsed.scheme = matches[1];+ parsed.userinfo = matches[3];+ parsed.host = matches[4];+ parsed.port = parseInt(matches[5], 10);+ parsed.path = matches[6] || "";+ parsed.query = matches[7];+ parsed.fragment = matches[8];+ if (isNaN(parsed.port)) {+ parsed.port = matches[5];+ }+ const parseError = getParseError(parsed, matches);+ if (parseError !== void 0) {+ parsed.error = parsed.error || parseError;+ malformedAuthorityOrPort = true;+ }+ if (parsed.host) {+ const ipv4result = isIPv4(parsed.host);+ if (ipv4result === false) {+ const ipv6result = normalizeIPv6(parsed.host);+ parsed.host = ipv6result.host.toLowerCase();+ isIP = ipv6result.isIPV6;+ } else {+ isIP = true;+ }+ }+ if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {+ parsed.reference = "same-document";+ } else if (parsed.scheme === void 0) {+ parsed.reference = "relative";+ } else if (parsed.fragment === void 0) {+ parsed.reference = "absolute";+ } else {+ parsed.reference = "uri";+ }+ if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {+ parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";+ }+ const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);+ if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {+ if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {+ try {+ parsed.host = new URL("http://" + parsed.host).hostname;+ } catch (e) {+ parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;+ }+ }+ }+ if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {+ if (uri.indexOf("%") !== -1) {+ if (parsed.scheme !== void 0) {+ parsed.scheme = unescape(parsed.scheme);+ }+ if (parsed.host !== void 0) {+ parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);+ }+ }+ if (parsed.path) {+ parsed.path = normalizePathEncoding(parsed.path);+ }+ if (parsed.fragment) {+ try {+ parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));+ } catch {+ parsed.error = parsed.error || "URI malformed";+ }+ }+ }+ if (schemeHandler && schemeHandler.parse) {+ schemeHandler.parse(parsed, options);+ }+ } else {+ parsed.error = parsed.error || "URI can not be parsed.";+ }+ return { parsed, malformedAuthorityOrPort };+ }+ function parse3(uri, opts) {+ return parseWithStatus(uri, opts).parsed;+ }+ function normalizeString(uri, opts) {+ return normalizeStringWithStatus(uri, opts).normalized;+ }+ function normalizeStringWithStatus(uri, opts) {+ const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);+ return {+ normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),+ malformedAuthorityOrPort+ };+ }+ function normalizeComparableURI(uri, opts) {+ if (typeof uri === "string") {+ const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);+ return malformedAuthorityOrPort ? void 0 : normalized;+ }+ if (typeof uri === "object") {+ return serialize(uri, opts);+ }+ }+ var fastUri = {+ SCHEMES,+ normalize,+ resolve: resolve2,+ resolveComponent,+ equal,+ serialize,+ parse: parse3+ };+ module.exports = fastUri;+ module.exports.default = fastUri;+ module.exports.fastUri = fastUri;+ }+});++// node_modules/ajv/dist/runtime/uri.js+var require_uri = __commonJS({+ "node_modules/ajv/dist/runtime/uri.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var uri = require_fast_uri();+ uri.code = 'require("ajv/dist/runtime/uri").default';+ exports.default = uri;+ }+});++// node_modules/ajv/dist/core.js+var require_core = __commonJS({+ "node_modules/ajv/dist/core.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;+ var validate_1 = require_validate();+ Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {+ return validate_1.KeywordCxt;+ } });+ var codegen_1 = require_codegen();+ Object.defineProperty(exports, "_", { enumerable: true, get: function() {+ return codegen_1._;+ } });+ Object.defineProperty(exports, "str", { enumerable: true, get: function() {+ return codegen_1.str;+ } });+ Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {+ return codegen_1.stringify;+ } });+ Object.defineProperty(exports, "nil", { enumerable: true, get: function() {+ return codegen_1.nil;+ } });+ Object.defineProperty(exports, "Name", { enumerable: true, get: function() {+ return codegen_1.Name;+ } });+ Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {+ return codegen_1.CodeGen;+ } });+ var validation_error_1 = require_validation_error();+ var ref_error_1 = require_ref_error();+ var rules_1 = require_rules();+ var compile_1 = require_compile();+ var codegen_2 = require_codegen();+ var resolve_1 = require_resolve();+ var dataType_1 = require_dataType();+ var util_1 = require_util();+ var $dataRefSchema = require_data();+ var uri_1 = require_uri();+ var defaultRegExp = (str, flags) => new RegExp(str, flags);+ defaultRegExp.code = "new RegExp";+ var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];+ var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([+ "validate",+ "serialize",+ "parse",+ "wrapper",+ "root",+ "schema",+ "keyword",+ "pattern",+ "formats",+ "validate$data",+ "func",+ "obj",+ "Error"+ ]);+ var removedOptions = {+ errorDataPath: "",+ format: "`validateFormats: false` can be used instead.",+ nullable: '"nullable" keyword is supported by default.',+ jsonPointers: "Deprecated jsPropertySyntax can be used instead.",+ extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",+ missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",+ processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",+ sourceCode: "Use option `code: {source: true}`",+ strictDefaults: "It is default now, see option `strict`.",+ strictKeywords: "It is default now, see option `strict`.",+ uniqueItems: '"uniqueItems" keyword is always validated.',+ unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",+ cache: "Map is used as cache, schema object as key.",+ serialize: "Map is used as cache, schema object as key.",+ ajvErrors: "It is default now."+ };+ var deprecatedOptions = {+ ignoreKeywordsWithRef: "",+ jsPropertySyntax: "",+ unicode: '"minLength"/"maxLength" account for unicode characters by default.'+ };+ var MAX_EXPRESSION = 200;+ function requiredOptions(o) {+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;+ const s = o.strict;+ const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;+ const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;+ const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;+ const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;+ return {+ strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,+ strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,+ strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",+ strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",+ strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,+ code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },+ loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,+ loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,+ meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,+ messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,+ inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,+ schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",+ addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,+ validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,+ validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,+ unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,+ int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,+ uriResolver+ };+ }+ var Ajv2 = class {+ constructor(opts = {}) {+ this.schemas = {};+ this.refs = {};+ this.formats = /* @__PURE__ */ Object.create(null);+ this._compilations = /* @__PURE__ */ new Set();+ this._loading = {};+ this._cache = /* @__PURE__ */ new Map();+ opts = this.opts = { ...opts, ...requiredOptions(opts) };+ const { es5, lines } = this.opts.code;+ this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });+ this.logger = getLogger(opts.logger);+ const formatOpt = opts.validateFormats;+ opts.validateFormats = false;+ this.RULES = (0, rules_1.getRules)();+ checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");+ checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");+ this._metaOpts = getMetaSchemaOptions.call(this);+ if (opts.formats)+ addInitialFormats.call(this);+ this._addVocabularies();+ this._addDefaultMetaSchema();+ if (opts.keywords)+ addInitialKeywords.call(this, opts.keywords);+ if (typeof opts.meta == "object")+ this.addMetaSchema(opts.meta);+ addInitialSchemas.call(this);+ opts.validateFormats = formatOpt;+ }+ _addVocabularies() {+ this.addKeyword("$async");+ }+ _addDefaultMetaSchema() {+ const { $data, meta, schemaId } = this.opts;+ let _dataRefSchema = $dataRefSchema;+ if (schemaId === "id") {+ _dataRefSchema = { ...$dataRefSchema };+ _dataRefSchema.id = _dataRefSchema.$id;+ delete _dataRefSchema.$id;+ }+ if (meta && $data)+ this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);+ }+ defaultMeta() {+ const { meta, schemaId } = this.opts;+ return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;+ }+ validate(schemaKeyRef, data) {+ let v;+ if (typeof schemaKeyRef == "string") {+ v = this.getSchema(schemaKeyRef);+ if (!v)+ throw new Error(`no schema with key or ref "${schemaKeyRef}"`);+ } else {+ v = this.compile(schemaKeyRef);+ }+ const valid = v(data);+ if (!("$async" in v))+ this.errors = v.errors;+ return valid;+ }+ compile(schema, _meta) {+ const sch = this._addSchema(schema, _meta);+ return sch.validate || this._compileSchemaEnv(sch);+ }+ compileAsync(schema, meta) {+ if (typeof this.opts.loadSchema != "function") {+ throw new Error("options.loadSchema should be a function");+ }+ const { loadSchema } = this.opts;+ return runCompileAsync.call(this, schema, meta);+ async function runCompileAsync(_schema, _meta) {+ await loadMetaSchema.call(this, _schema.$schema);+ const sch = this._addSchema(_schema, _meta);+ return sch.validate || _compileAsync.call(this, sch);+ }+ async function loadMetaSchema($ref) {+ if ($ref && !this.getSchema($ref)) {+ await runCompileAsync.call(this, { $ref }, true);+ }+ }+ async function _compileAsync(sch) {+ try {+ return this._compileSchemaEnv(sch);+ } catch (e) {+ if (!(e instanceof ref_error_1.default))+ throw e;+ checkLoaded.call(this, e);+ await loadMissingSchema.call(this, e.missingSchema);+ return _compileAsync.call(this, sch);+ }+ }+ function checkLoaded({ missingSchema: ref, missingRef }) {+ if (this.refs[ref]) {+ throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);+ }+ }+ async function loadMissingSchema(ref) {+ const _schema = await _loadSchema.call(this, ref);+ if (!this.refs[ref])+ await loadMetaSchema.call(this, _schema.$schema);+ if (!this.refs[ref])+ this.addSchema(_schema, ref, meta);+ }+ async function _loadSchema(ref) {+ const p = this._loading[ref];+ if (p)+ return p;+ try {+ return await (this._loading[ref] = loadSchema(ref));+ } finally {+ delete this._loading[ref];+ }+ }+ }+ // Adds schema to the instance+ addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {+ if (Array.isArray(schema)) {+ for (const sch of schema)+ this.addSchema(sch, void 0, _meta, _validateSchema);+ return this;+ }+ let id;+ if (typeof schema === "object") {+ const { schemaId } = this.opts;+ id = schema[schemaId];+ if (id !== void 0 && typeof id != "string") {+ throw new Error(`schema ${schemaId} must be string`);+ }+ }+ key = (0, resolve_1.normalizeId)(key || id);+ this._checkUnique(key);+ this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);+ return this;+ }+ // Add schema that will be used to validate other schemas+ // options in META_IGNORE_OPTIONS are alway set to false+ addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {+ this.addSchema(schema, key, true, _validateSchema);+ return this;+ }+ // Validate schema against its meta-schema+ validateSchema(schema, throwOrLogError) {+ if (typeof schema == "boolean")+ return true;+ let $schema;+ $schema = schema.$schema;+ if ($schema !== void 0 && typeof $schema != "string") {+ throw new Error("$schema must be a string");+ }+ $schema = $schema || this.opts.defaultMeta || this.defaultMeta();+ if (!$schema) {+ this.logger.warn("meta-schema not available");+ this.errors = null;+ return true;+ }+ const valid = this.validate($schema, schema);+ if (!valid && throwOrLogError) {+ const message = "schema is invalid: " + this.errorsText();+ if (this.opts.validateSchema === "log")+ this.logger.error(message);+ else+ throw new Error(message);+ }+ return valid;+ }+ // Get compiled schema by `key` or `ref`.+ // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)+ getSchema(keyRef) {+ let sch;+ while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")+ keyRef = sch;+ if (sch === void 0) {+ const { schemaId } = this.opts;+ const root = new compile_1.SchemaEnv({ schema: {}, schemaId });+ sch = compile_1.resolveSchema.call(this, root, keyRef);+ if (!sch)+ return;+ this.refs[keyRef] = sch;+ }+ return sch.validate || this._compileSchemaEnv(sch);+ }+ // Remove cached schema(s).+ // If no parameter is passed all schemas but meta-schemas are removed.+ // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.+ // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.+ removeSchema(schemaKeyRef) {+ if (schemaKeyRef instanceof RegExp) {+ this._removeAllSchemas(this.schemas, schemaKeyRef);+ this._removeAllSchemas(this.refs, schemaKeyRef);+ return this;+ }+ switch (typeof schemaKeyRef) {+ case "undefined":+ this._removeAllSchemas(this.schemas);+ this._removeAllSchemas(this.refs);+ this._cache.clear();+ return this;+ case "string": {+ const sch = getSchEnv.call(this, schemaKeyRef);+ if (typeof sch == "object")+ this._cache.delete(sch.schema);+ delete this.schemas[schemaKeyRef];+ delete this.refs[schemaKeyRef];+ return this;+ }+ case "object": {+ const cacheKey = schemaKeyRef;+ this._cache.delete(cacheKey);+ let id = schemaKeyRef[this.opts.schemaId];+ if (id) {+ id = (0, resolve_1.normalizeId)(id);+ delete this.schemas[id];+ delete this.refs[id];+ }+ return this;+ }+ default:+ throw new Error("ajv.removeSchema: invalid parameter");+ }+ }+ // add "vocabulary" - a collection of keywords+ addVocabulary(definitions) {+ for (const def of definitions)+ this.addKeyword(def);+ return this;+ }+ addKeyword(kwdOrDef, def) {+ let keyword;+ if (typeof kwdOrDef == "string") {+ keyword = kwdOrDef;+ if (typeof def == "object") {+ this.logger.warn("these parameters are deprecated, see docs for addKeyword");+ def.keyword = keyword;+ }+ } else if (typeof kwdOrDef == "object" && def === void 0) {+ def = kwdOrDef;+ keyword = def.keyword;+ if (Array.isArray(keyword) && !keyword.length) {+ throw new Error("addKeywords: keyword must be string or non-empty array");+ }+ } else {+ throw new Error("invalid addKeywords parameters");+ }+ checkKeyword.call(this, keyword, def);+ if (!def) {+ (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));+ return this;+ }+ keywordMetaschema.call(this, def);+ const definition = {+ ...def,+ type: (0, dataType_1.getJSONTypes)(def.type),+ schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)+ };+ (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));+ return this;+ }+ getKeyword(keyword) {+ const rule = this.RULES.all[keyword];+ return typeof rule == "object" ? rule.definition : !!rule;+ }+ // Remove keyword+ removeKeyword(keyword) {+ const { RULES } = this;+ delete RULES.keywords[keyword];+ delete RULES.all[keyword];+ for (const group of RULES.rules) {+ const i = group.rules.findIndex((rule) => rule.keyword === keyword);+ if (i >= 0)+ group.rules.splice(i, 1);+ }+ return this;+ }+ // Add format+ addFormat(name3, format) {+ if (typeof format == "string")+ format = new RegExp(format);+ this.formats[name3] = format;+ return this;+ }+ errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {+ if (!errors || errors.length === 0)+ return "No errors";+ return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);+ }+ $dataMetaSchema(metaSchema, keywordsJsonPointers) {+ const rules = this.RULES.all;+ metaSchema = JSON.parse(JSON.stringify(metaSchema));+ for (const jsonPointer of keywordsJsonPointers) {+ const segments = jsonPointer.split("/").slice(1);+ let keywords = metaSchema;+ for (const seg of segments)+ keywords = keywords[seg];+ for (const key in rules) {+ const rule = rules[key];+ if (typeof rule != "object")+ continue;+ const { $data } = rule.definition;+ const schema = keywords[key];+ if ($data && schema)+ keywords[key] = schemaOrData(schema);+ }+ }+ return metaSchema;+ }+ _removeAllSchemas(schemas, regex) {+ for (const keyRef in schemas) {+ const sch = schemas[keyRef];+ if (!regex || regex.test(keyRef)) {+ if (typeof sch == "string") {+ delete schemas[keyRef];+ } else if (sch && !sch.meta) {+ this._cache.delete(sch.schema);+ delete schemas[keyRef];+ }+ }+ }+ }+ _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {+ let id;+ const { schemaId } = this.opts;+ if (typeof schema == "object") {+ id = schema[schemaId];+ } else {+ if (this.opts.jtd)+ throw new Error("schema must be object");+ else if (typeof schema != "boolean")+ throw new Error("schema must be object or boolean");+ }+ let sch = this._cache.get(schema);+ if (sch !== void 0)+ return sch;+ baseId = (0, resolve_1.normalizeId)(id || baseId);+ const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);+ sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });+ this._cache.set(sch.schema, sch);+ if (addSchema && !baseId.startsWith("#")) {+ if (baseId)+ this._checkUnique(baseId);+ this.refs[baseId] = sch;+ }+ if (validateSchema)+ this.validateSchema(schema, true);+ return sch;+ }+ _checkUnique(id) {+ if (this.schemas[id] || this.refs[id]) {+ throw new Error(`schema with key or id "${id}" already exists`);+ }+ }+ _compileSchemaEnv(sch) {+ if (sch.meta)+ this._compileMetaSchema(sch);+ else+ compile_1.compileSchema.call(this, sch);+ if (!sch.validate)+ throw new Error("ajv implementation error");+ return sch.validate;+ }+ _compileMetaSchema(sch) {+ const currentOpts = this.opts;+ this.opts = this._metaOpts;+ try {+ compile_1.compileSchema.call(this, sch);+ } finally {+ this.opts = currentOpts;+ }+ }+ };+ Ajv2.ValidationError = validation_error_1.default;+ Ajv2.MissingRefError = ref_error_1.default;+ exports.default = Ajv2;+ function checkOptions(checkOpts, options, msg, log = "error") {+ for (const key in checkOpts) {+ const opt = key;+ if (opt in options)+ this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);+ }+ }+ function getSchEnv(keyRef) {+ keyRef = (0, resolve_1.normalizeId)(keyRef);+ return this.schemas[keyRef] || this.refs[keyRef];+ }+ function addInitialSchemas() {+ const optsSchemas = this.opts.schemas;+ if (!optsSchemas)+ return;+ if (Array.isArray(optsSchemas))+ this.addSchema(optsSchemas);+ else+ for (const key in optsSchemas)+ this.addSchema(optsSchemas[key], key);+ }+ function addInitialFormats() {+ for (const name3 in this.opts.formats) {+ const format = this.opts.formats[name3];+ if (format)+ this.addFormat(name3, format);+ }+ }+ function addInitialKeywords(defs) {+ if (Array.isArray(defs)) {+ this.addVocabulary(defs);+ return;+ }+ this.logger.warn("keywords option as map is deprecated, pass array");+ for (const keyword in defs) {+ const def = defs[keyword];+ if (!def.keyword)+ def.keyword = keyword;+ this.addKeyword(def);+ }+ }+ function getMetaSchemaOptions() {+ const metaOpts = { ...this.opts };+ for (const opt of META_IGNORE_OPTIONS)+ delete metaOpts[opt];+ return metaOpts;+ }+ var noLogs = { log() {+ }, warn() {+ }, error() {+ } };+ function getLogger(logger2) {+ if (logger2 === false)+ return noLogs;+ if (logger2 === void 0)+ return console;+ if (logger2.log && logger2.warn && logger2.error)+ return logger2;+ throw new Error("logger must implement log, warn and error methods");+ }+ var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;+ function checkKeyword(keyword, def) {+ const { RULES } = this;+ (0, util_1.eachItem)(keyword, (kwd) => {+ if (RULES.keywords[kwd])+ throw new Error(`Keyword ${kwd} is already defined`);+ if (!KEYWORD_NAME.test(kwd))+ throw new Error(`Keyword ${kwd} has invalid name`);+ });+ if (!def)+ return;+ if (def.$data && !("code" in def || "validate" in def)) {+ throw new Error('$data keyword must have "code" or "validate" function');+ }+ }+ function addRule(keyword, definition, dataType) {+ var _a;+ const post = definition === null || definition === void 0 ? void 0 : definition.post;+ if (dataType && post)+ throw new Error('keyword with "post" flag cannot have "type"');+ const { RULES } = this;+ let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);+ if (!ruleGroup) {+ ruleGroup = { type: dataType, rules: [] };+ RULES.rules.push(ruleGroup);+ }+ RULES.keywords[keyword] = true;+ if (!definition)+ return;+ const rule = {+ keyword,+ definition: {+ ...definition,+ type: (0, dataType_1.getJSONTypes)(definition.type),+ schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)+ }+ };+ if (definition.before)+ addBeforeRule.call(this, ruleGroup, rule, definition.before);+ else+ ruleGroup.rules.push(rule);+ RULES.all[keyword] = rule;+ (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));+ }+ function addBeforeRule(ruleGroup, rule, before) {+ const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);+ if (i >= 0) {+ ruleGroup.rules.splice(i, 0, rule);+ } else {+ ruleGroup.rules.push(rule);+ this.logger.warn(`rule ${before} is not defined`);+ }+ }+ function keywordMetaschema(def) {+ let { metaSchema } = def;+ if (metaSchema === void 0)+ return;+ if (def.$data && this.opts.$data)+ metaSchema = schemaOrData(metaSchema);+ def.validateSchema = this.compile(metaSchema, true);+ }+ var $dataRef = {+ $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"+ };+ function schemaOrData(schema) {+ return { anyOf: [schema, $dataRef] };+ }+ }+});++// node_modules/ajv/dist/vocabularies/core/id.js+var require_id = __commonJS({+ "node_modules/ajv/dist/vocabularies/core/id.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var def = {+ keyword: "id",+ code() {+ throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/core/ref.js+var require_ref = __commonJS({+ "node_modules/ajv/dist/vocabularies/core/ref.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.callRef = exports.getValidate = void 0;+ var ref_error_1 = require_ref_error();+ var code_1 = require_code2();+ var codegen_1 = require_codegen();+ var names_1 = require_names();+ var compile_1 = require_compile();+ var util_1 = require_util();+ var def = {+ keyword: "$ref",+ schemaType: "string",+ code(cxt) {+ const { gen, schema: $ref, it } = cxt;+ const { baseId, schemaEnv: env, validateName, opts, self } = it;+ const { root } = env;+ if (($ref === "#" || $ref === "#/") && baseId === root.baseId)+ return callRootRef();+ const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);+ if (schOrEnv === void 0)+ throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);+ if (schOrEnv instanceof compile_1.SchemaEnv)+ return callValidate(schOrEnv);+ return inlineRefSchema(schOrEnv);+ function callRootRef() {+ if (env === root)+ return callRef(cxt, validateName, env, env.$async);+ const rootName = gen.scopeValue("root", { ref: root });+ return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);+ }+ function callValidate(sch) {+ const v = getValidate(cxt, sch);+ callRef(cxt, v, sch, sch.$async);+ }+ function inlineRefSchema(sch) {+ const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });+ const valid = gen.name("valid");+ const schCxt = cxt.subschema({+ schema: sch,+ dataTypes: [],+ schemaPath: codegen_1.nil,+ topSchemaRef: schName,+ errSchemaPath: $ref+ }, valid);+ cxt.mergeEvaluated(schCxt);+ cxt.ok(valid);+ }+ }+ };+ function getValidate(cxt, sch) {+ const { gen } = cxt;+ return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;+ }+ exports.getValidate = getValidate;+ function callRef(cxt, v, sch, $async) {+ const { gen, it } = cxt;+ const { allErrors, schemaEnv: env, opts } = it;+ const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;+ if ($async)+ callAsyncRef();+ else+ callSyncRef();+ function callAsyncRef() {+ if (!env.$async)+ throw new Error("async schema referenced by sync schema");+ const valid = gen.let("valid");+ gen.try(() => {+ gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);+ addEvaluatedFrom(v);+ if (!allErrors)+ gen.assign(valid, true);+ }, (e) => {+ gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));+ addErrorsFrom(e);+ if (!allErrors)+ gen.assign(valid, false);+ });+ cxt.ok(valid);+ }+ function callSyncRef() {+ cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));+ }+ function addErrorsFrom(source) {+ const errs = (0, codegen_1._)`${source}.errors`;+ gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);+ gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);+ }+ function addEvaluatedFrom(source) {+ var _a;+ if (!it.opts.unevaluated)+ return;+ const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;+ if (it.props !== true) {+ if (schEvaluated && !schEvaluated.dynamicProps) {+ if (schEvaluated.props !== void 0) {+ it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);+ }+ } else {+ const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);+ it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);+ }+ }+ if (it.items !== true) {+ if (schEvaluated && !schEvaluated.dynamicItems) {+ if (schEvaluated.items !== void 0) {+ it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);+ }+ } else {+ const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);+ it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);+ }+ }+ }+ }+ exports.callRef = callRef;+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/core/index.js+var require_core2 = __commonJS({+ "node_modules/ajv/dist/vocabularies/core/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var id_1 = require_id();+ var ref_1 = require_ref();+ var core = [+ "$schema",+ "$id",+ "$defs",+ "$vocabulary",+ { keyword: "$comment" },+ "definitions",+ id_1.default,+ ref_1.default+ ];+ exports.default = core;+ }+});++// node_modules/ajv/dist/vocabularies/validation/limitNumber.js+var require_limitNumber = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var ops = codegen_1.operators;+ var KWDs = {+ maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },+ minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },+ exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },+ exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }+ };+ var error2 = {+ message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,+ params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`+ };+ var def = {+ keyword: Object.keys(KWDs),+ type: "number",+ schemaType: "number",+ $data: true,+ error: error2,+ code(cxt) {+ const { keyword, data, schemaCode } = cxt;+ cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/multipleOf.js+var require_multipleOf = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var error2 = {+ message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,+ params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`+ };+ var def = {+ keyword: "multipleOf",+ type: "number",+ schemaType: "number",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, schemaCode, it } = cxt;+ const prec = it.opts.multipleOfPrecision;+ const res = gen.let("res");+ const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/runtime/ucs2length.js+var require_ucs2length = __commonJS({+ "node_modules/ajv/dist/runtime/ucs2length.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ function ucs2length(str) {+ const len = str.length;+ let length = 0;+ let pos = 0;+ let value;+ while (pos < len) {+ length++;+ value = str.charCodeAt(pos++);+ if (value >= 55296 && value <= 56319 && pos < len) {+ value = str.charCodeAt(pos);+ if ((value & 64512) === 56320)+ pos++;+ }+ }+ return length;+ }+ exports.default = ucs2length;+ ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';+ }+});++// node_modules/ajv/dist/vocabularies/validation/limitLength.js+var require_limitLength = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var ucs2length_1 = require_ucs2length();+ var error2 = {+ message({ keyword, schemaCode }) {+ const comp = keyword === "maxLength" ? "more" : "fewer";+ return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;+ },+ params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`+ };+ var def = {+ keyword: ["maxLength", "minLength"],+ type: "string",+ schemaType: "number",+ $data: true,+ error: error2,+ code(cxt) {+ const { keyword, data, schemaCode, it } = cxt;+ const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;+ const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;+ cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/pattern.js+var require_pattern = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var code_1 = require_code2();+ var util_1 = require_util();+ var codegen_1 = require_codegen();+ var error2 = {+ message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,+ params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`+ };+ var def = {+ keyword: "pattern",+ type: "string",+ schemaType: "string",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, $data, schema, schemaCode, it } = cxt;+ const u = it.opts.unicodeRegExp ? "u" : "";+ if ($data) {+ const { regExp } = it.opts.code;+ const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);+ const valid = gen.let("valid");+ gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));+ cxt.fail$data((0, codegen_1._)`!${valid}`);+ } else {+ const regExp = (0, code_1.usePattern)(cxt, schema);+ cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/limitProperties.js+var require_limitProperties = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var error2 = {+ message({ keyword, schemaCode }) {+ const comp = keyword === "maxProperties" ? "more" : "fewer";+ return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;+ },+ params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`+ };+ var def = {+ keyword: ["maxProperties", "minProperties"],+ type: "object",+ schemaType: "number",+ $data: true,+ error: error2,+ code(cxt) {+ const { keyword, data, schemaCode } = cxt;+ const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;+ cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/required.js+var require_required = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/required.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var code_1 = require_code2();+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,+ params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`+ };+ var def = {+ keyword: "required",+ type: "object",+ schemaType: "array",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, schema, schemaCode, data, $data, it } = cxt;+ const { opts } = it;+ if (!$data && schema.length === 0)+ return;+ const useLoop = schema.length >= opts.loopRequired;+ if (it.allErrors)+ allErrorsMode();+ else+ exitOnErrorMode();+ if (opts.strictRequired) {+ const props = cxt.parentSchema.properties;+ const { definedProperties } = cxt.it;+ for (const requiredKey of schema) {+ if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {+ const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;+ const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;+ (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);+ }+ }+ }+ function allErrorsMode() {+ if (useLoop || $data) {+ cxt.block$data(codegen_1.nil, loopAllRequired);+ } else {+ for (const prop of schema) {+ (0, code_1.checkReportMissingProp)(cxt, prop);+ }+ }+ }+ function exitOnErrorMode() {+ const missing = gen.let("missing");+ if (useLoop || $data) {+ const valid = gen.let("valid", true);+ cxt.block$data(valid, () => loopUntilMissing(missing, valid));+ cxt.ok(valid);+ } else {+ gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));+ (0, code_1.reportMissingProp)(cxt, missing);+ gen.else();+ }+ }+ function loopAllRequired() {+ gen.forOf("prop", schemaCode, (prop) => {+ cxt.setParams({ missingProperty: prop });+ gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());+ });+ }+ function loopUntilMissing(missing, valid) {+ cxt.setParams({ missingProperty: missing });+ gen.forOf(missing, schemaCode, () => {+ gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));+ gen.if((0, codegen_1.not)(valid), () => {+ cxt.error();+ gen.break();+ });+ }, codegen_1.nil);+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/limitItems.js+var require_limitItems = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var error2 = {+ message({ keyword, schemaCode }) {+ const comp = keyword === "maxItems" ? "more" : "fewer";+ return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;+ },+ params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`+ };+ var def = {+ keyword: ["maxItems", "minItems"],+ type: "array",+ schemaType: "number",+ $data: true,+ error: error2,+ code(cxt) {+ const { keyword, data, schemaCode } = cxt;+ const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;+ cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/runtime/equal.js+var require_equal = __commonJS({+ "node_modules/ajv/dist/runtime/equal.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var equal = require_fast_deep_equal();+ equal.code = 'require("ajv/dist/runtime/equal").default';+ exports.default = equal;+ }+});++// node_modules/ajv/dist/vocabularies/validation/uniqueItems.js+var require_uniqueItems = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var dataType_1 = require_dataType();+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var equal_1 = require_equal();+ var error2 = {+ message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,+ params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`+ };+ var def = {+ keyword: "uniqueItems",+ type: "array",+ schemaType: "boolean",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;+ if (!$data && !schema)+ return;+ const valid = gen.let("valid");+ const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];+ cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);+ cxt.ok(valid);+ function validateUniqueItems() {+ const i = gen.let("i", (0, codegen_1._)`${data}.length`);+ const j = gen.let("j");+ cxt.setParams({ i, j });+ gen.assign(valid, true);+ gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));+ }+ function canOptimize() {+ return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");+ }+ function loopN(i, j) {+ const item = gen.name("item");+ const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);+ const indices = gen.const("indices", (0, codegen_1._)`{}`);+ gen.for((0, codegen_1._)`;${i}--;`, () => {+ gen.let(item, (0, codegen_1._)`${data}[${i}]`);+ gen.if(wrongType, (0, codegen_1._)`continue`);+ if (itemTypes.length > 1)+ gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);+ gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {+ gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);+ cxt.error();+ gen.assign(valid, false).break();+ }).code((0, codegen_1._)`${indices}[${item}] = ${i}`);+ });+ }+ function loopN2(i, j) {+ const eql = (0, util_1.useFunc)(gen, equal_1.default);+ const outer = gen.name("outer");+ gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {+ cxt.error();+ gen.assign(valid, false).break(outer);+ })));+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/const.js+var require_const = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/const.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var equal_1 = require_equal();+ var error2 = {+ message: "must be equal to constant",+ params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`+ };+ var def = {+ keyword: "const",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, $data, schemaCode, schema } = cxt;+ if ($data || schema && typeof schema == "object") {+ cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);+ } else {+ cxt.fail((0, codegen_1._)`${schema} !== ${data}`);+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/enum.js+var require_enum = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var equal_1 = require_equal();+ var error2 = {+ message: "must be equal to one of the allowed values",+ params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`+ };+ var def = {+ keyword: "enum",+ schemaType: "array",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, $data, schema, schemaCode, it } = cxt;+ if (!$data && schema.length === 0)+ throw new Error("enum must have non-empty array");+ const useLoop = schema.length >= it.opts.loopEnum;+ let eql;+ const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);+ let valid;+ if (useLoop || $data) {+ valid = gen.let("valid");+ cxt.block$data(valid, loopEnum);+ } else {+ if (!Array.isArray(schema))+ throw new Error("ajv implementation error");+ const vSchema = gen.const("vSchema", schemaCode);+ valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));+ }+ cxt.pass(valid);+ function loopEnum() {+ gen.assign(valid, false);+ gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));+ }+ function equalCode(vSchema, i) {+ const sch = schema[i];+ return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/validation/index.js+var require_validation = __commonJS({+ "node_modules/ajv/dist/vocabularies/validation/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var limitNumber_1 = require_limitNumber();+ var multipleOf_1 = require_multipleOf();+ var limitLength_1 = require_limitLength();+ var pattern_1 = require_pattern();+ var limitProperties_1 = require_limitProperties();+ var required_1 = require_required();+ var limitItems_1 = require_limitItems();+ var uniqueItems_1 = require_uniqueItems();+ var const_1 = require_const();+ var enum_1 = require_enum();+ var validation = [+ // number+ limitNumber_1.default,+ multipleOf_1.default,+ // string+ limitLength_1.default,+ pattern_1.default,+ // object+ limitProperties_1.default,+ required_1.default,+ // array+ limitItems_1.default,+ uniqueItems_1.default,+ // any+ { keyword: "type", schemaType: ["string", "array"] },+ { keyword: "nullable", schemaType: "boolean" },+ const_1.default,+ enum_1.default+ ];+ exports.default = validation;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/additionalItems.js+var require_additionalItems = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.validateAdditionalItems = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,+ params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`+ };+ var def = {+ keyword: "additionalItems",+ type: "array",+ schemaType: ["boolean", "object"],+ before: "uniqueItems",+ error: error2,+ code(cxt) {+ const { parentSchema, it } = cxt;+ const { items } = parentSchema;+ if (!Array.isArray(items)) {+ (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');+ return;+ }+ validateAdditionalItems(cxt, items);+ }+ };+ function validateAdditionalItems(cxt, items) {+ const { gen, schema, data, keyword, it } = cxt;+ it.items = true;+ const len = gen.const("len", (0, codegen_1._)`${data}.length`);+ if (schema === false) {+ cxt.setParams({ len: items.length });+ cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);+ } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {+ const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);+ gen.if((0, codegen_1.not)(valid), () => validateItems(valid));+ cxt.ok(valid);+ }+ function validateItems(valid) {+ gen.forRange("i", items.length, len, (i) => {+ cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);+ if (!it.allErrors)+ gen.if((0, codegen_1.not)(valid), () => gen.break());+ });+ }+ }+ exports.validateAdditionalItems = validateAdditionalItems;+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/items.js+var require_items = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.validateTuple = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var code_1 = require_code2();+ var def = {+ keyword: "items",+ type: "array",+ schemaType: ["object", "array", "boolean"],+ before: "uniqueItems",+ code(cxt) {+ const { schema, it } = cxt;+ if (Array.isArray(schema))+ return validateTuple(cxt, "additionalItems", schema);+ it.items = true;+ if ((0, util_1.alwaysValidSchema)(it, schema))+ return;+ cxt.ok((0, code_1.validateArray)(cxt));+ }+ };+ function validateTuple(cxt, extraItems, schArr = cxt.schema) {+ const { gen, parentSchema, data, keyword, it } = cxt;+ checkStrictTuple(parentSchema);+ if (it.opts.unevaluated && schArr.length && it.items !== true) {+ it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);+ }+ const valid = gen.name("valid");+ const len = gen.const("len", (0, codegen_1._)`${data}.length`);+ schArr.forEach((sch, i) => {+ if ((0, util_1.alwaysValidSchema)(it, sch))+ return;+ gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({+ keyword,+ schemaProp: i,+ dataProp: i+ }, valid));+ cxt.ok(valid);+ });+ function checkStrictTuple(sch) {+ const { opts, errSchemaPath } = it;+ const l = schArr.length;+ const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);+ if (opts.strictTuples && !fullTuple) {+ const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;+ (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);+ }+ }+ }+ exports.validateTuple = validateTuple;+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/prefixItems.js+var require_prefixItems = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var items_1 = require_items();+ var def = {+ keyword: "prefixItems",+ type: "array",+ schemaType: ["array"],+ before: "uniqueItems",+ code: (cxt) => (0, items_1.validateTuple)(cxt, "items")+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/items2020.js+var require_items2020 = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var code_1 = require_code2();+ var additionalItems_1 = require_additionalItems();+ var error2 = {+ message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,+ params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`+ };+ var def = {+ keyword: "items",+ type: "array",+ schemaType: ["object", "boolean"],+ before: "uniqueItems",+ error: error2,+ code(cxt) {+ const { schema, parentSchema, it } = cxt;+ const { prefixItems } = parentSchema;+ it.items = true;+ if ((0, util_1.alwaysValidSchema)(it, schema))+ return;+ if (prefixItems)+ (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);+ else+ cxt.ok((0, code_1.validateArray)(cxt));+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/contains.js+var require_contains = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,+ params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`+ };+ var def = {+ keyword: "contains",+ type: "array",+ schemaType: ["object", "boolean"],+ before: "uniqueItems",+ trackErrors: true,+ error: error2,+ code(cxt) {+ const { gen, schema, parentSchema, data, it } = cxt;+ let min;+ let max;+ const { minContains, maxContains } = parentSchema;+ if (it.opts.next) {+ min = minContains === void 0 ? 1 : minContains;+ max = maxContains;+ } else {+ min = 1;+ }+ const len = gen.const("len", (0, codegen_1._)`${data}.length`);+ cxt.setParams({ min, max });+ if (max === void 0 && min === 0) {+ (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);+ return;+ }+ if (max !== void 0 && min > max) {+ (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);+ cxt.fail();+ return;+ }+ if ((0, util_1.alwaysValidSchema)(it, schema)) {+ let cond = (0, codegen_1._)`${len} >= ${min}`;+ if (max !== void 0)+ cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;+ cxt.pass(cond);+ return;+ }+ it.items = true;+ const valid = gen.name("valid");+ if (max === void 0 && min === 1) {+ validateItems(valid, () => gen.if(valid, () => gen.break()));+ } else if (min === 0) {+ gen.let(valid, true);+ if (max !== void 0)+ gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);+ } else {+ gen.let(valid, false);+ validateItemsWithCount();+ }+ cxt.result(valid, () => cxt.reset());+ function validateItemsWithCount() {+ const schValid = gen.name("_valid");+ const count = gen.let("count", 0);+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));+ }+ function validateItems(_valid, block) {+ gen.forRange("i", 0, len, (i) => {+ cxt.subschema({+ keyword: "contains",+ dataProp: i,+ dataPropType: util_1.Type.Num,+ compositeRule: true+ }, _valid);+ block();+ });+ }+ function checkLimits(count) {+ gen.code((0, codegen_1._)`${count}++`);+ if (max === void 0) {+ gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());+ } else {+ gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());+ if (min === 1)+ gen.assign(valid, true);+ else+ gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));+ }+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/dependencies.js+var require_dependencies = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var code_1 = require_code2();+ exports.error = {+ message: ({ params: { property, depsCount, deps } }) => {+ const property_ies = depsCount === 1 ? "property" : "properties";+ return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;+ },+ params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},+ missingProperty: ${missingProperty},+ depsCount: ${depsCount},+ deps: ${deps}}`+ // TODO change to reference+ };+ var def = {+ keyword: "dependencies",+ type: "object",+ schemaType: "object",+ error: exports.error,+ code(cxt) {+ const [propDeps, schDeps] = splitDependencies(cxt);+ validatePropertyDeps(cxt, propDeps);+ validateSchemaDeps(cxt, schDeps);+ }+ };+ function splitDependencies({ schema }) {+ const propertyDeps = {};+ const schemaDeps = {};+ for (const key in schema) {+ if (key === "__proto__")+ continue;+ const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;+ deps[key] = schema[key];+ }+ return [propertyDeps, schemaDeps];+ }+ function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {+ const { gen, data, it } = cxt;+ if (Object.keys(propertyDeps).length === 0)+ return;+ const missing = gen.let("missing");+ for (const prop in propertyDeps) {+ const deps = propertyDeps[prop];+ if (deps.length === 0)+ continue;+ const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);+ cxt.setParams({+ property: prop,+ depsCount: deps.length,+ deps: deps.join(", ")+ });+ if (it.allErrors) {+ gen.if(hasProperty, () => {+ for (const depProp of deps) {+ (0, code_1.checkReportMissingProp)(cxt, depProp);+ }+ });+ } else {+ gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);+ (0, code_1.reportMissingProp)(cxt, missing);+ gen.else();+ }+ }+ }+ exports.validatePropertyDeps = validatePropertyDeps;+ function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {+ const { gen, data, keyword, it } = cxt;+ const valid = gen.name("valid");+ for (const prop in schemaDeps) {+ if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))+ continue;+ gen.if(+ (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),+ () => {+ const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);+ cxt.mergeValidEvaluated(schCxt, valid);+ },+ () => gen.var(valid, true)+ // TODO var+ );+ cxt.ok(valid);+ }+ }+ exports.validateSchemaDeps = validateSchemaDeps;+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/propertyNames.js+var require_propertyNames = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: "property name must be valid",+ params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`+ };+ var def = {+ keyword: "propertyNames",+ type: "object",+ schemaType: ["object", "boolean"],+ error: error2,+ code(cxt) {+ const { gen, schema, data, it } = cxt;+ if ((0, util_1.alwaysValidSchema)(it, schema))+ return;+ const valid = gen.name("valid");+ gen.forIn("key", data, (key) => {+ cxt.setParams({ propertyName: key });+ cxt.subschema({+ keyword: "propertyNames",+ data: key,+ dataTypes: ["string"],+ propertyName: key,+ compositeRule: true+ }, valid);+ gen.if((0, codegen_1.not)(valid), () => {+ cxt.error(true);+ if (!it.allErrors)+ gen.break();+ });+ });+ cxt.ok(valid);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js+var require_additionalProperties = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var code_1 = require_code2();+ var codegen_1 = require_codegen();+ var names_1 = require_names();+ var util_1 = require_util();+ var error2 = {+ message: "must NOT have additional properties",+ params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`+ };+ var def = {+ keyword: "additionalProperties",+ type: ["object"],+ schemaType: ["boolean", "object"],+ allowUndefined: true,+ trackErrors: true,+ error: error2,+ code(cxt) {+ const { gen, schema, parentSchema, data, errsCount, it } = cxt;+ if (!errsCount)+ throw new Error("ajv implementation error");+ const { allErrors, opts } = it;+ it.props = true;+ if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))+ return;+ const props = (0, code_1.allSchemaProperties)(parentSchema.properties);+ const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);+ checkAdditionalProperties();+ cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);+ function checkAdditionalProperties() {+ gen.forIn("key", data, (key) => {+ if (!props.length && !patProps.length)+ additionalPropertyCode(key);+ else+ gen.if(isAdditional(key), () => additionalPropertyCode(key));+ });+ }+ function isAdditional(key) {+ let definedProp;+ if (props.length > 8) {+ const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");+ definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);+ } else if (props.length) {+ definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));+ } else {+ definedProp = codegen_1.nil;+ }+ if (patProps.length) {+ definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));+ }+ return (0, codegen_1.not)(definedProp);+ }+ function deleteAdditional(key) {+ gen.code((0, codegen_1._)`delete ${data}[${key}]`);+ }+ function additionalPropertyCode(key) {+ if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {+ deleteAdditional(key);+ return;+ }+ if (schema === false) {+ cxt.setParams({ additionalProperty: key });+ cxt.error();+ if (!allErrors)+ gen.break();+ return;+ }+ if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {+ const valid = gen.name("valid");+ if (opts.removeAdditional === "failing") {+ applyAdditionalSchema(key, valid, false);+ gen.if((0, codegen_1.not)(valid), () => {+ cxt.reset();+ deleteAdditional(key);+ });+ } else {+ applyAdditionalSchema(key, valid);+ if (!allErrors)+ gen.if((0, codegen_1.not)(valid), () => gen.break());+ }+ }+ }+ function applyAdditionalSchema(key, valid, errors) {+ const subschema = {+ keyword: "additionalProperties",+ dataProp: key,+ dataPropType: util_1.Type.Str+ };+ if (errors === false) {+ Object.assign(subschema, {+ compositeRule: true,+ createErrors: false,+ allErrors: false+ });+ }+ cxt.subschema(subschema, valid);+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/properties.js+var require_properties = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var validate_1 = require_validate();+ var code_1 = require_code2();+ var util_1 = require_util();+ var additionalProperties_1 = require_additionalProperties();+ var def = {+ keyword: "properties",+ type: "object",+ schemaType: "object",+ code(cxt) {+ const { gen, schema, parentSchema, data, it } = cxt;+ if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {+ additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));+ }+ const allProps = (0, code_1.allSchemaProperties)(schema);+ for (const prop of allProps) {+ it.definedProperties.add(prop);+ }+ if (it.opts.unevaluated && allProps.length && it.props !== true) {+ it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);+ }+ const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));+ if (properties.length === 0)+ return;+ const valid = gen.name("valid");+ for (const prop of properties) {+ if (hasDefault(prop)) {+ applyPropertySchema(prop);+ } else {+ gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));+ applyPropertySchema(prop);+ if (!it.allErrors)+ gen.else().var(valid, true);+ gen.endIf();+ }+ cxt.it.definedProperties.add(prop);+ cxt.ok(valid);+ }+ function hasDefault(prop) {+ return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;+ }+ function applyPropertySchema(prop) {+ cxt.subschema({+ keyword: "properties",+ schemaProp: prop,+ dataProp: prop+ }, valid);+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/patternProperties.js+var require_patternProperties = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var code_1 = require_code2();+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var util_2 = require_util();+ var def = {+ keyword: "patternProperties",+ type: "object",+ schemaType: "object",+ code(cxt) {+ const { gen, schema, data, parentSchema, it } = cxt;+ const { opts } = it;+ const patterns = (0, code_1.allSchemaProperties)(schema);+ const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));+ if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {+ return;+ }+ const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;+ const valid = gen.name("valid");+ if (it.props !== true && !(it.props instanceof codegen_1.Name)) {+ it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);+ }+ const { props } = it;+ validatePatternProperties();+ function validatePatternProperties() {+ for (const pat of patterns) {+ if (checkProperties)+ checkMatchingProperties(pat);+ if (it.allErrors) {+ validateProperties(pat);+ } else {+ gen.var(valid, true);+ validateProperties(pat);+ gen.if(valid);+ }+ }+ }+ function checkMatchingProperties(pat) {+ for (const prop in checkProperties) {+ if (new RegExp(pat).test(prop)) {+ (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);+ }+ }+ }+ function validateProperties(pat) {+ gen.forIn("key", data, (key) => {+ gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {+ const alwaysValid = alwaysValidPatterns.includes(pat);+ if (!alwaysValid) {+ cxt.subschema({+ keyword: "patternProperties",+ schemaProp: pat,+ dataProp: key,+ dataPropType: util_2.Type.Str+ }, valid);+ }+ if (it.opts.unevaluated && props !== true) {+ gen.assign((0, codegen_1._)`${props}[${key}]`, true);+ } else if (!alwaysValid && !it.allErrors) {+ gen.if((0, codegen_1.not)(valid), () => gen.break());+ }+ });+ });+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/not.js+var require_not = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var util_1 = require_util();+ var def = {+ keyword: "not",+ schemaType: ["object", "boolean"],+ trackErrors: true,+ code(cxt) {+ const { gen, schema, it } = cxt;+ if ((0, util_1.alwaysValidSchema)(it, schema)) {+ cxt.fail();+ return;+ }+ const valid = gen.name("valid");+ cxt.subschema({+ keyword: "not",+ compositeRule: true,+ createErrors: false,+ allErrors: false+ }, valid);+ cxt.failResult(valid, () => cxt.reset(), () => cxt.error());+ },+ error: { message: "must NOT be valid" }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/anyOf.js+var require_anyOf = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var code_1 = require_code2();+ var def = {+ keyword: "anyOf",+ schemaType: "array",+ trackErrors: true,+ code: code_1.validateUnion,+ error: { message: "must match a schema in anyOf" }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/oneOf.js+var require_oneOf = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: "must match exactly one schema in oneOf",+ params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`+ };+ var def = {+ keyword: "oneOf",+ schemaType: "array",+ trackErrors: true,+ error: error2,+ code(cxt) {+ const { gen, schema, parentSchema, it } = cxt;+ if (!Array.isArray(schema))+ throw new Error("ajv implementation error");+ if (it.opts.discriminator && parentSchema.discriminator)+ return;+ const schArr = schema;+ const valid = gen.let("valid", false);+ const passing = gen.let("passing", null);+ const schValid = gen.name("_valid");+ cxt.setParams({ passing });+ gen.block(validateOneOf);+ cxt.result(valid, () => cxt.reset(), () => cxt.error(true));+ function validateOneOf() {+ schArr.forEach((sch, i) => {+ let schCxt;+ if ((0, util_1.alwaysValidSchema)(it, sch)) {+ gen.var(schValid, true);+ } else {+ schCxt = cxt.subschema({+ keyword: "oneOf",+ schemaProp: i,+ compositeRule: true+ }, schValid);+ }+ if (i > 0) {+ gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();+ }+ gen.if(schValid, () => {+ gen.assign(valid, true);+ gen.assign(passing, i);+ if (schCxt)+ cxt.mergeEvaluated(schCxt, codegen_1.Name);+ });+ });+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/allOf.js+var require_allOf = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var util_1 = require_util();+ var def = {+ keyword: "allOf",+ schemaType: "array",+ code(cxt) {+ const { gen, schema, it } = cxt;+ if (!Array.isArray(schema))+ throw new Error("ajv implementation error");+ const valid = gen.name("valid");+ schema.forEach((sch, i) => {+ if ((0, util_1.alwaysValidSchema)(it, sch))+ return;+ const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);+ cxt.ok(valid);+ cxt.mergeEvaluated(schCxt);+ });+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/if.js+var require_if = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var util_1 = require_util();+ var error2 = {+ message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,+ params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`+ };+ var def = {+ keyword: "if",+ schemaType: ["object", "boolean"],+ trackErrors: true,+ error: error2,+ code(cxt) {+ const { gen, parentSchema, it } = cxt;+ if (parentSchema.then === void 0 && parentSchema.else === void 0) {+ (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');+ }+ const hasThen = hasSchema(it, "then");+ const hasElse = hasSchema(it, "else");+ if (!hasThen && !hasElse)+ return;+ const valid = gen.let("valid", true);+ const schValid = gen.name("_valid");+ validateIf();+ cxt.reset();+ if (hasThen && hasElse) {+ const ifClause = gen.let("ifClause");+ cxt.setParams({ ifClause });+ gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));+ } else if (hasThen) {+ gen.if(schValid, validateClause("then"));+ } else {+ gen.if((0, codegen_1.not)(schValid), validateClause("else"));+ }+ cxt.pass(valid, () => cxt.error(true));+ function validateIf() {+ const schCxt = cxt.subschema({+ keyword: "if",+ compositeRule: true,+ createErrors: false,+ allErrors: false+ }, schValid);+ cxt.mergeEvaluated(schCxt);+ }+ function validateClause(keyword, ifClause) {+ return () => {+ const schCxt = cxt.subschema({ keyword }, schValid);+ gen.assign(valid, schValid);+ cxt.mergeValidEvaluated(schCxt, valid);+ if (ifClause)+ gen.assign(ifClause, (0, codegen_1._)`${keyword}`);+ else+ cxt.setParams({ ifClause: keyword });+ };+ }+ }+ };+ function hasSchema(it, keyword) {+ const schema = it.schema[keyword];+ return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);+ }+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/thenElse.js+var require_thenElse = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var util_1 = require_util();+ var def = {+ keyword: ["then", "else"],+ schemaType: ["object", "boolean"],+ code({ keyword, parentSchema, it }) {+ if (parentSchema.if === void 0)+ (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/applicator/index.js+var require_applicator = __commonJS({+ "node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var additionalItems_1 = require_additionalItems();+ var prefixItems_1 = require_prefixItems();+ var items_1 = require_items();+ var items2020_1 = require_items2020();+ var contains_1 = require_contains();+ var dependencies_1 = require_dependencies();+ var propertyNames_1 = require_propertyNames();+ var additionalProperties_1 = require_additionalProperties();+ var properties_1 = require_properties();+ var patternProperties_1 = require_patternProperties();+ var not_1 = require_not();+ var anyOf_1 = require_anyOf();+ var oneOf_1 = require_oneOf();+ var allOf_1 = require_allOf();+ var if_1 = require_if();+ var thenElse_1 = require_thenElse();+ function getApplicator(draft2020 = false) {+ const applicator = [+ // any+ not_1.default,+ anyOf_1.default,+ oneOf_1.default,+ allOf_1.default,+ if_1.default,+ thenElse_1.default,+ // object+ propertyNames_1.default,+ additionalProperties_1.default,+ dependencies_1.default,+ properties_1.default,+ patternProperties_1.default+ ];+ if (draft2020)+ applicator.push(prefixItems_1.default, items2020_1.default);+ else+ applicator.push(additionalItems_1.default, items_1.default);+ applicator.push(contains_1.default);+ return applicator;+ }+ exports.default = getApplicator;+ }+});++// node_modules/ajv/dist/vocabularies/format/format.js+var require_format = __commonJS({+ "node_modules/ajv/dist/vocabularies/format/format.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var error2 = {+ message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,+ params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`+ };+ var def = {+ keyword: "format",+ type: ["number", "string"],+ schemaType: "string",+ $data: true,+ error: error2,+ code(cxt, ruleType) {+ const { gen, data, $data, schema, schemaCode, it } = cxt;+ const { opts, errSchemaPath, schemaEnv, self } = it;+ if (!opts.validateFormats)+ return;+ if ($data)+ validate$DataFormat();+ else+ validateFormat();+ function validate$DataFormat() {+ const fmts = gen.scopeValue("formats", {+ ref: self.formats,+ code: opts.code.formats+ });+ const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);+ const fType = gen.let("fType");+ const format = gen.let("format");+ gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));+ cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));+ function unknownFmt() {+ if (opts.strictSchema === false)+ return codegen_1.nil;+ return (0, codegen_1._)`${schemaCode} && !${format}`;+ }+ function invalidFmt() {+ const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;+ const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;+ return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;+ }+ }+ function validateFormat() {+ const formatDef = self.formats[schema];+ if (!formatDef) {+ unknownFormat();+ return;+ }+ if (formatDef === true)+ return;+ const [fmtType, format, fmtRef] = getFormat(formatDef);+ if (fmtType === ruleType)+ cxt.pass(validCondition());+ function unknownFormat() {+ if (opts.strictSchema === false) {+ self.logger.warn(unknownMsg());+ return;+ }+ throw new Error(unknownMsg());+ function unknownMsg() {+ return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;+ }+ }+ function getFormat(fmtDef) {+ const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;+ const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });+ if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {+ return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];+ }+ return ["string", fmtDef, fmt];+ }+ function validCondition() {+ if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {+ if (!schemaEnv.$async)+ throw new Error("async format in sync schema");+ return (0, codegen_1._)`await ${fmtRef}(${data})`;+ }+ return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;+ }+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/vocabularies/format/index.js+var require_format2 = __commonJS({+ "node_modules/ajv/dist/vocabularies/format/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var format_1 = require_format();+ var format = [format_1.default];+ exports.default = format;+ }+});++// node_modules/ajv/dist/vocabularies/metadata.js+var require_metadata = __commonJS({+ "node_modules/ajv/dist/vocabularies/metadata.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.contentVocabulary = exports.metadataVocabulary = void 0;+ exports.metadataVocabulary = [+ "title",+ "description",+ "default",+ "deprecated",+ "readOnly",+ "writeOnly",+ "examples"+ ];+ exports.contentVocabulary = [+ "contentMediaType",+ "contentEncoding",+ "contentSchema"+ ];+ }+});++// node_modules/ajv/dist/vocabularies/draft7.js+var require_draft7 = __commonJS({+ "node_modules/ajv/dist/vocabularies/draft7.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var core_1 = require_core2();+ var validation_1 = require_validation();+ var applicator_1 = require_applicator();+ var format_1 = require_format2();+ var metadata_1 = require_metadata();+ var draft7Vocabularies = [+ core_1.default,+ validation_1.default,+ (0, applicator_1.default)(),+ format_1.default,+ metadata_1.metadataVocabulary,+ metadata_1.contentVocabulary+ ];+ exports.default = draft7Vocabularies;+ }+});++// node_modules/ajv/dist/vocabularies/discriminator/types.js+var require_types = __commonJS({+ "node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.DiscrError = void 0;+ var DiscrError;+ (function(DiscrError2) {+ DiscrError2["Tag"] = "tag";+ DiscrError2["Mapping"] = "mapping";+ })(DiscrError || (exports.DiscrError = DiscrError = {}));+ }+});++// node_modules/ajv/dist/vocabularies/discriminator/index.js+var require_discriminator = __commonJS({+ "node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var codegen_1 = require_codegen();+ var types_1 = require_types();+ var compile_1 = require_compile();+ var ref_error_1 = require_ref_error();+ var util_1 = require_util();+ var error2 = {+ message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,+ params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`+ };+ var def = {+ keyword: "discriminator",+ type: "object",+ schemaType: "object",+ error: error2,+ code(cxt) {+ const { gen, data, schema, parentSchema, it } = cxt;+ const { oneOf } = parentSchema;+ if (!it.opts.discriminator) {+ throw new Error("discriminator: requires discriminator option");+ }+ const tagName = schema.propertyName;+ if (typeof tagName != "string")+ throw new Error("discriminator: requires propertyName");+ if (schema.mapping)+ throw new Error("discriminator: mapping is not supported");+ if (!oneOf)+ throw new Error("discriminator: requires oneOf keyword");+ const valid = gen.let("valid", false);+ const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);+ gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));+ cxt.ok(valid);+ function validateMapping() {+ const mapping = getMapping();+ gen.if(false);+ for (const tagValue in mapping) {+ gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);+ gen.assign(valid, applyTagSchema(mapping[tagValue]));+ }+ gen.else();+ cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });+ gen.endIf();+ }+ function applyTagSchema(schemaProp) {+ const _valid = gen.name("valid");+ const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);+ cxt.mergeEvaluated(schCxt, codegen_1.Name);+ return _valid;+ }+ function getMapping() {+ var _a;+ const oneOfMapping = {};+ const topRequired = hasRequired(parentSchema);+ let tagRequired = true;+ for (let i = 0; i < oneOf.length; i++) {+ let sch = oneOf[i];+ if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {+ const ref = sch.$ref;+ sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);+ if (sch instanceof compile_1.SchemaEnv)+ sch = sch.schema;+ if (sch === void 0)+ throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);+ }+ const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];+ if (typeof propSch != "object") {+ throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);+ }+ tagRequired = tagRequired && (topRequired || hasRequired(sch));+ addMappings(propSch, i);+ }+ if (!tagRequired)+ throw new Error(`discriminator: "${tagName}" must be required`);+ return oneOfMapping;+ function hasRequired({ required: required2 }) {+ return Array.isArray(required2) && required2.includes(tagName);+ }+ function addMappings(sch, i) {+ if (sch.const) {+ addMapping(sch.const, i);+ } else if (sch.enum) {+ for (const tagValue of sch.enum) {+ addMapping(tagValue, i);+ }+ } else {+ throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);+ }+ }+ function addMapping(tagValue, i) {+ if (typeof tagValue != "string" || tagValue in oneOfMapping) {+ throw new Error(`discriminator: "${tagName}" values must be unique strings`);+ }+ oneOfMapping[tagValue] = i;+ }+ }+ }+ };+ exports.default = def;+ }+});++// node_modules/ajv/dist/refs/json-schema-draft-07.json+var require_json_schema_draft_07 = __commonJS({+ "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) {+ module.exports = {+ $schema: "http://json-schema.org/draft-07/schema#",+ $id: "http://json-schema.org/draft-07/schema#",+ title: "Core schema meta-schema",+ definitions: {+ schemaArray: {+ type: "array",+ minItems: 1,+ items: { $ref: "#" }+ },+ nonNegativeInteger: {+ type: "integer",+ minimum: 0+ },+ nonNegativeIntegerDefault0: {+ allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }]+ },+ simpleTypes: {+ enum: ["array", "boolean", "integer", "null", "number", "object", "string"]+ },+ stringArray: {+ type: "array",+ items: { type: "string" },+ uniqueItems: true,+ default: []+ }+ },+ type: ["object", "boolean"],+ properties: {+ $id: {+ type: "string",+ format: "uri-reference"+ },+ $schema: {+ type: "string",+ format: "uri"+ },+ $ref: {+ type: "string",+ format: "uri-reference"+ },+ $comment: {+ type: "string"+ },+ title: {+ type: "string"+ },+ description: {+ type: "string"+ },+ default: true,+ readOnly: {+ type: "boolean",+ default: false+ },+ examples: {+ type: "array",+ items: true+ },+ multipleOf: {+ type: "number",+ exclusiveMinimum: 0+ },+ maximum: {+ type: "number"+ },+ exclusiveMaximum: {+ type: "number"+ },+ minimum: {+ type: "number"+ },+ exclusiveMinimum: {+ type: "number"+ },+ maxLength: { $ref: "#/definitions/nonNegativeInteger" },+ minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" },+ pattern: {+ type: "string",+ format: "regex"+ },+ additionalItems: { $ref: "#" },+ items: {+ anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],+ default: true+ },+ maxItems: { $ref: "#/definitions/nonNegativeInteger" },+ minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },+ uniqueItems: {+ type: "boolean",+ default: false+ },+ contains: { $ref: "#" },+ maxProperties: { $ref: "#/definitions/nonNegativeInteger" },+ minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" },+ required: { $ref: "#/definitions/stringArray" },+ additionalProperties: { $ref: "#" },+ definitions: {+ type: "object",+ additionalProperties: { $ref: "#" },+ default: {}+ },+ properties: {+ type: "object",+ additionalProperties: { $ref: "#" },+ default: {}+ },+ patternProperties: {+ type: "object",+ additionalProperties: { $ref: "#" },+ propertyNames: { format: "regex" },+ default: {}+ },+ dependencies: {+ type: "object",+ additionalProperties: {+ anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]+ }+ },+ propertyNames: { $ref: "#" },+ const: true,+ enum: {+ type: "array",+ items: true,+ minItems: 1,+ uniqueItems: true+ },+ type: {+ anyOf: [+ { $ref: "#/definitions/simpleTypes" },+ {+ type: "array",+ items: { $ref: "#/definitions/simpleTypes" },+ minItems: 1,+ uniqueItems: true+ }+ ]+ },+ format: { type: "string" },+ contentMediaType: { type: "string" },+ contentEncoding: { type: "string" },+ if: { $ref: "#" },+ then: { $ref: "#" },+ else: { $ref: "#" },+ allOf: { $ref: "#/definitions/schemaArray" },+ anyOf: { $ref: "#/definitions/schemaArray" },+ oneOf: { $ref: "#/definitions/schemaArray" },+ not: { $ref: "#" }+ },+ default: true+ };+ }+});++// node_modules/ajv/dist/ajv.js+var require_ajv = __commonJS({+ "node_modules/ajv/dist/ajv.js"(exports, module) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;+ var core_1 = require_core();+ var draft7_1 = require_draft7();+ var discriminator_1 = require_discriminator();+ var draft7MetaSchema = require_json_schema_draft_07();+ var META_SUPPORT_DATA = ["/properties"];+ var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";+ var Ajv2 = class extends core_1.default {+ _addVocabularies() {+ super._addVocabularies();+ draft7_1.default.forEach((v) => this.addVocabulary(v));+ if (this.opts.discriminator)+ this.addKeyword(discriminator_1.default);+ }+ _addDefaultMetaSchema() {+ super._addDefaultMetaSchema();+ if (!this.opts.meta)+ return;+ const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;+ this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);+ this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;+ }+ defaultMeta() {+ return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);+ }+ };+ exports.Ajv = Ajv2;+ module.exports = exports = Ajv2;+ module.exports.Ajv = Ajv2;+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.default = Ajv2;+ var validate_1 = require_validate();+ Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {+ return validate_1.KeywordCxt;+ } });+ var codegen_1 = require_codegen();+ Object.defineProperty(exports, "_", { enumerable: true, get: function() {+ return codegen_1._;+ } });+ Object.defineProperty(exports, "str", { enumerable: true, get: function() {+ return codegen_1.str;+ } });+ Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {+ return codegen_1.stringify;+ } });+ Object.defineProperty(exports, "nil", { enumerable: true, get: function() {+ return codegen_1.nil;+ } });+ Object.defineProperty(exports, "Name", { enumerable: true, get: function() {+ return codegen_1.Name;+ } });+ Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {+ return codegen_1.CodeGen;+ } });+ var validation_error_1 = require_validation_error();+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {+ return validation_error_1.default;+ } });+ var ref_error_1 = require_ref_error();+ Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {+ return ref_error_1.default;+ } });+ }+});++// node_modules/ajv-formats/dist/formats.js+var require_formats = __commonJS({+ "node_modules/ajv-formats/dist/formats.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;+ function fmtDef(validate, compare) {+ return { validate, compare };+ }+ exports.fullFormats = {+ // date: http://tools.ietf.org/html/rfc3339#section-5.6+ date: fmtDef(date3, compareDate),+ // date-time: http://tools.ietf.org/html/rfc3339#section-5.6+ time: fmtDef(getTime(true), compareTime),+ "date-time": fmtDef(getDateTime(true), compareDateTime),+ "iso-time": fmtDef(getTime(), compareIsoTime),+ "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),+ // duration: https://tools.ietf.org/html/rfc3339#appendix-A+ duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,+ uri,+ "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,+ // uri-template: https://tools.ietf.org/html/rfc6570+ "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,+ // For the source: https://gist.github.com/dperini/729294+ // For test cases: https://mathiasbynens.be/demo/url-regex+ url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,+ email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,+ hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,+ // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html+ ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,+ ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,+ regex,+ // uuid: http://tools.ietf.org/html/rfc4122+ uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,+ // JSON-pointer: https://tools.ietf.org/html/rfc6901+ // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A+ "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,+ "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,+ // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00+ "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,+ // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types+ // byte: https://github.com/miguelmota/is-base64+ byte,+ // signed 32 bit integer+ int32: { type: "number", validate: validateInt32 },+ // signed 64 bit integer+ int64: { type: "number", validate: validateInt64 },+ // C-type float+ float: { type: "number", validate: validateNumber },+ // C-type double+ double: { type: "number", validate: validateNumber },+ // hint to the UI to hide input strings+ password: true,+ // unchecked string payload+ binary: true+ };+ exports.fastFormats = {+ ...exports.fullFormats,+ date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),+ time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),+ "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),+ "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),+ "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),+ // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js+ uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,+ "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,+ // email (sources from jsen validator):+ // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363+ // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')+ email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i+ };+ exports.formatNames = Object.keys(exports.fullFormats);+ function isLeapYear(year) {+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);+ }+ var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;+ var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];+ function date3(str) {+ const matches = DATE.exec(str);+ if (!matches)+ return false;+ const year = +matches[1];+ const month = +matches[2];+ const day = +matches[3];+ return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);+ }+ function compareDate(d1, d2) {+ if (!(d1 && d2))+ return void 0;+ if (d1 > d2)+ return 1;+ if (d1 < d2)+ return -1;+ return 0;+ }+ var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;+ function getTime(strictTimeZone) {+ return function time3(str) {+ const matches = TIME.exec(str);+ if (!matches)+ return false;+ const hr = +matches[1];+ const min = +matches[2];+ const sec = +matches[3];+ const tz = matches[4];+ const tzSign = matches[5] === "-" ? -1 : 1;+ const tzH = +(matches[6] || 0);+ const tzM = +(matches[7] || 0);+ if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)+ return false;+ if (hr <= 23 && min <= 59 && sec < 60)+ return true;+ const utcMin = min - tzM * tzSign;+ const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);+ return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;+ };+ }+ function compareTime(s1, s2) {+ if (!(s1 && s2))+ return void 0;+ const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();+ const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();+ if (!(t1 && t2))+ return void 0;+ return t1 - t2;+ }+ function compareIsoTime(t1, t2) {+ if (!(t1 && t2))+ return void 0;+ const a1 = TIME.exec(t1);+ const a2 = TIME.exec(t2);+ if (!(a1 && a2))+ return void 0;+ t1 = a1[1] + a1[2] + a1[3];+ t2 = a2[1] + a2[2] + a2[3];+ if (t1 > t2)+ return 1;+ if (t1 < t2)+ return -1;+ return 0;+ }+ var DATE_TIME_SEPARATOR = /t|\s/i;+ function getDateTime(strictTimeZone) {+ const time3 = getTime(strictTimeZone);+ return function date_time(str) {+ const dateTime = str.split(DATE_TIME_SEPARATOR);+ return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]);+ };+ }+ function compareDateTime(dt1, dt2) {+ if (!(dt1 && dt2))+ return void 0;+ const d1 = new Date(dt1).valueOf();+ const d2 = new Date(dt2).valueOf();+ if (!(d1 && d2))+ return void 0;+ return d1 - d2;+ }+ function compareIsoDateTime(dt1, dt2) {+ if (!(dt1 && dt2))+ return void 0;+ const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);+ const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);+ const res = compareDate(d1, d2);+ if (res === void 0)+ return void 0;+ return res || compareTime(t1, t2);+ }+ var NOT_URI_FRAGMENT = /\/|:/;+ var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;+ function uri(str) {+ return NOT_URI_FRAGMENT.test(str) && URI.test(str);+ }+ var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;+ function byte(str) {+ BYTE.lastIndex = 0;+ return BYTE.test(str);+ }+ var MIN_INT32 = -(2 ** 31);+ var MAX_INT32 = 2 ** 31 - 1;+ function validateInt32(value) {+ return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;+ }+ function validateInt64(value) {+ return Number.isInteger(value);+ }+ function validateNumber() {+ return true;+ }+ var Z_ANCHOR = /[^\\]\\Z/;+ function regex(str) {+ if (Z_ANCHOR.test(str))+ return false;+ try {+ new RegExp(str);+ return true;+ } catch (e) {+ return false;+ }+ }+ }+});++// node_modules/ajv-formats/dist/limit.js+var require_limit = __commonJS({+ "node_modules/ajv-formats/dist/limit.js"(exports) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.formatLimitDefinition = void 0;+ var ajv_1 = require_ajv();+ var codegen_1 = require_codegen();+ var ops = codegen_1.operators;+ var KWDs = {+ formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },+ formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },+ formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },+ formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }+ };+ var error2 = {+ message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,+ params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`+ };+ exports.formatLimitDefinition = {+ keyword: Object.keys(KWDs),+ type: "string",+ schemaType: "string",+ $data: true,+ error: error2,+ code(cxt) {+ const { gen, data, schemaCode, keyword, it } = cxt;+ const { opts, self } = it;+ if (!opts.validateFormats)+ return;+ const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");+ if (fCxt.$data)+ validate$DataFormat();+ else+ validateFormat();+ function validate$DataFormat() {+ const fmts = gen.scopeValue("formats", {+ ref: self.formats,+ code: opts.code.formats+ });+ const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);+ cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));+ }+ function validateFormat() {+ const format = fCxt.schema;+ const fmtDef = self.formats[format];+ if (!fmtDef || fmtDef === true)+ return;+ if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {+ throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);+ }+ const fmt = gen.scopeValue("formats", {+ key: format,+ ref: fmtDef,+ code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0+ });+ cxt.fail$data(compareCode(fmt));+ }+ function compareCode(fmt) {+ return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;+ }+ },+ dependencies: ["format"]+ };+ var formatLimitPlugin = (ajv) => {+ ajv.addKeyword(exports.formatLimitDefinition);+ return ajv;+ };+ exports.default = formatLimitPlugin;+ }+});++// node_modules/ajv-formats/dist/index.js+var require_dist = __commonJS({+ "node_modules/ajv-formats/dist/index.js"(exports, module) {+ "use strict";+ Object.defineProperty(exports, "__esModule", { value: true });+ var formats_1 = require_formats();+ var limit_1 = require_limit();+ var codegen_1 = require_codegen();+ var fullName = new codegen_1.Name("fullFormats");+ var fastName = new codegen_1.Name("fastFormats");+ var formatsPlugin = (ajv, opts = { keywords: true }) => {+ if (Array.isArray(opts)) {+ addFormats(ajv, opts, formats_1.fullFormats, fullName);+ return ajv;+ }+ const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];+ const list = opts.formats || formats_1.formatNames;+ addFormats(ajv, list, formats, exportName);+ if (opts.keywords)+ (0, limit_1.default)(ajv);+ return ajv;+ };+ formatsPlugin.get = (name3, mode = "full") => {+ const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;+ const f = formats[name3];+ if (!f)+ throw new Error(`Unknown format "${name3}"`);+ return f;+ };+ function addFormats(ajv, list, fs3, exportName) {+ var _a;+ var _b;+ (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;+ for (const f of list)+ ajv.addFormat(f, fs3[f]);+ }+ module.exports = exports = formatsPlugin;+ Object.defineProperty(exports, "__esModule", { value: true });+ exports.default = formatsPlugin;+ }+});++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js+import process2 from "node:process";++// node_modules/zod/v4/core/core.js+var NEVER = Object.freeze({+ status: "aborted"+});+// @__NO_SIDE_EFFECTS__+function $constructor(name3, initializer3, params) {+ function init(inst, def) {+ var _a;+ Object.defineProperty(inst, "_zod", {+ value: inst._zod ?? {},+ enumerable: false+ });+ (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());+ inst._zod.traits.add(name3);+ initializer3(inst, def);+ for (const k in _.prototype) {+ if (!(k in inst))+ Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });+ }+ inst._zod.constr = _;+ inst._zod.def = def;+ }+ const Parent = params?.Parent ?? Object;+ class Definition extends Parent {+ }+ Object.defineProperty(Definition, "name", { value: name3 });+ function _(def) {+ var _a;+ const inst = params?.Parent ? new Definition() : this;+ init(inst, def);+ (_a = inst._zod).deferred ?? (_a.deferred = []);+ for (const fn of inst._zod.deferred) {+ fn();+ }+ 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(name3);+ }+ });+ Object.defineProperty(_, "name", { value: name3 });+ return _;+}+var $brand = Symbol("zod_brand");+var $ZodAsyncError = class extends Error {+ constructor() {+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);+ }+};+var globalConfig = {};+function config(newConfig) {+ if (newConfig)+ Object.assign(globalConfig, newConfig);+ return globalConfig;+}++// node_modules/zod/v4/core/util.js+var util_exports = {};+__export(util_exports, {+ BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,+ Class: () => Class,+ NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,+ aborted: () => aborted,+ allowsEval: () => allowsEval,+ assert: () => assert,+ assertEqual: () => assertEqual,+ assertIs: () => assertIs,+ assertNever: () => assertNever,+ assertNotEqual: () => assertNotEqual,+ assignProp: () => assignProp,+ cached: () => cached,+ captureStackTrace: () => captureStackTrace,+ cleanEnum: () => cleanEnum,+ cleanRegex: () => cleanRegex,+ clone: () => clone,+ createTransparentProxy: () => createTransparentProxy,+ defineLazy: () => defineLazy,+ esc: () => esc,+ escapeRegex: () => escapeRegex,+ extend: () => extend,+ finalizeIssue: () => finalizeIssue,+ floatSafeRemainder: () => floatSafeRemainder,+ getElementAtPath: () => getElementAtPath,+ getEnumValues: () => getEnumValues,+ getLengthableOrigin: () => getLengthableOrigin,+ getParsedType: () => getParsedType,+ getSizableOrigin: () => getSizableOrigin,+ isObject: () => isObject,+ isPlainObject: () => isPlainObject,+ issue: () => issue,+ joinValues: () => joinValues,+ jsonStringifyReplacer: () => jsonStringifyReplacer,+ merge: () => merge,+ normalizeParams: () => normalizeParams,+ nullish: () => nullish,+ numKeys: () => numKeys,+ omit: () => omit,+ optionalKeys: () => optionalKeys,+ partial: () => partial,+ pick: () => pick,+ prefixIssues: () => prefixIssues,+ primitiveTypes: () => primitiveTypes,+ promiseAllObject: () => promiseAllObject,+ propertyKeyTypes: () => propertyKeyTypes,+ randomString: () => randomString,+ required: () => required,+ stringifyPrimitive: () => stringifyPrimitive,+ unwrapMessage: () => unwrapMessage+});+function assertEqual(val) {+ return val;+}+function assertNotEqual(val) {+ return val;+}+function assertIs(_arg) {+}+function assertNever(_x) {+ throw new Error();+}+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(array2, separator = "|") {+ return array2.map((val) => stringifyPrimitive(val)).join(separator);+}+function jsonStringifyReplacer(_, value) {+ if (typeof value === "bigint")+ return value.toString();+ return value;+}+function cached(getter) {+ const set = false;+ return {+ get value() {+ if (!set) {+ const value = getter();+ Object.defineProperty(this, "value", { value });+ return value;+ }+ throw new Error("cached value already set");+ }+ };+}+function nullish(input) {+ return input === null || input === void 0;+}+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 valDecCount = (val.toString().split(".")[1] || "").length;+ const stepDecCount = (step.toString().split(".")[1] || "").length;+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));+ return valInt % stepInt / 10 ** decCount;+}+function defineLazy(object3, key, getter) {+ const set = false;+ Object.defineProperty(object3, key, {+ get() {+ if (!set) {+ const value = getter();+ object3[key] = value;+ return value;+ }+ throw new Error("cached value already set");+ },+ set(v) {+ Object.defineProperty(object3, key, {+ value: v+ // configurable: true,+ });+ },+ configurable: true+ });+}+function assignProp(target, prop, value) {+ Object.defineProperty(target, prop, {+ value,+ writable: true,+ enumerable: true,+ configurable: true+ });+}+function getElementAtPath(obj, path3) {+ if (!path3)+ return obj;+ return path3.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);+}+var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => {+};+function isObject(data) {+ return typeof data === "object" && data !== null && !Array.isArray(data);+}+var allowsEval = cached(() => {+ 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;+ const ctor = o.constructor;+ if (ctor === void 0)+ return true;+ const prot = ctor.prototype;+ if (isObject(prot) === false)+ return false;+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {+ return false;+ }+ return true;+}+function numKeys(data) {+ let keyCount = 0;+ for (const key in data) {+ if (Object.prototype.hasOwnProperty.call(data, key)) {+ keyCount++;+ }+ }+ return keyCount;+}+var 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";+ }+ if (typeof File !== "undefined" && data instanceof File) {+ return "file";+ }+ return "object";+ default:+ throw new Error(`Unknown data type: ${t}`);+ }+};+var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);+var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);+function escapeRegex(str) {+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}+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 !== void 0) {+ if (params?.error !== void 0)+ 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 === "optional" && shape[k]._zod.optout === "optional";+ });+}+var NUMBER_FORMAT_RANGES = {+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],+ int32: [-2147483648, 2147483647],+ uint32: [0, 4294967295],+ float32: [-34028234663852886e22, 34028234663852886e22],+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]+};+var BIGINT_FORMAT_RANGES = {+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]+};+function pick(schema, mask) {+ const newShape = {};+ const currDef = schema._zod.def;+ for (const key in mask) {+ if (!(key in currDef.shape)) {+ throw new Error(`Unrecognized key: "${key}"`);+ }+ if (!mask[key])+ continue;+ newShape[key] = currDef.shape[key];+ }+ return clone(schema, {+ ...schema._zod.def,+ shape: newShape,+ checks: []+ });+}+function omit(schema, mask) {+ const newShape = { ...schema._zod.def.shape };+ const currDef = schema._zod.def;+ for (const key in mask) {+ if (!(key in currDef.shape)) {+ throw new Error(`Unrecognized key: "${key}"`);+ }+ if (!mask[key])+ continue;+ delete newShape[key];+ }+ return clone(schema, {+ ...schema._zod.def,+ shape: newShape,+ checks: []+ });+}+function extend(schema, shape) {+ if (!isPlainObject(shape)) {+ throw new Error("Invalid input to extend: expected a plain object");+ }+ const def = {+ ...schema._zod.def,+ get shape() {+ const _shape = { ...schema._zod.def.shape, ...shape };+ assignProp(this, "shape", _shape);+ return _shape;+ },+ checks: []+ // delete existing checks+ };+ return clone(schema, def);+}+function merge(a, b) {+ return clone(a, {+ ...a._zod.def,+ get shape() {+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };+ assignProp(this, "shape", _shape);+ return _shape;+ },+ catchall: b._zod.def.catchall,+ checks: []+ // delete existing checks+ });+}+function partial(Class2, schema, mask) {+ const oldShape = schema._zod.def.shape;+ const shape = { ...oldShape };+ if (mask) {+ for (const key in mask) {+ if (!(key in oldShape)) {+ throw new Error(`Unrecognized key: "${key}"`);+ }+ if (!mask[key])+ continue;+ shape[key] = Class2 ? new Class2({+ type: "optional",+ innerType: oldShape[key]+ }) : oldShape[key];+ }+ } else {+ for (const key in oldShape) {+ shape[key] = Class2 ? new Class2({+ type: "optional",+ innerType: oldShape[key]+ }) : oldShape[key];+ }+ }+ return clone(schema, {+ ...schema._zod.def,+ shape,+ checks: []+ });+}+function required(Class2, schema, mask) {+ const oldShape = schema._zod.def.shape;+ const shape = { ...oldShape };+ if (mask) {+ for (const key in mask) {+ if (!(key in shape)) {+ throw new Error(`Unrecognized key: "${key}"`);+ }+ if (!mask[key])+ continue;+ shape[key] = new Class2({+ type: "nonoptional",+ innerType: oldShape[key]+ });+ }+ } else {+ for (const key in oldShape) {+ shape[key] = new Class2({+ type: "nonoptional",+ innerType: oldShape[key]+ });+ }+ }+ return clone(schema, {+ ...schema._zod.def,+ shape,+ // optional: [],+ checks: []+ });+}+function aborted(x, startIndex = 0) {+ for (let i = startIndex; i < x.issues.length; i++) {+ if (x.issues[i]?.continue !== true)+ return true;+ }+ return false;+}+function prefixIssues(path3, issues) {+ return issues.map((iss) => {+ var _a;+ (_a = iss).path ?? (_a.path = []);+ iss.path.unshift(path3);+ return iss;+ });+}+function unwrapMessage(message) {+ return typeof message === "string" ? message : message?.message;+}+function finalizeIssue(iss, ctx, config2) {+ const full = { ...iss, path: iss.path ?? [] };+ if (!iss.message) {+ const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";+ full.message = message;+ }+ delete full.inst;+ delete full.continue;+ if (!ctx?.reportInput) {+ delete full.input;+ }+ return full;+}+function getSizableOrigin(input) {+ if (input instanceof Set)+ return "set";+ if (input instanceof Map)+ return "map";+ if (input instanceof File)+ return "file";+ return "unknown";+}+function getLengthableOrigin(input) {+ if (Array.isArray(input))+ return "array";+ if (typeof input === "string")+ return "string";+ return "unknown";+}+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 Number.isNaN(Number.parseInt(k, 10));+ }).map((el) => el[1]);+}+var Class = class {+ constructor(..._args) {+ }+};++// node_modules/zod/v4/core/errors.js+var initializer = (inst, def) => {+ inst.name = "$ZodError";+ Object.defineProperty(inst, "_zod", {+ value: inst._zod,+ enumerable: false+ });+ Object.defineProperty(inst, "issues", {+ value: def,+ enumerable: false+ });+ Object.defineProperty(inst, "message", {+ get() {+ return JSON.stringify(def, jsonStringifyReplacer, 2);+ },+ enumerable: true+ // configurable: false,+ });+ Object.defineProperty(inst, "toString", {+ value: () => inst.message,+ enumerable: false+ });+};+var $ZodError = $constructor("$ZodError", initializer);+var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });+function flattenError(error2, mapper = (issue2) => issue2.message) {+ const fieldErrors = {};+ const formErrors = [];+ for (const sub of error2.issues) {+ if (sub.path.length > 0) {+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];+ fieldErrors[sub.path[0]].push(mapper(sub));+ } else {+ formErrors.push(mapper(sub));+ }+ }+ return { formErrors, fieldErrors };+}+function formatError(error2, _mapper) {+ const mapper = _mapper || function(issue2) {+ return issue2.message;+ };+ const fieldErrors = { _errors: [] };+ const processError = (error3) => {+ for (const issue2 of error3.issues) {+ if (issue2.code === "invalid_union" && issue2.errors.length) {+ issue2.errors.map((issues) => processError({ issues }));+ } else if (issue2.code === "invalid_key") {+ processError({ issues: issue2.issues });+ } else if (issue2.code === "invalid_element") {+ processError({ issues: issue2.issues });+ } else if (issue2.path.length === 0) {+ fieldErrors._errors.push(mapper(issue2));+ } else {+ let curr = fieldErrors;+ let i = 0;+ while (i < issue2.path.length) {+ const el = issue2.path[i];+ const terminal = i === issue2.path.length - 1;+ if (!terminal) {+ curr[el] = curr[el] || { _errors: [] };+ } else {+ curr[el] = curr[el] || { _errors: [] };+ curr[el]._errors.push(mapper(issue2));+ }+ curr = curr[el];+ i++;+ }+ }+ }+ };+ processError(error2);+ return fieldErrors;+}++// node_modules/zod/v4/core/parse.js+var _parse = (_Err) => (schema, value, _ctx, _params) => {+ const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };+ const result = schema._zod.run({ value, issues: [] }, ctx);+ if (result instanceof Promise) {+ throw new $ZodAsyncError();+ }+ if (result.issues.length) {+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));+ captureStackTrace(e, _params?.callee);+ throw e;+ }+ return result.value;+};+var parse = /* @__PURE__ */ _parse($ZodRealError);+var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {+ const ctx = _ctx ? Object.assign(_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) => finalizeIssue(iss, ctx, config())));+ captureStackTrace(e, params?.callee);+ throw e;+ }+ return result.value;+};+var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);+var _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 $ZodAsyncError();+ }+ return result.issues.length ? {+ success: false,+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))+ } : { success: true, data: result.value };+};+var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);+var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {+ const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };+ let result = schema._zod.run({ value, issues: [] }, ctx);+ if (result instanceof Promise)+ result = await result;+ return result.issues.length ? {+ success: false,+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))+ } : { success: true, data: result.value };+};+var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);++// node_modules/zod/v4/core/regexes.js+var cuid = /^[cC][^\s-]{8,}$/;+var cuid2 = /^[0-9a-z]+$/;+var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;+var xid = /^[0-9a-vA-V]{20}$/;+var ksuid = /^[A-Za-z0-9]{27}$/;+var nanoid = /^[a-zA-Z0-9_-]{21}$/;+var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;+var 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})$/;+var uuid = (version4) => {+ if (!version4)+ 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)$/;+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);+};+var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;+var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;+function emoji() {+ return new RegExp(_emoji, "u");+}+var 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])$/;+var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;+var 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])$/;+var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;+var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;+var base64url = /^[A-Za-z0-9_-]*$/;+var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;+var e164 = /^\+(?:[0-9]){6,14}[0-9]$/;+var 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])))`;+var date = /* @__PURE__ */ new RegExp(`^${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}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;+ return regex;+}+function time(args) {+ return new RegExp(`^${timeSource(args)}$`);+}+function datetime(args) {+ const time3 = timeSource({ precision: args.precision });+ const opts = ["Z"];+ if (args.local)+ opts.push("");+ if (args.offset)+ opts.push(`([+-]\\d{2}:\\d{2})`);+ const timeRegex2 = `${time3}(?:${opts.join("|")})`;+ return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);+}+var string = (params) => {+ const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;+ return new RegExp(`^${regex}$`);+};+var integer = /^\d+$/;+var number = /^-?\d+(?:\.\d+)?/i;+var boolean = /true|false/i;+var _null = /null/i;+var lowercase = /^[^A-Z]*$/;+var uppercase = /^[^a-z]*$/;++// node_modules/zod/v4/core/checks.js+var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {+ var _a;+ inst._zod ?? (inst._zod = {});+ inst._zod.def = def;+ (_a = inst._zod).onattach ?? (_a.onattach = []);+});+var numericOriginMap = {+ number: "number",+ bigint: "bigint",+ object: "date"+};+var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {+ $ZodCheck.init(inst, def);+ const origin = numericOriginMap[typeof def.value];+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;+ if (def.value < curr) {+ if (def.inclusive)+ bag.maximum = def.value;+ else+ bag.exclusiveMaximum = def.value;+ }+ });+ inst._zod.check = (payload) => {+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {+ return;+ }+ payload.issues.push({+ origin,+ code: "too_big",+ maximum: def.value,+ input: payload.value,+ inclusive: def.inclusive,+ inst,+ continue: !def.abort+ });+ };+});+var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {+ $ZodCheck.init(inst, def);+ const origin = numericOriginMap[typeof def.value];+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;+ if (def.value > curr) {+ if (def.inclusive)+ bag.minimum = def.value;+ else+ bag.exclusiveMinimum = def.value;+ }+ });+ inst._zod.check = (payload) => {+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {+ return;+ }+ payload.issues.push({+ origin,+ code: "too_small",+ minimum: def.value,+ input: payload.value,+ inclusive: def.inclusive,+ inst,+ continue: !def.abort+ });+ };+});+var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {+ $ZodCheck.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ var _a;+ (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value);+ });+ 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" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(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+ });+ };+});+var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {+ $ZodCheck.init(inst, def);+ def.format = def.format || "float64";+ const isInt = def.format?.includes("int");+ const origin = isInt ? "int" : "number";+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.format = def.format;+ bag.minimum = minimum;+ bag.maximum = maximum;+ if (isInt)+ bag.pattern = integer;+ });+ inst._zod.check = (payload) => {+ const input = payload.value;+ if (isInt) {+ if (!Number.isInteger(input)) {+ payload.issues.push({+ expected: origin,+ format: def.format,+ code: "invalid_type",+ input,+ inst+ });+ return;+ }+ if (!Number.isSafeInteger(input)) {+ if (input > 0) {+ payload.issues.push({+ input,+ code: "too_big",+ maximum: Number.MAX_SAFE_INTEGER,+ note: "Integers must be within the safe integer range.",+ inst,+ origin,+ continue: !def.abort+ });+ } else {+ payload.issues.push({+ input,+ code: "too_small",+ minimum: Number.MIN_SAFE_INTEGER,+ note: "Integers must be within the safe integer range.",+ inst,+ origin,+ 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,+ inst+ });+ }+ };+});+var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {+ var _a;+ $ZodCheck.init(inst, def);+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {+ const val = payload.value;+ return !nullish(val) && val.length !== void 0;+ });+ inst._zod.onattach.push((inst2) => {+ const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;+ if (def.maximum < curr)+ inst2._zod.bag.maximum = def.maximum;+ });+ inst._zod.check = (payload) => {+ const input = payload.value;+ const length = input.length;+ if (length <= def.maximum)+ return;+ const origin = getLengthableOrigin(input);+ payload.issues.push({+ origin,+ code: "too_big",+ maximum: def.maximum,+ inclusive: true,+ input,+ inst,+ continue: !def.abort+ });+ };+});+var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {+ var _a;+ $ZodCheck.init(inst, def);+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {+ const val = payload.value;+ return !nullish(val) && val.length !== void 0;+ });+ inst._zod.onattach.push((inst2) => {+ const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;+ if (def.minimum > curr)+ inst2._zod.bag.minimum = def.minimum;+ });+ inst._zod.check = (payload) => {+ const input = payload.value;+ const length = input.length;+ if (length >= def.minimum)+ return;+ const origin = getLengthableOrigin(input);+ payload.issues.push({+ origin,+ code: "too_small",+ minimum: def.minimum,+ inclusive: true,+ input,+ inst,+ continue: !def.abort+ });+ };+});+var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {+ var _a;+ $ZodCheck.init(inst, def);+ (_a = inst._zod.def).when ?? (_a.when = (payload) => {+ const val = payload.value;+ return !nullish(val) && val.length !== void 0;+ });+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.minimum = def.length;+ bag.maximum = def.length;+ bag.length = def.length;+ });+ inst._zod.check = (payload) => {+ const input = payload.value;+ const length = input.length;+ if (length === def.length)+ return;+ const origin = getLengthableOrigin(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+ });+ };+});+var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {+ var _a, _b;+ $ZodCheck.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.format = def.format;+ if (def.pattern) {+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());+ bag.patterns.add(def.pattern);+ }+ });+ 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 = () => {+ });+});+var $ZodCheckRegex = /* @__PURE__ */ $constructor("$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+ });+ };+});+var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {+ def.pattern ?? (def.pattern = lowercase);+ $ZodCheckStringFormat.init(inst, def);+});+var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {+ def.pattern ?? (def.pattern = uppercase);+ $ZodCheckStringFormat.init(inst, def);+});+var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {+ $ZodCheck.init(inst, def);+ const escapedRegex = escapeRegex(def.includes);+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);+ def.pattern = pattern;+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());+ bag.patterns.add(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+ });+ };+});+var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {+ $ZodCheck.init(inst, def);+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);+ def.pattern ?? (def.pattern = pattern);+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());+ bag.patterns.add(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+ });+ };+});+var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {+ $ZodCheck.init(inst, def);+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);+ def.pattern ?? (def.pattern = pattern);+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());+ bag.patterns.add(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+ });+ };+});+var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {+ $ZodCheck.init(inst, def);+ inst._zod.check = (payload) => {+ payload.value = def.tx(payload.value);+ };+});++// node_modules/zod/v4/core/doc.js+var Doc = class {+ constructor(args = []) {+ this.content = [];+ this.indent = 0;+ if (this)+ this.args = args;+ }+ indented(fn) {+ this.indent += 1;+ fn(this);+ 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 args = this?.args;+ const content = this?.content ?? [``];+ const lines = [...content.map((x) => ` ${x}`)];+ return new F(...args, lines.join("\n"));+ }+};++// node_modules/zod/v4/core/versions.js+var version = {+ major: 4,+ minor: 0,+ patch: 0+};++// node_modules/zod/v4/core/schemas.js+var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {+ var _a;+ inst ?? (inst = {});+ inst._zod.def = def;+ inst._zod.bag = inst._zod.bag || {};+ inst._zod.version = version;+ const checks = [...inst._zod.def.checks ?? []];+ if (inst._zod.traits.has("$ZodCheck")) {+ checks.unshift(inst);+ }+ for (const ch of checks) {+ for (const fn of ch._zod.onattach) {+ fn(inst);+ }+ }+ if (checks.length === 0) {+ (_a = inst._zod).deferred ?? (_a.deferred = []);+ inst._zod.deferred?.push(() => {+ inst._zod.run = inst._zod.parse;+ });+ } else {+ const runChecks = (payload, checks2, ctx) => {+ let isAborted2 = aborted(payload);+ let asyncResult;+ for (const ch of checks2) {+ if (ch._zod.def.when) {+ const shouldRun = ch._zod.def.when(payload);+ if (!shouldRun)+ continue;+ } else if (isAborted2) {+ continue;+ }+ const currLen = payload.issues.length;+ const _ = ch._zod.check(payload);+ if (_ instanceof Promise && ctx?.async === false) {+ throw new $ZodAsyncError();+ }+ if (asyncResult || _ instanceof Promise) {+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {+ await _;+ const nextLen = payload.issues.length;+ if (nextLen === currLen)+ return;+ if (!isAborted2)+ isAborted2 = aborted(payload, currLen);+ });+ } else {+ const nextLen = payload.issues.length;+ if (nextLen === currLen)+ continue;+ if (!isAborted2)+ isAborted2 = aborted(payload, currLen);+ }+ }+ if (asyncResult) {+ return asyncResult.then(() => {+ return payload;+ });+ }+ return payload;+ };+ inst._zod.run = (payload, ctx) => {+ const result = inst._zod.parse(payload, ctx);+ if (result instanceof Promise) {+ if (ctx.async === false)+ throw new $ZodAsyncError();+ return result.then((result2) => runChecks(result2, checks, ctx));+ }+ return runChecks(result, checks, ctx);+ };+ }+ inst["~standard"] = {+ validate: (value) => {+ try {+ const r = safeParse(inst, value);+ return r.success ? { value: r.data } : { issues: r.error?.issues };+ } catch (_) {+ return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });+ }+ },+ vendor: "zod",+ version: 1+ };+});+var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);+ inst._zod.parse = (payload, _) => {+ if (def.coerce)+ try {+ payload.value = String(payload.value);+ } catch (_2) {+ }+ if (typeof payload.value === "string")+ return payload;+ payload.issues.push({+ expected: "string",+ code: "invalid_type",+ input: payload.value,+ inst+ });+ return payload;+ };+});+var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {+ $ZodCheckStringFormat.init(inst, def);+ $ZodString.init(inst, def);+});+var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {+ def.pattern ?? (def.pattern = guid);+ $ZodStringFormat.init(inst, def);+});+var $ZodUUID = /* @__PURE__ */ $constructor("$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 === void 0)+ throw new Error(`Invalid UUID version: "${def.version}"`);+ def.pattern ?? (def.pattern = uuid(v));+ } else+ def.pattern ?? (def.pattern = uuid());+ $ZodStringFormat.init(inst, def);+});+var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {+ def.pattern ?? (def.pattern = email);+ $ZodStringFormat.init(inst, def);+});+var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {+ $ZodStringFormat.init(inst, def);+ inst._zod.check = (payload) => {+ try {+ const orig = payload.value;+ const url = new URL(orig);+ const href = url.href;+ if (def.hostname) {+ def.hostname.lastIndex = 0;+ if (!def.hostname.test(url.hostname)) {+ payload.issues.push({+ code: "invalid_format",+ format: "url",+ note: "Invalid hostname",+ pattern: hostname.source,+ input: payload.value,+ inst,+ continue: !def.abort+ });+ }+ }+ if (def.protocol) {+ def.protocol.lastIndex = 0;+ if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {+ payload.issues.push({+ code: "invalid_format",+ format: "url",+ note: "Invalid protocol",+ pattern: def.protocol.source,+ input: payload.value,+ inst,+ continue: !def.abort+ });+ }+ }+ if (!orig.endsWith("/") && href.endsWith("/")) {+ payload.value = href.slice(0, -1);+ } else {+ payload.value = href;+ }+ return;+ } catch (_) {+ payload.issues.push({+ code: "invalid_format",+ format: "url",+ input: payload.value,+ inst,+ continue: !def.abort+ });+ }+ };+});+var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {+ def.pattern ?? (def.pattern = emoji());+ $ZodStringFormat.init(inst, def);+});+var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {+ def.pattern ?? (def.pattern = nanoid);+ $ZodStringFormat.init(inst, def);+});+var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {+ def.pattern ?? (def.pattern = cuid);+ $ZodStringFormat.init(inst, def);+});+var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {+ def.pattern ?? (def.pattern = cuid2);+ $ZodStringFormat.init(inst, def);+});+var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {+ def.pattern ?? (def.pattern = ulid);+ $ZodStringFormat.init(inst, def);+});+var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {+ def.pattern ?? (def.pattern = xid);+ $ZodStringFormat.init(inst, def);+});+var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {+ def.pattern ?? (def.pattern = ksuid);+ $ZodStringFormat.init(inst, def);+});+var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {+ def.pattern ?? (def.pattern = datetime(def));+ $ZodStringFormat.init(inst, def);+});+var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {+ def.pattern ?? (def.pattern = date);+ $ZodStringFormat.init(inst, def);+});+var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {+ def.pattern ?? (def.pattern = time(def));+ $ZodStringFormat.init(inst, def);+});+var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {+ def.pattern ?? (def.pattern = duration);+ $ZodStringFormat.init(inst, def);+});+var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {+ def.pattern ?? (def.pattern = ipv4);+ $ZodStringFormat.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.format = `ipv4`;+ });+});+var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {+ def.pattern ?? (def.pattern = ipv6);+ $ZodStringFormat.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ const bag = inst2._zod.bag;+ bag.format = `ipv6`;+ });+ inst._zod.check = (payload) => {+ try {+ new URL(`http://[${payload.value}]`);+ } catch {+ payload.issues.push({+ code: "invalid_format",+ format: "ipv6",+ input: payload.value,+ inst,+ continue: !def.abort+ });+ }+ };+});+var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {+ def.pattern ?? (def.pattern = cidrv4);+ $ZodStringFormat.init(inst, def);+});+var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {+ def.pattern ?? (def.pattern = cidrv6);+ $ZodStringFormat.init(inst, def);+ inst._zod.check = (payload) => {+ const [address, prefix] = payload.value.split("/");+ try {+ if (!prefix)+ throw new Error();+ const prefixNum = Number(prefix);+ if (`${prefixNum}` !== prefix)+ throw new Error();+ if (prefixNum < 0 || prefixNum > 128)+ throw new Error();+ new URL(`http://[${address}]`);+ } catch {+ payload.issues.push({+ code: "invalid_format",+ format: "cidrv6",+ input: payload.value,+ inst,+ continue: !def.abort+ });+ }+ };+});+function isValidBase64(data) {+ if (data === "")+ return true;+ if (data.length % 4 !== 0)+ return false;+ try {+ atob(data);+ return true;+ } catch {+ return false;+ }+}+var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {+ def.pattern ?? (def.pattern = base64);+ $ZodStringFormat.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ inst2._zod.bag.contentEncoding = "base64";+ });+ inst._zod.check = (payload) => {+ if (isValidBase64(payload.value))+ return;+ payload.issues.push({+ code: "invalid_format",+ format: "base64",+ input: payload.value,+ inst,+ continue: !def.abort+ });+ };+});+function isValidBase64URL(data) {+ if (!base64url.test(data))+ return false;+ const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");+ const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");+ return isValidBase64(padded);+}+var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {+ def.pattern ?? (def.pattern = base64url);+ $ZodStringFormat.init(inst, def);+ inst._zod.onattach.push((inst2) => {+ inst2._zod.bag.contentEncoding = "base64url";+ });+ inst._zod.check = (payload) => {+ if (isValidBase64URL(payload.value))+ return;+ payload.issues.push({+ code: "invalid_format",+ format: "base64url",+ input: payload.value,+ inst,+ continue: !def.abort+ });+ };+});+var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {+ def.pattern ?? (def.pattern = e164);+ $ZodStringFormat.init(inst, def);+});+function isValidJWT(token, algorithm = null) {+ try {+ const tokensParts = token.split(".");+ if (tokensParts.length !== 3)+ return false;+ const [header] = tokensParts;+ if (!header)+ return false;+ 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;+ }+}+var $ZodJWT = /* @__PURE__ */ $constructor("$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+ });+ };+});+var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.pattern = inst._zod.bag.pattern ?? number;+ 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) ? "Infinity" : void 0 : void 0;+ payload.issues.push({+ expected: "number",+ code: "invalid_type",+ input,+ inst,+ ...received ? { received } : {}+ });+ return payload;+ };+});+var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {+ $ZodCheckNumberFormat.init(inst, def);+ $ZodNumber.init(inst, def);+});+var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.pattern = boolean;+ 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;+ };+});+var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.pattern = _null;+ inst._zod.values = /* @__PURE__ */ 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;+ };+});+var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.parse = (payload) => payload;+});+var $ZodNever = /* @__PURE__ */ $constructor("$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;+ };+});+function handleArrayResult(result, final, index) {+ if (result.issues.length) {+ final.issues.push(...prefixIssues(index, result.issues));+ }+ final.value[index] = result.value;+}+var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {+ $ZodType.init(inst, def);+ 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 = Array(input.length);+ const proms = [];+ 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((result2) => handleArrayResult(result2, payload, i)));+ } else {+ handleArrayResult(result, payload, i);+ }+ }+ if (proms.length) {+ return Promise.all(proms).then(() => payload);+ }+ return payload;+ };+});+function handleObjectResult(result, final, key) {+ if (result.issues.length) {+ final.issues.push(...prefixIssues(key, result.issues));+ }+ final.value[key] = result.value;+}+function handleOptionalObjectResult(result, final, key, input) {+ if (result.issues.length) {+ if (input[key] === void 0) {+ if (key in input) {+ final.value[key] = void 0;+ } else {+ final.value[key] = result.value;+ }+ } else {+ final.issues.push(...prefixIssues(key, result.issues));+ }+ } else if (result.value === void 0) {+ if (key in input)+ final.value[key] = void 0;+ } else {+ final.value[key] = result.value;+ }+}+var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {+ $ZodType.init(inst, def);+ const _normalized = cached(() => {+ const keys = Object.keys(def.shape);+ for (const k of keys) {+ if (!(def.shape[k] instanceof $ZodType)) {+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);+ }+ }+ const okeys = optionalKeys(def.shape);+ return {+ shape: def.shape,+ keys,+ keySet: new Set(keys),+ numKeys: keys.length,+ optionalKeys: new Set(okeys)+ };+ });+ defineLazy(inst._zod, "propValues", () => {+ const shape = def.shape;+ const propValues = {};+ for (const key in shape) {+ const field = shape[key]._zod;+ if (field.values) {+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());+ for (const v of field.values)+ propValues[key].add(v);+ }+ }+ return propValues;+ });+ const generateFastpass = (shape) => {+ const doc = new Doc(["shape", "payload", "ctx"]);+ const normalized = _normalized.value;+ const parseStr = (key) => {+ const k = esc(key);+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;+ };+ doc.write(`const input = payload.value;`);+ const ids = /* @__PURE__ */ Object.create(null);+ let counter = 0;+ for (const key of normalized.keys) {+ ids[key] = `key_${counter++}`;+ }+ doc.write(`const newResult = {}`);+ for (const key of normalized.keys) {+ if (normalized.optionalKeys.has(key)) {+ const id = ids[key];+ doc.write(`const ${id} = ${parseStr(key)};`);+ const k = esc(key);+ doc.write(`+ if (${id}.issues.length) {+ if (input[${k}] === undefined) {+ if (${k} in input) {+ newResult[${k}] = undefined;+ }+ } else {+ payload.issues = payload.issues.concat(+ ${id}.issues.map((iss) => ({+ ...iss,+ path: iss.path ? [${k}, ...iss.path] : [${k}],+ }))+ );+ }+ } else if (${id}.value === undefined) {+ if (${k} in input) newResult[${k}] = undefined;+ } else {+ newResult[${k}] = ${id}.value;+ }+ `);+ } else {+ const id = ids[key];+ doc.write(`const ${id} = ${parseStr(key)};`);+ doc.write(`+ if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({+ ...iss,+ path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]+ })));`);+ doc.write(`newResult[${esc(key)}] = ${id}.value`);+ }+ }+ doc.write(`payload.value = newResult;`);+ doc.write(`return payload;`);+ const fn = doc.compile();+ return (payload, ctx) => fn(shape, payload, ctx);+ };+ let fastpass;+ const isObject2 = isObject;+ const jit = !globalConfig.jitless;+ const allowsEval2 = allowsEval;+ const fastEnabled = jit && allowsEval2.value;+ const catchall = def.catchall;+ let value;+ inst._zod.parse = (payload, ctx) => {+ value ?? (value = _normalized.value);+ const input = payload.value;+ if (!isObject2(input)) {+ payload.issues.push({+ expected: "object",+ code: "invalid_type",+ input,+ inst+ });+ return payload;+ }+ const proms = [];+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {+ if (!fastpass)+ fastpass = generateFastpass(def.shape);+ payload = fastpass(payload, ctx);+ } else {+ payload.value = {};+ const shape = value.shape;+ for (const key of value.keys) {+ const el = shape[key];+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);+ const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";+ if (r instanceof Promise) {+ proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));+ } else if (isOptional) {+ handleOptionalObjectResult(r, payload, key, input);+ } else {+ handleObjectResult(r, payload, key);+ }+ }+ }+ if (!catchall) {+ return proms.length ? Promise.all(proms).then(() => payload) : payload;+ }+ const unrecognized = [];+ const keySet = value.keySet;+ const _catchall = catchall._zod;+ const t = _catchall.def.type;+ for (const key of Object.keys(input)) {+ if (keySet.has(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((r2) => handleObjectResult(r2, payload, key)));+ } else {+ handleObjectResult(r, payload, key);+ }+ }+ if (unrecognized.length) {+ payload.issues.push({+ code: "unrecognized_keys",+ keys: unrecognized,+ input,+ inst+ });+ }+ if (!proms.length)+ return payload;+ return Promise.all(proms).then(() => {+ return payload;+ });+ };+});+function handleUnionResults(results, final, inst, ctx) {+ for (const result of results) {+ if (result.issues.length === 0) {+ final.value = result.value;+ return final;+ }+ }+ final.issues.push({+ code: "invalid_union",+ input: final.value,+ inst,+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))+ });+ return final;+}+var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {+ $ZodType.init(inst, def);+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);+ defineLazy(inst._zod, "values", () => {+ if (def.options.every((o) => o._zod.values)) {+ return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));+ }+ return void 0;+ });+ defineLazy(inst._zod, "pattern", () => {+ if (def.options.every((o) => o._zod.pattern)) {+ const patterns = def.options.map((o) => o._zod.pattern);+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);+ }+ return void 0;+ });+ inst._zod.parse = (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((results2) => {+ return handleUnionResults(results2, payload, inst, ctx);+ });+ };+});+var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {+ $ZodUnion.init(inst, def);+ const _super = inst._zod.parse;+ defineLazy(inst._zod, "propValues", () => {+ const propValues = {};+ for (const option of def.options) {+ const pv = option._zod.propValues;+ if (!pv || Object.keys(pv).length === 0)+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);+ for (const [k, v] of Object.entries(pv)) {+ if (!propValues[k])+ propValues[k] = /* @__PURE__ */ new Set();+ for (const val of v) {+ propValues[k].add(val);+ }+ }+ }+ return propValues;+ });+ const disc = cached(() => {+ const opts = def.options;+ const map = /* @__PURE__ */ new Map();+ for (const o of opts) {+ const values = o._zod.propValues[def.discriminator];+ if (!values || values.size === 0)+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);+ for (const v of values) {+ if (map.has(v)) {+ throw new Error(`Duplicate discriminator value "${String(v)}"`);+ }+ map.set(v, o);+ }+ }+ return map;+ });+ inst._zod.parse = (payload, ctx) => {+ const input = payload.value;+ if (!isObject(input)) {+ payload.issues.push({+ code: "invalid_type",+ expected: "object",+ input,+ inst+ });+ return payload;+ }+ const opt = disc.value.get(input?.[def.discriminator]);+ if (opt) {+ return opt._zod.run(payload, ctx);+ }+ if (def.unionFallback) {+ return _super(payload, ctx);+ }+ payload.issues.push({+ code: "invalid_union",+ errors: [],+ note: "No matching discriminator",+ input,+ path: [def.discriminator],+ inst+ });+ return payload;+ };+});+var $ZodIntersection = /* @__PURE__ */ $constructor("$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(([left2, right2]) => {+ return handleIntersectionResults(payload, left2, right2);+ });+ }+ return handleIntersectionResults(payload, left, right);+ };+});+function mergeValues(a, b) {+ if (a === b) {+ return { valid: true, data: a };+ }+ if (a instanceof Date && b instanceof Date && +a === +b) {+ return { valid: true, data: a };+ }+ if (isPlainObject(a) && isPlainObject(b)) {+ const bKeys = Object.keys(b);+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);+ const newObj = { ...a, ...b };+ for (const key of sharedKeys) {+ 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) {+ if (left.issues.length) {+ result.issues.push(...left.issues);+ }+ if (right.issues.length) {+ result.issues.push(...right.issues);+ }+ if (aborted(result))+ return result;+ const merged = mergeValues(left.value, right.value);+ if (!merged.valid) {+ throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);+ }+ result.value = merged.data;+ return result;+}+var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.parse = (payload, ctx) => {+ const input = payload.value;+ if (!isPlainObject(input)) {+ payload.issues.push({+ expected: "record",+ code: "invalid_type",+ input,+ inst+ });+ return payload;+ }+ const proms = [];+ if (def.keyType._zod.values) {+ const values = def.keyType._zod.values;+ payload.value = {};+ for (const key of values) {+ if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);+ if (result instanceof Promise) {+ proms.push(result.then((result2) => {+ if (result2.issues.length) {+ payload.issues.push(...prefixIssues(key, result2.issues));+ }+ payload.value[key] = result2.value;+ }));+ } else {+ if (result.issues.length) {+ payload.issues.push(...prefixIssues(key, result.issues));+ }+ payload.value[key] = result.value;+ }+ }+ }+ let unrecognized;+ for (const key in input) {+ if (!values.has(key)) {+ unrecognized = unrecognized ?? [];+ unrecognized.push(key);+ }+ }+ if (unrecognized && unrecognized.length > 0) {+ payload.issues.push({+ code: "unrecognized_keys",+ input,+ inst,+ keys: unrecognized+ });+ }+ } else {+ payload.value = {};+ for (const key of Reflect.ownKeys(input)) {+ 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({+ origin: "record",+ code: "invalid_key",+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),+ input: key,+ path: [key],+ inst+ });+ payload.value[keyResult.value] = keyResult.value;+ continue;+ }+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);+ if (result instanceof Promise) {+ proms.push(result.then((result2) => {+ if (result2.issues.length) {+ payload.issues.push(...prefixIssues(key, result2.issues));+ }+ payload.value[keyResult.value] = result2.value;+ }));+ } else {+ if (result.issues.length) {+ payload.issues.push(...prefixIssues(key, result.issues));+ }+ payload.value[keyResult.value] = result.value;+ }+ }+ }+ if (proms.length) {+ return Promise.all(proms).then(() => payload);+ }+ return payload;+ };+});+var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {+ $ZodType.init(inst, def);+ const values = getEnumValues(def.entries);+ inst._zod.values = new Set(values);+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);+ inst._zod.parse = (payload, _ctx) => {+ const input = payload.value;+ if (inst._zod.values.has(input)) {+ return payload;+ }+ payload.issues.push({+ code: "invalid_value",+ values,+ input,+ inst+ });+ return payload;+ };+});+var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.values = new Set(def.values);+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);+ inst._zod.parse = (payload, _ctx) => {+ const input = payload.value;+ if (inst._zod.values.has(input)) {+ return payload;+ }+ payload.issues.push({+ code: "invalid_value",+ values: def.values,+ input,+ inst+ });+ return payload;+ };+});+var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.parse = (payload, _ctx) => {+ const _out = def.transform(payload.value, payload);+ if (_ctx.async) {+ const output = _out instanceof Promise ? _out : Promise.resolve(_out);+ return output.then((output2) => {+ payload.value = output2;+ return payload;+ });+ }+ if (_out instanceof Promise) {+ throw new $ZodAsyncError();+ }+ payload.value = _out;+ return payload;+ };+});+var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.optin = "optional";+ inst._zod.optout = "optional";+ defineLazy(inst._zod, "values", () => {+ return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;+ });+ defineLazy(inst._zod, "pattern", () => {+ const pattern = def.innerType._zod.pattern;+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;+ });+ inst._zod.parse = (payload, ctx) => {+ if (def.innerType._zod.optin === "optional") {+ return def.innerType._zod.run(payload, ctx);+ }+ if (payload.value === void 0) {+ return payload;+ }+ return def.innerType._zod.run(payload, ctx);+ };+});+var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {+ $ZodType.init(inst, def);+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);+ defineLazy(inst._zod, "pattern", () => {+ const pattern = def.innerType._zod.pattern;+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;+ });+ defineLazy(inst._zod, "values", () => {+ return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;+ });+ inst._zod.parse = (payload, ctx) => {+ if (payload.value === null)+ return payload;+ return def.innerType._zod.run(payload, ctx);+ };+});+var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.optin = "optional";+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);+ inst._zod.parse = (payload, ctx) => {+ if (payload.value === void 0) {+ payload.value = def.defaultValue;+ return payload;+ }+ const result = def.innerType._zod.run(payload, ctx);+ if (result instanceof Promise) {+ return result.then((result2) => handleDefaultResult(result2, def));+ }+ return handleDefaultResult(result, def);+ };+});+function handleDefaultResult(payload, def) {+ if (payload.value === void 0) {+ payload.value = def.defaultValue;+ }+ return payload;+}+var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.optin = "optional";+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);+ inst._zod.parse = (payload, ctx) => {+ if (payload.value === void 0) {+ payload.value = def.defaultValue;+ }+ return def.innerType._zod.run(payload, ctx);+ };+});+var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {+ $ZodType.init(inst, def);+ defineLazy(inst._zod, "values", () => {+ const v = def.innerType._zod.values;+ return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;+ });+ inst._zod.parse = (payload, ctx) => {+ const result = def.innerType._zod.run(payload, ctx);+ if (result instanceof Promise) {+ return result.then((result2) => handleNonOptionalResult(result2, inst));+ }+ return handleNonOptionalResult(result, inst);+ };+});+function handleNonOptionalResult(payload, inst) {+ if (!payload.issues.length && payload.value === void 0) {+ payload.issues.push({+ code: "invalid_type",+ expected: "nonoptional",+ input: payload.value,+ inst+ });+ }+ return payload;+}+var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {+ $ZodType.init(inst, def);+ inst._zod.optin = "optional";+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);+ inst._zod.parse = (payload, ctx) => {+ const result = def.innerType._zod.run(payload, ctx);+ if (result instanceof Promise) {+ return result.then((result2) => {+ payload.value = result2.value;+ if (result2.issues.length) {+ payload.value = def.catchValue({+ ...payload,+ error: {+ issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))+ },+ input: payload.value+ });+ payload.issues = [];+ }+ return payload;+ });+ }+ payload.value = result.value;+ if (result.issues.length) {+ payload.value = def.catchValue({+ ...payload,+ error: {+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))+ },+ input: payload.value+ });+ payload.issues = [];+ }+ return payload;+ };+});+var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {+ $ZodType.init(inst, def);+ defineLazy(inst._zod, "values", () => def.in._zod.values);+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);+ inst._zod.parse = (payload, ctx) => {+ const left = def.in._zod.run(payload, ctx);+ if (left instanceof Promise) {+ return left.then((left2) => handlePipeResult(left2, def, ctx));+ }+ return handlePipeResult(left, def, ctx);+ };+});+function handlePipeResult(left, def, ctx) {+ if (aborted(left)) {+ return left;+ }+ return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);+}+var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {+ $ZodType.init(inst, def);+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);+ inst._zod.parse = (payload, ctx) => {+ const result = def.innerType._zod.run(payload, ctx);+ if (result instanceof Promise) {+ return result.then(handleReadonlyResult);+ }+ return handleReadonlyResult(result);+ };+});+function handleReadonlyResult(payload) {+ payload.value = Object.freeze(payload.value);+ return payload;+}+var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {+ $ZodCheck.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((r2) => handleRefineResult(r2, 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(issue(_iss));+ }+}++// node_modules/zod/v4/locales/en.js+var parsedType = (data) => {+ const t = typeof data;+ switch (t) {+ case "number": {+ return Number.isNaN(data) ? "NaN" : "number";+ }+ case "object": {+ if (Array.isArray(data)) {+ return "array";+ }+ if (data === null) {+ return "null";+ }+ if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {+ return data.constructor.name;+ }+ }+ }+ return t;+};+var 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" }+ };+ function getSizing(origin) {+ return Sizable[origin] ?? null;+ }+ const Nouns = {+ 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",+ cidrv4: "IPv4 range",+ cidrv6: "IPv6 range",+ base64: "base64-encoded string",+ base64url: "base64url-encoded string",+ json_string: "JSON string",+ e164: "E.164 number",+ jwt: "JWT",+ template_literal: "input"+ };+ return (issue2) => {+ switch (issue2.code) {+ case "invalid_type":+ return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`;+ case "invalid_value":+ if (issue2.values.length === 1)+ return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;+ return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;+ case "too_big": {+ const adj = issue2.inclusive ? "<=" : "<";+ const sizing = getSizing(issue2.origin);+ if (sizing)+ return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;+ return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;+ }+ case "too_small": {+ const adj = issue2.inclusive ? ">=" : ">";+ const sizing = getSizing(issue2.origin);+ if (sizing) {+ return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;+ }+ return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;+ }+ case "invalid_format": {+ const _issue = issue2;+ 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 ${Nouns[_issue.format] ?? issue2.format}`;+ }+ case "not_multiple_of":+ return `Invalid number: must be a multiple of ${issue2.divisor}`;+ case "unrecognized_keys":+ return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;+ case "invalid_key":+ return `Invalid key in ${issue2.origin}`;+ case "invalid_union":+ return "Invalid input";+ case "invalid_element":+ return `Invalid value in ${issue2.origin}`;+ default:+ return `Invalid input`;+ }+ };+};+function en_default() {+ return {+ localeError: error()+ };+}++// node_modules/zod/v4/core/registries.js+var $output = Symbol("ZodOutput");+var $input = Symbol("ZodInput");+var $ZodRegistry = class {+ constructor() {+ this._map = /* @__PURE__ */ new Map();+ this._idmap = /* @__PURE__ */ new Map();+ }+ add(schema, ..._meta) {+ const meta = _meta[0];+ this._map.set(schema, meta);+ if (meta && typeof meta === "object" && "id" in meta) {+ if (this._idmap.has(meta.id)) {+ throw new Error(`ID ${meta.id} already exists in the registry`);+ }+ this._idmap.set(meta.id, schema);+ }+ return this;+ }+ clear() {+ this._map = /* @__PURE__ */ new Map();+ this._idmap = /* @__PURE__ */ 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) {+ const p = schema._zod.parent;+ if (p) {+ const pm = { ...this.get(p) ?? {} };+ delete pm.id;+ return { ...pm, ...this._map.get(schema) };+ }+ return this._map.get(schema);+ }+ has(schema) {+ return this._map.has(schema);+ }+};+function registry() {+ return new $ZodRegistry();+}+var globalRegistry = /* @__PURE__ */ registry();++// node_modules/zod/v4/core/api.js+function _string(Class2, params) {+ return new Class2({+ type: "string",+ ...normalizeParams(params)+ });+}+function _email(Class2, params) {+ return new Class2({+ type: "string",+ format: "email",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _guid(Class2, params) {+ return new Class2({+ type: "string",+ format: "guid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _uuid(Class2, params) {+ return new Class2({+ type: "string",+ format: "uuid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _uuidv4(Class2, params) {+ return new Class2({+ type: "string",+ format: "uuid",+ check: "string_format",+ abort: false,+ version: "v4",+ ...normalizeParams(params)+ });+}+function _uuidv6(Class2, params) {+ return new Class2({+ type: "string",+ format: "uuid",+ check: "string_format",+ abort: false,+ version: "v6",+ ...normalizeParams(params)+ });+}+function _uuidv7(Class2, params) {+ return new Class2({+ type: "string",+ format: "uuid",+ check: "string_format",+ abort: false,+ version: "v7",+ ...normalizeParams(params)+ });+}+function _url(Class2, params) {+ return new Class2({+ type: "string",+ format: "url",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _emoji2(Class2, params) {+ return new Class2({+ type: "string",+ format: "emoji",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _nanoid(Class2, params) {+ return new Class2({+ type: "string",+ format: "nanoid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _cuid(Class2, params) {+ return new Class2({+ type: "string",+ format: "cuid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _cuid2(Class2, params) {+ return new Class2({+ type: "string",+ format: "cuid2",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _ulid(Class2, params) {+ return new Class2({+ type: "string",+ format: "ulid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _xid(Class2, params) {+ return new Class2({+ type: "string",+ format: "xid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _ksuid(Class2, params) {+ return new Class2({+ type: "string",+ format: "ksuid",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _ipv4(Class2, params) {+ return new Class2({+ type: "string",+ format: "ipv4",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _ipv6(Class2, params) {+ return new Class2({+ type: "string",+ format: "ipv6",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _cidrv4(Class2, params) {+ return new Class2({+ type: "string",+ format: "cidrv4",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _cidrv6(Class2, params) {+ return new Class2({+ type: "string",+ format: "cidrv6",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _base64(Class2, params) {+ return new Class2({+ type: "string",+ format: "base64",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _base64url(Class2, params) {+ return new Class2({+ type: "string",+ format: "base64url",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _e164(Class2, params) {+ return new Class2({+ type: "string",+ format: "e164",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _jwt(Class2, params) {+ return new Class2({+ type: "string",+ format: "jwt",+ check: "string_format",+ abort: false,+ ...normalizeParams(params)+ });+}+function _isoDateTime(Class2, params) {+ return new Class2({+ type: "string",+ format: "datetime",+ check: "string_format",+ offset: false,+ local: false,+ precision: null,+ ...normalizeParams(params)+ });+}+function _isoDate(Class2, params) {+ return new Class2({+ type: "string",+ format: "date",+ check: "string_format",+ ...normalizeParams(params)+ });+}+function _isoTime(Class2, params) {+ return new Class2({+ type: "string",+ format: "time",+ check: "string_format",+ precision: null,+ ...normalizeParams(params)+ });+}+function _isoDuration(Class2, params) {+ return new Class2({+ type: "string",+ format: "duration",+ check: "string_format",+ ...normalizeParams(params)+ });+}+function _number(Class2, params) {+ return new Class2({+ type: "number",+ checks: [],+ ...normalizeParams(params)+ });+}+function _int(Class2, params) {+ return new Class2({+ type: "number",+ check: "number_format",+ abort: false,+ format: "safeint",+ ...normalizeParams(params)+ });+}+function _boolean(Class2, params) {+ return new Class2({+ type: "boolean",+ ...normalizeParams(params)+ });+}+function _null2(Class2, params) {+ return new Class2({+ type: "null",+ ...normalizeParams(params)+ });+}+function _unknown(Class2) {+ return new Class2({+ type: "unknown"+ });+}+function _never(Class2, params) {+ return new Class2({+ type: "never",+ ...normalizeParams(params)+ });+}+function _lt(value, params) {+ return new $ZodCheckLessThan({+ check: "less_than",+ ...normalizeParams(params),+ value,+ inclusive: false+ });+}+function _lte(value, params) {+ return new $ZodCheckLessThan({+ check: "less_than",+ ...normalizeParams(params),+ value,+ inclusive: true+ });+}+function _gt(value, params) {+ return new $ZodCheckGreaterThan({+ check: "greater_than",+ ...normalizeParams(params),+ value,+ inclusive: false+ });+}+function _gte(value, params) {+ return new $ZodCheckGreaterThan({+ check: "greater_than",+ ...normalizeParams(params),+ value,+ inclusive: true+ });+}+function _multipleOf(value, params) {+ return new $ZodCheckMultipleOf({+ check: "multiple_of",+ ...normalizeParams(params),+ value+ });+}+function _maxLength(maximum, params) {+ const ch = new $ZodCheckMaxLength({+ check: "max_length",+ ...normalizeParams(params),+ maximum+ });+ return ch;+}+function _minLength(minimum, params) {+ return new $ZodCheckMinLength({+ check: "min_length",+ ...normalizeParams(params),+ minimum+ });+}+function _length(length, params) {+ return new $ZodCheckLengthEquals({+ check: "length_equals",+ ...normalizeParams(params),+ length+ });+}+function _regex(pattern, params) {+ return new $ZodCheckRegex({+ check: "string_format",+ format: "regex",+ ...normalizeParams(params),+ pattern+ });+}+function _lowercase(params) {+ return new $ZodCheckLowerCase({+ check: "string_format",+ format: "lowercase",+ ...normalizeParams(params)+ });+}+function _uppercase(params) {+ return new $ZodCheckUpperCase({+ check: "string_format",+ format: "uppercase",+ ...normalizeParams(params)+ });+}+function _includes(includes, params) {+ return new $ZodCheckIncludes({+ check: "string_format",+ format: "includes",+ ...normalizeParams(params),+ includes+ });+}+function _startsWith(prefix, params) {+ return new $ZodCheckStartsWith({+ check: "string_format",+ format: "starts_with",+ ...normalizeParams(params),+ prefix+ });+}+function _endsWith(suffix, params) {+ return new $ZodCheckEndsWith({+ check: "string_format",+ format: "ends_with",+ ...normalizeParams(params),+ suffix+ });+}+function _overwrite(tx) {+ return new $ZodCheckOverwrite({+ check: "overwrite",+ tx+ });+}+function _normalize(form) {+ return _overwrite((input) => input.normalize(form));+}+function _trim() {+ return _overwrite((input) => input.trim());+}+function _toLowerCase() {+ return _overwrite((input) => input.toLowerCase());+}+function _toUpperCase() {+ return _overwrite((input) => input.toUpperCase());+}+function _array(Class2, element, params) {+ return new Class2({+ type: "array",+ element,+ // get element() {+ // return element;+ // },+ ...normalizeParams(params)+ });+}+function _custom(Class2, fn, _params) {+ const norm = normalizeParams(_params);+ norm.abort ?? (norm.abort = true);+ const schema = new Class2({+ type: "custom",+ check: "custom",+ fn,+ ...norm+ });+ return schema;+}+function _refine(Class2, fn, _params) {+ const schema = new Class2({+ type: "custom",+ check: "custom",+ fn,+ ...normalizeParams(_params)+ });+ return schema;+}++// node_modules/zod/v4/core/to-json-schema.js+var JSONSchemaGenerator = class {+ constructor(params) {+ this.counter = 0;+ this.metadataRegistry = params?.metadata ?? globalRegistry;+ this.target = params?.target ?? "draft-2020-12";+ this.unrepresentable = params?.unrepresentable ?? "throw";+ this.override = params?.override ?? (() => {+ });+ this.io = params?.io ?? "output";+ this.seen = /* @__PURE__ */ new Map();+ }+ process(schema, _params = { path: [], schemaPath: [] }) {+ var _a;+ const def = schema._zod.def;+ const formatMap = {+ guid: "uuid",+ url: "uri",+ datetime: "date-time",+ json_string: "json-string",+ regex: ""+ // do not set+ };+ const seen = this.seen.get(schema);+ if (seen) {+ seen.count++;+ const isCycle = _params.schemaPath.includes(schema);+ if (isCycle) {+ seen.cycle = _params.path;+ }+ return seen.schema;+ }+ const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };+ this.seen.set(schema, result);+ const overrideSchema = schema._zod.toJSONSchema?.();+ if (overrideSchema) {+ result.schema = overrideSchema;+ } else {+ const params = {+ ..._params,+ schemaPath: [..._params.schemaPath, schema],+ path: _params.path+ };+ const parent = schema._zod.parent;+ if (parent) {+ result.ref = parent;+ this.process(parent, params);+ this.seen.get(parent).isParent = true;+ } else {+ const _json = result.schema;+ switch (def.type) {+ case "string": {+ const json = _json;+ json.type = "string";+ const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;+ if (typeof minimum === "number")+ json.minLength = minimum;+ if (typeof maximum === "number")+ json.maxLength = maximum;+ if (format) {+ json.format = formatMap[format] ?? format;+ if (json.format === "")+ delete json.format;+ }+ if (contentEncoding)+ json.contentEncoding = contentEncoding;+ if (patterns && patterns.size > 0) {+ const regexes = [...patterns];+ if (regexes.length === 1)+ json.pattern = regexes[0].source;+ else if (regexes.length > 1) {+ result.schema.allOf = [+ ...regexes.map((regex) => ({+ ...this.target === "draft-7" ? { type: "string" } : {},+ pattern: regex.source+ }))+ ];+ }+ }+ break;+ }+ case "number": {+ const json = _json;+ const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;+ if (typeof format === "string" && format.includes("int"))+ json.type = "integer";+ else+ json.type = "number";+ if (typeof exclusiveMinimum === "number")+ json.exclusiveMinimum = exclusiveMinimum;+ if (typeof minimum === "number") {+ json.minimum = minimum;+ if (typeof exclusiveMinimum === "number") {+ if (exclusiveMinimum >= minimum)+ delete json.minimum;+ else+ delete json.exclusiveMinimum;+ }+ }+ if (typeof exclusiveMaximum === "number")+ json.exclusiveMaximum = exclusiveMaximum;+ if (typeof maximum === "number") {+ json.maximum = maximum;+ if (typeof exclusiveMaximum === "number") {+ if (exclusiveMaximum <= maximum)+ delete json.maximum;+ else+ delete json.exclusiveMaximum;+ }+ }+ if (typeof multipleOf === "number")+ json.multipleOf = multipleOf;+ break;+ }+ case "boolean": {+ const json = _json;+ json.type = "boolean";+ break;+ }+ case "bigint": {+ if (this.unrepresentable === "throw") {+ throw new Error("BigInt cannot be represented in JSON Schema");+ }+ break;+ }+ case "symbol": {+ if (this.unrepresentable === "throw") {+ throw new Error("Symbols cannot be represented in JSON Schema");+ }+ break;+ }+ case "null": {+ _json.type = "null";+ break;+ }+ case "any": {+ break;+ }+ case "unknown": {+ break;+ }+ case "undefined": {+ if (this.unrepresentable === "throw") {+ throw new Error("Undefined cannot be represented in JSON Schema");+ }+ break;+ }+ case "void": {+ if (this.unrepresentable === "throw") {+ throw new Error("Void cannot be represented in JSON Schema");+ }+ break;+ }+ case "never": {+ _json.not = {};+ break;+ }+ case "date": {+ if (this.unrepresentable === "throw") {+ throw new Error("Date cannot be represented in JSON Schema");+ }+ break;+ }+ case "array": {+ const json = _json;+ const { minimum, maximum } = schema._zod.bag;+ if (typeof minimum === "number")+ json.minItems = minimum;+ if (typeof maximum === "number")+ json.maxItems = maximum;+ json.type = "array";+ json.items = this.process(def.element, { ...params, path: [...params.path, "items"] });+ break;+ }+ case "object": {+ const json = _json;+ json.type = "object";+ json.properties = {};+ const shape = def.shape;+ for (const key in shape) {+ json.properties[key] = this.process(shape[key], {+ ...params,+ path: [...params.path, "properties", key]+ });+ }+ const allKeys = new Set(Object.keys(shape));+ const requiredKeys = new Set([...allKeys].filter((key) => {+ const v = def.shape[key]._zod;+ if (this.io === "input") {+ return v.optin === void 0;+ } else {+ return v.optout === void 0;+ }+ }));+ if (requiredKeys.size > 0) {+ json.required = Array.from(requiredKeys);+ }+ if (def.catchall?._zod.def.type === "never") {+ json.additionalProperties = false;+ } else if (!def.catchall) {+ if (this.io === "output")+ json.additionalProperties = false;+ } else if (def.catchall) {+ json.additionalProperties = this.process(def.catchall, {+ ...params,+ path: [...params.path, "additionalProperties"]+ });+ }+ break;+ }+ case "union": {+ const json = _json;+ json.anyOf = def.options.map((x, i) => this.process(x, {+ ...params,+ path: [...params.path, "anyOf", i]+ }));+ break;+ }+ case "intersection": {+ const json = _json;+ const a = this.process(def.left, {+ ...params,+ path: [...params.path, "allOf", 0]+ });+ const b = this.process(def.right, {+ ...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;+ break;+ }+ case "tuple": {+ const json = _json;+ json.type = "array";+ const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] }));+ if (this.target === "draft-2020-12") {+ json.prefixItems = prefixItems;+ } else {+ json.items = prefixItems;+ }+ if (def.rest) {+ const rest = this.process(def.rest, {+ ...params,+ path: [...params.path, "items"]+ });+ if (this.target === "draft-2020-12") {+ json.items = rest;+ } else {+ json.additionalItems = rest;+ }+ }+ if (def.rest) {+ json.items = this.process(def.rest, {+ ...params,+ path: [...params.path, "items"]+ });+ }+ const { minimum, maximum } = schema._zod.bag;+ if (typeof minimum === "number")+ json.minItems = minimum;+ if (typeof maximum === "number")+ json.maxItems = maximum;+ break;+ }+ case "record": {+ const json = _json;+ json.type = "object";+ json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] });+ json.additionalProperties = this.process(def.valueType, {+ ...params,+ path: [...params.path, "additionalProperties"]+ });+ break;+ }+ case "map": {+ if (this.unrepresentable === "throw") {+ throw new Error("Map cannot be represented in JSON Schema");+ }+ break;+ }+ case "set": {+ if (this.unrepresentable === "throw") {+ throw new Error("Set cannot be represented in JSON Schema");+ }+ break;+ }+ case "enum": {+ const json = _json;+ const values = getEnumValues(def.entries);+ if (values.every((v) => typeof v === "number"))+ json.type = "number";+ if (values.every((v) => typeof v === "string"))+ json.type = "string";+ json.enum = values;+ break;+ }+ case "literal": {+ const json = _json;+ const vals = [];+ for (const val of def.values) {+ if (val === void 0) {+ if (this.unrepresentable === "throw") {+ throw new Error("Literal `undefined` cannot be represented in JSON Schema");+ } else {+ }+ } else if (typeof val === "bigint") {+ if (this.unrepresentable === "throw") {+ throw new Error("BigInt literals cannot be represented in JSON Schema");+ } else {+ vals.push(Number(val));+ }+ } else {+ vals.push(val);+ }+ }+ if (vals.length === 0) {+ } else if (vals.length === 1) {+ const val = vals[0];+ json.type = val === null ? "null" : typeof val;+ 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 = "string";+ if (vals.every((v) => v === null))+ json.type = "null";+ json.enum = vals;+ }+ break;+ }+ case "file": {+ const json = _json;+ const file = {+ type: "string",+ format: "binary",+ contentEncoding: "binary"+ };+ const { minimum, maximum, mime } = schema._zod.bag;+ if (minimum !== void 0)+ file.minLength = minimum;+ if (maximum !== void 0)+ file.maxLength = maximum;+ if (mime) {+ if (mime.length === 1) {+ file.contentMediaType = mime[0];+ Object.assign(json, file);+ } else {+ json.anyOf = mime.map((m) => {+ const mFile = { ...file, contentMediaType: m };+ return mFile;+ });+ }+ } else {+ Object.assign(json, file);+ }+ break;+ }+ case "transform": {+ if (this.unrepresentable === "throw") {+ throw new Error("Transforms cannot be represented in JSON Schema");+ }+ break;+ }+ case "nullable": {+ const inner = this.process(def.innerType, params);+ _json.anyOf = [inner, { type: "null" }];+ break;+ }+ case "nonoptional": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ break;+ }+ case "success": {+ const json = _json;+ json.type = "boolean";+ break;+ }+ case "default": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ _json.default = JSON.parse(JSON.stringify(def.defaultValue));+ break;+ }+ case "prefault": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ if (this.io === "input")+ _json._prefault = JSON.parse(JSON.stringify(def.defaultValue));+ break;+ }+ case "catch": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ let catchValue;+ try {+ catchValue = def.catchValue(void 0);+ } catch {+ throw new Error("Dynamic catch values are not supported in JSON Schema");+ }+ _json.default = catchValue;+ break;+ }+ case "nan": {+ if (this.unrepresentable === "throw") {+ throw new Error("NaN cannot be represented in JSON Schema");+ }+ break;+ }+ case "template_literal": {+ 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;+ break;+ }+ case "pipe": {+ const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;+ this.process(innerType, params);+ result.ref = innerType;+ break;+ }+ case "readonly": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ _json.readOnly = true;+ break;+ }+ // passthrough types+ case "promise": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ break;+ }+ case "optional": {+ this.process(def.innerType, params);+ result.ref = def.innerType;+ break;+ }+ case "lazy": {+ const innerType = schema._zod.innerType;+ this.process(innerType, params);+ result.ref = innerType;+ break;+ }+ case "custom": {+ if (this.unrepresentable === "throw") {+ throw new Error("Custom types cannot be represented in JSON Schema");+ }+ break;+ }+ default: {+ def;+ }+ }+ }+ }+ const meta = this.metadataRegistry.get(schema);+ if (meta)+ Object.assign(result.schema, meta);+ if (this.io === "input" && isTransforming(schema)) {+ delete result.schema.examples;+ delete result.schema.default;+ }+ if (this.io === "input" && result.schema._prefault)+ (_a = result.schema).default ?? (_a.default = result.schema._prefault);+ delete result.schema._prefault;+ const _result = this.seen.get(schema);+ return _result.schema;+ }+ emit(schema, _params) {+ const params = {+ cycles: _params?.cycles ?? "ref",+ reused: _params?.reused ?? "inline",+ // unrepresentable: _params?.unrepresentable ?? "throw",+ // uri: _params?.uri ?? ((id) => `${id}`),+ external: _params?.external ?? void 0+ };+ const root = this.seen.get(schema);+ if (!root)+ throw new Error("Unprocessed schema. This is a bug in Zod.");+ const makeURI = (entry) => {+ const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions";+ if (params.external) {+ const externalId = params.external.registry.get(entry[0])?.id;+ const uriGenerator = params.external.uri ?? ((id2) => id2);+ if (externalId) {+ return { ref: uriGenerator(externalId) };+ }+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`;+ entry[1].defId = id;+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };+ }+ if (entry[1] === root) {+ return { ref: "#" };+ }+ const uriPrefix = `#`;+ const defUriPrefix = `${uriPrefix}/${defsSegment}/`;+ const defId = entry[1].schema.id ?? `__schema${this.counter++}`;+ return { defId, ref: defUriPrefix + defId };+ };+ const extractToDef = (entry) => {+ if (entry[1].schema.$ref) {+ return;+ }+ const seen = entry[1];+ const { ref, defId } = makeURI(entry);+ seen.def = { ...seen.schema };+ if (defId)+ seen.defId = defId;+ const schema2 = seen.schema;+ for (const key in schema2) {+ delete schema2[key];+ }+ schema2.$ref = ref;+ };+ if (params.cycles === "throw") {+ for (const entry of this.seen.entries()) {+ const seen = entry[1];+ if (seen.cycle) {+ throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>++Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);+ }+ }+ }+ for (const entry of this.seen.entries()) {+ const seen = entry[1];+ if (schema === entry[0]) {+ extractToDef(entry);+ continue;+ }+ if (params.external) {+ const ext = params.external.registry.get(entry[0])?.id;+ if (schema !== entry[0] && ext) {+ extractToDef(entry);+ continue;+ }+ }+ const id = this.metadataRegistry.get(entry[0])?.id;+ if (id) {+ extractToDef(entry);+ continue;+ }+ if (seen.cycle) {+ extractToDef(entry);+ continue;+ }+ if (seen.count > 1) {+ if (params.reused === "ref") {+ extractToDef(entry);+ continue;+ }+ }+ }+ const flattenRef = (zodSchema, params2) => {+ const seen = this.seen.get(zodSchema);+ const schema2 = seen.def ?? seen.schema;+ const _cached = { ...schema2 };+ if (seen.ref === null) {+ return;+ }+ const ref = seen.ref;+ seen.ref = null;+ if (ref) {+ flattenRef(ref, params2);+ const refSchema = this.seen.get(ref).schema;+ if (refSchema.$ref && params2.target === "draft-7") {+ schema2.allOf = schema2.allOf ?? [];+ schema2.allOf.push(refSchema);+ } else {+ Object.assign(schema2, refSchema);+ Object.assign(schema2, _cached);+ }+ }+ if (!seen.isParent)+ this.override({+ zodSchema,+ jsonSchema: schema2,+ path: seen.path ?? []+ });+ };+ for (const entry of [...this.seen.entries()].reverse()) {+ flattenRef(entry[0], { target: this.target });+ }+ const result = {};+ if (this.target === "draft-2020-12") {+ result.$schema = "https://json-schema.org/draft/2020-12/schema";+ } else if (this.target === "draft-7") {+ result.$schema = "http://json-schema.org/draft-07/schema#";+ } else {+ console.warn(`Invalid target: ${this.target}`);+ }+ if (params.external?.uri) {+ const id = params.external.registry.get(schema)?.id;+ if (!id)+ throw new Error("Schema is missing an `id` property");+ result.$id = params.external.uri(id);+ }+ Object.assign(result, root.def);+ const defs = params.external?.defs ?? {};+ for (const entry of this.seen.entries()) {+ const seen = entry[1];+ if (seen.def && seen.defId) {+ defs[seen.defId] = seen.def;+ }+ }+ if (params.external) {+ } else {+ if (Object.keys(defs).length > 0) {+ if (this.target === "draft-2020-12") {+ result.$defs = defs;+ } else {+ result.definitions = defs;+ }+ }+ }+ try {+ return JSON.parse(JSON.stringify(result));+ } catch (_err) {+ throw new Error("Error converting schema to JSON.");+ }+ }+};+function toJSONSchema(input, _params) {+ if (input instanceof $ZodRegistry) {+ const gen2 = new JSONSchemaGenerator(_params);+ const defs = {};+ for (const entry of input._idmap.entries()) {+ const [_, schema] = entry;+ gen2.process(schema);+ }+ const schemas = {};+ const external = {+ registry: input,+ uri: _params?.uri,+ defs+ };+ for (const entry of input._idmap.entries()) {+ const [key, schema] = entry;+ schemas[key] = gen2.emit(schema, {+ ..._params,+ external+ });+ }+ if (Object.keys(defs).length > 0) {+ const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions";+ schemas.__shared = {+ [defsSegment]: defs+ };+ }+ return { schemas };+ }+ const gen = new JSONSchemaGenerator(_params);+ gen.process(input);+ return gen.emit(input, _params);+}+function isTransforming(_schema, _ctx) {+ const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };+ if (ctx.seen.has(_schema))+ return false;+ ctx.seen.add(_schema);+ const schema = _schema;+ const def = schema._zod.def;+ switch (def.type) {+ case "string":+ case "number":+ case "bigint":+ case "boolean":+ case "date":+ case "symbol":+ case "undefined":+ case "null":+ case "any":+ case "unknown":+ case "never":+ case "void":+ case "literal":+ case "enum":+ case "nan":+ case "file":+ case "template_literal":+ return false;+ case "array": {+ return isTransforming(def.element, ctx);+ }+ case "object": {+ for (const key in def.shape) {+ if (isTransforming(def.shape[key], ctx))+ return true;+ }+ return false;+ }+ case "union": {+ for (const option of def.options) {+ if (isTransforming(option, ctx))+ return true;+ }+ return false;+ }+ case "intersection": {+ return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);+ }+ case "tuple": {+ for (const item of def.items) {+ if (isTransforming(item, ctx))+ return true;+ }+ if (def.rest && isTransforming(def.rest, ctx))+ return true;+ return false;+ }+ case "record": {+ return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);+ }+ case "map": {+ return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);+ }+ case "set": {+ return isTransforming(def.valueType, ctx);+ }+ // inner types+ case "promise":+ case "optional":+ case "nonoptional":+ case "nullable":+ case "readonly":+ return isTransforming(def.innerType, ctx);+ case "lazy":+ return isTransforming(def.getter(), ctx);+ case "default": {+ return isTransforming(def.innerType, ctx);+ }+ case "prefault": {+ return isTransforming(def.innerType, ctx);+ }+ case "custom": {+ return false;+ }+ case "transform": {+ return true;+ }+ case "pipe": {+ return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);+ }+ case "success": {+ return false;+ }+ case "catch": {+ return false;+ }+ default:+ def;+ }+ throw new Error(`Unknown schema type: ${def.type}`);+}++// node_modules/zod/v4/classic/iso.js+var iso_exports = {};+__export(iso_exports, {+ ZodISODate: () => ZodISODate,+ ZodISODateTime: () => ZodISODateTime,+ ZodISODuration: () => ZodISODuration,+ ZodISOTime: () => ZodISOTime,+ date: () => date2,+ datetime: () => datetime2,+ duration: () => duration2,+ time: () => time2+});+var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {+ $ZodISODateTime.init(inst, def);+ ZodStringFormat.init(inst, def);+});+function datetime2(params) {+ return _isoDateTime(ZodISODateTime, params);+}+var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {+ $ZodISODate.init(inst, def);+ ZodStringFormat.init(inst, def);+});+function date2(params) {+ return _isoDate(ZodISODate, params);+}+var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {+ $ZodISOTime.init(inst, def);+ ZodStringFormat.init(inst, def);+});+function time2(params) {+ return _isoTime(ZodISOTime, params);+}+var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {+ $ZodISODuration.init(inst, def);+ ZodStringFormat.init(inst, def);+});+function duration2(params) {+ return _isoDuration(ZodISODuration, params);+}++// node_modules/zod/v4/classic/errors.js+var initializer2 = (inst, issues) => {+ $ZodError.init(inst, issues);+ inst.name = "ZodError";+ Object.defineProperties(inst, {+ format: {+ value: (mapper) => formatError(inst, mapper)+ // enumerable: false,+ },+ flatten: {+ value: (mapper) => flattenError(inst, mapper)+ // enumerable: false,+ },+ addIssue: {+ value: (issue2) => inst.issues.push(issue2)+ // enumerable: false,+ },+ addIssues: {+ value: (issues2) => inst.issues.push(...issues2)+ // enumerable: false,+ },+ isEmpty: {+ get() {+ return inst.issues.length === 0;+ }+ // enumerable: false,+ }+ });+};+var ZodError = $constructor("ZodError", initializer2);+var ZodRealError = $constructor("ZodError", initializer2, {+ Parent: Error+});++// node_modules/zod/v4/classic/parse.js+var parse2 = /* @__PURE__ */ _parse(ZodRealError);+var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);+var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);+var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);++// node_modules/zod/v4/classic/schemas.js+var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {+ $ZodType.init(inst, def);+ inst.def = def;+ Object.defineProperty(inst, "_def", { value: def });+ inst.check = (...checks) => {+ return inst.clone(+ {+ ...def,+ checks: [+ ...def.checks ?? [],+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)+ ]+ }+ // { parent: true }+ );+ };+ inst.clone = (def2, params) => clone(inst, def2, params);+ inst.brand = () => inst;+ inst.register = (reg, meta) => {+ reg.add(inst, meta);+ return inst;+ };+ inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse });+ inst.safeParse = (data, params) => safeParse2(inst, data, params);+ inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });+ inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);+ inst.spa = inst.safeParseAsync;+ inst.refine = (check2, params) => inst.check(refine(check2, params));+ inst.superRefine = (refinement) => inst.check(superRefine(refinement));+ inst.overwrite = (fn) => inst.check(_overwrite(fn));+ inst.optional = () => optional(inst);+ inst.nullable = () => nullable(inst);+ inst.nullish = () => optional(nullable(inst));+ inst.nonoptional = (params) => nonoptional(inst, params);+ inst.array = () => array(inst);+ inst.or = (arg) => union([inst, arg]);+ inst.and = (arg) => intersection(inst, arg);+ inst.transform = (tx) => pipe(inst, transform(tx));+ inst.default = (def2) => _default(inst, def2);+ inst.prefault = (def2) => prefault(inst, def2);+ inst.catch = (params) => _catch(inst, params);+ inst.pipe = (target) => pipe(inst, target);+ inst.readonly = () => readonly(inst);+ inst.describe = (description) => {+ const cl = inst.clone();+ globalRegistry.add(cl, { description });+ return cl;+ };+ Object.defineProperty(inst, "description", {+ get() {+ return globalRegistry.get(inst)?.description;+ },+ configurable: true+ });+ inst.meta = (...args) => {+ if (args.length === 0) {+ return globalRegistry.get(inst);+ }+ const cl = inst.clone();+ globalRegistry.add(cl, args[0]);+ return cl;+ };+ inst.isOptional = () => inst.safeParse(void 0).success;+ inst.isNullable = () => inst.safeParse(null).success;+ return inst;+});+var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {+ $ZodString.init(inst, def);+ ZodType.init(inst, def);+ const bag = inst._zod.bag;+ inst.format = bag.format ?? null;+ inst.minLength = bag.minimum ?? null;+ inst.maxLength = bag.maximum ?? null;+ inst.regex = (...args) => inst.check(_regex(...args));+ inst.includes = (...args) => inst.check(_includes(...args));+ inst.startsWith = (...args) => inst.check(_startsWith(...args));+ inst.endsWith = (...args) => inst.check(_endsWith(...args));+ inst.min = (...args) => inst.check(_minLength(...args));+ inst.max = (...args) => inst.check(_maxLength(...args));+ inst.length = (...args) => inst.check(_length(...args));+ inst.nonempty = (...args) => inst.check(_minLength(1, ...args));+ inst.lowercase = (params) => inst.check(_lowercase(params));+ inst.uppercase = (params) => inst.check(_uppercase(params));+ inst.trim = () => inst.check(_trim());+ inst.normalize = (...args) => inst.check(_normalize(...args));+ inst.toLowerCase = () => inst.check(_toLowerCase());+ inst.toUpperCase = () => inst.check(_toUpperCase());+});+var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {+ $ZodString.init(inst, def);+ _ZodString.init(inst, def);+ inst.email = (params) => inst.check(_email(ZodEmail, params));+ inst.url = (params) => inst.check(_url(ZodURL, params));+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));+ inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));+ inst.xid = (params) => inst.check(_xid(ZodXID, params));+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));+ inst.datetime = (params) => inst.check(datetime2(params));+ inst.date = (params) => inst.check(date2(params));+ inst.time = (params) => inst.check(time2(params));+ inst.duration = (params) => inst.check(duration2(params));+});+function string2(params) {+ return _string(ZodString, params);+}+var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {+ $ZodStringFormat.init(inst, def);+ _ZodString.init(inst, def);+});+var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {+ $ZodEmail.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {+ $ZodGUID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {+ $ZodUUID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {+ $ZodURL.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {+ $ZodEmoji.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {+ $ZodNanoID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {+ $ZodCUID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {+ $ZodCUID2.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {+ $ZodULID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {+ $ZodXID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {+ $ZodKSUID.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {+ $ZodIPv4.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {+ $ZodIPv6.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {+ $ZodCIDRv4.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {+ $ZodCIDRv6.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {+ $ZodBase64.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {+ $ZodBase64URL.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {+ $ZodE164.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {+ $ZodJWT.init(inst, def);+ ZodStringFormat.init(inst, def);+});+var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {+ $ZodNumber.init(inst, def);+ ZodType.init(inst, def);+ inst.gt = (value, params) => inst.check(_gt(value, params));+ inst.gte = (value, params) => inst.check(_gte(value, params));+ inst.min = (value, params) => inst.check(_gte(value, params));+ inst.lt = (value, params) => inst.check(_lt(value, params));+ inst.lte = (value, params) => inst.check(_lte(value, params));+ inst.max = (value, params) => inst.check(_lte(value, params));+ inst.int = (params) => inst.check(int(params));+ inst.safe = (params) => inst.check(int(params));+ inst.positive = (params) => inst.check(_gt(0, params));+ inst.nonnegative = (params) => inst.check(_gte(0, params));+ inst.negative = (params) => inst.check(_lt(0, params));+ inst.nonpositive = (params) => inst.check(_lte(0, params));+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));+ inst.step = (value, params) => inst.check(_multipleOf(value, params));+ inst.finite = () => inst;+ const bag = inst._zod.bag;+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);+ inst.isFinite = true;+ inst.format = bag.format ?? null;+});+function number2(params) {+ return _number(ZodNumber, params);+}+var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {+ $ZodNumberFormat.init(inst, def);+ ZodNumber.init(inst, def);+});+function int(params) {+ return _int(ZodNumberFormat, params);+}+var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {+ $ZodBoolean.init(inst, def);+ ZodType.init(inst, def);+});+function boolean2(params) {+ return _boolean(ZodBoolean, params);+}+var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {+ $ZodNull.init(inst, def);+ ZodType.init(inst, def);+});+function _null3(params) {+ return _null2(ZodNull, params);+}+var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {+ $ZodUnknown.init(inst, def);+ ZodType.init(inst, def);+});+function unknown() {+ return _unknown(ZodUnknown);+}+var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {+ $ZodNever.init(inst, def);+ ZodType.init(inst, def);+});+function never(params) {+ return _never(ZodNever, params);+}+var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {+ $ZodArray.init(inst, def);+ ZodType.init(inst, def);+ inst.element = def.element;+ inst.min = (minLength, params) => inst.check(_minLength(minLength, params));+ inst.nonempty = (params) => inst.check(_minLength(1, params));+ inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));+ inst.length = (len, params) => inst.check(_length(len, params));+ inst.unwrap = () => inst.element;+});+function array(element, params) {+ return _array(ZodArray, element, params);+}+var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {+ $ZodObject.init(inst, def);+ ZodType.init(inst, def);+ util_exports.defineLazy(inst, "shape", () => def.shape);+ inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));+ inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });+ inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });+ inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });+ inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });+ inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });+ inst.extend = (incoming) => {+ return util_exports.extend(inst, incoming);+ };+ inst.merge = (other) => util_exports.merge(inst, other);+ inst.pick = (mask) => util_exports.pick(inst, mask);+ inst.omit = (mask) => util_exports.omit(inst, mask);+ inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]);+ inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]);+});+function object(shape, params) {+ const def = {+ type: "object",+ get shape() {+ util_exports.assignProp(this, "shape", { ...shape });+ return this.shape;+ },+ ...util_exports.normalizeParams(params)+ };+ return new ZodObject(def);+}+function looseObject(shape, params) {+ return new ZodObject({+ type: "object",+ get shape() {+ util_exports.assignProp(this, "shape", { ...shape });+ return this.shape;+ },+ catchall: unknown(),+ ...util_exports.normalizeParams(params)+ });+}+var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {+ $ZodUnion.init(inst, def);+ ZodType.init(inst, def);+ inst.options = def.options;+});+function union(options, params) {+ return new ZodUnion({+ type: "union",+ options,+ ...util_exports.normalizeParams(params)+ });+}+var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {+ ZodUnion.init(inst, def);+ $ZodDiscriminatedUnion.init(inst, def);+});+function discriminatedUnion(discriminator, options, params) {+ return new ZodDiscriminatedUnion({+ type: "union",+ options,+ discriminator,+ ...util_exports.normalizeParams(params)+ });+}+var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {+ $ZodIntersection.init(inst, def);+ ZodType.init(inst, def);+});+function intersection(left, right) {+ return new ZodIntersection({+ type: "intersection",+ left,+ right+ });+}+var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {+ $ZodRecord.init(inst, def);+ ZodType.init(inst, def);+ inst.keyType = def.keyType;+ inst.valueType = def.valueType;+});+function record(keyType, valueType, params) {+ return new ZodRecord({+ type: "record",+ keyType,+ valueType,+ ...util_exports.normalizeParams(params)+ });+}+var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {+ $ZodEnum.init(inst, def);+ ZodType.init(inst, def);+ inst.enum = def.entries;+ inst.options = Object.values(def.entries);+ 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: [],+ ...util_exports.normalizeParams(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: [],+ ...util_exports.normalizeParams(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,+ ...util_exports.normalizeParams(params)+ });+}+var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {+ $ZodLiteral.init(inst, def);+ ZodType.init(inst, def);+ 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],+ ...util_exports.normalizeParams(params)+ });+}+var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {+ $ZodTransform.init(inst, def);+ ZodType.init(inst, def);+ inst._zod.parse = (payload, _ctx) => {+ payload.addIssue = (issue2) => {+ if (typeof issue2 === "string") {+ payload.issues.push(util_exports.issue(issue2, payload.value, def));+ } else {+ const _issue = issue2;+ if (_issue.fatal)+ _issue.continue = false;+ _issue.code ?? (_issue.code = "custom");+ _issue.input ?? (_issue.input = payload.value);+ _issue.inst ?? (_issue.inst = inst);+ _issue.continue ?? (_issue.continue = true);+ payload.issues.push(util_exports.issue(_issue));+ }+ };+ const output = def.transform(payload.value, payload);+ if (output instanceof Promise) {+ return output.then((output2) => {+ payload.value = output2;+ return payload;+ });+ }+ payload.value = output;+ return payload;+ };+});+function transform(fn) {+ return new ZodTransform({+ type: "transform",+ transform: fn+ });+}+var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {+ $ZodOptional.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+});+function optional(innerType) {+ return new ZodOptional({+ type: "optional",+ innerType+ });+}+var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {+ $ZodNullable.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+});+function nullable(innerType) {+ return new ZodNullable({+ type: "nullable",+ innerType+ });+}+var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {+ $ZodDefault.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+ inst.removeDefault = inst.unwrap;+});+function _default(innerType, defaultValue) {+ return new ZodDefault({+ type: "default",+ innerType,+ get defaultValue() {+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;+ }+ });+}+var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {+ $ZodPrefault.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+});+function prefault(innerType, defaultValue) {+ return new ZodPrefault({+ type: "prefault",+ innerType,+ get defaultValue() {+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;+ }+ });+}+var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {+ $ZodNonOptional.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+});+function nonoptional(innerType, params) {+ return new ZodNonOptional({+ type: "nonoptional",+ innerType,+ ...util_exports.normalizeParams(params)+ });+}+var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {+ $ZodCatch.init(inst, def);+ ZodType.init(inst, def);+ inst.unwrap = () => inst._zod.def.innerType;+ inst.removeCatch = inst.unwrap;+});+function _catch(innerType, catchValue) {+ return new ZodCatch({+ type: "catch",+ innerType,+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue+ });+}+var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {+ $ZodPipe.init(inst, def);+ ZodType.init(inst, def);+ inst.in = def.in;+ inst.out = def.out;+});+function pipe(in_, out) {+ return new ZodPipe({+ type: "pipe",+ in: in_,+ out+ // ...util.normalizeParams(params),+ });+}+var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {+ $ZodReadonly.init(inst, def);+ ZodType.init(inst, def);+});+function readonly(innerType) {+ return new ZodReadonly({+ type: "readonly",+ innerType+ });+}+var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {+ $ZodCustom.init(inst, def);+ ZodType.init(inst, def);+});+function check(fn) {+ const ch = new $ZodCheck({+ check: "custom"+ // ...util.normalizeParams(params),+ });+ ch._zod.check = fn;+ return ch;+}+function custom(fn, _params) {+ return _custom(ZodCustom, fn ?? (() => true), _params);+}+function refine(fn, _params = {}) {+ return _refine(ZodCustom, fn, _params);+}+function superRefine(fn) {+ const ch = check((payload) => {+ payload.addIssue = (issue2) => {+ if (typeof issue2 === "string") {+ payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def));+ } else {+ const _issue = issue2;+ if (_issue.fatal)+ _issue.continue = false;+ _issue.code ?? (_issue.code = "custom");+ _issue.input ?? (_issue.input = payload.value);+ _issue.inst ?? (_issue.inst = ch);+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);+ payload.issues.push(util_exports.issue(_issue));+ }+ };+ return fn(payload.value, payload);+ });+ return ch;+}+function preprocess(fn, schema) {+ return pipe(transform(fn), schema);+}++// node_modules/zod/v4/classic/external.js+config(en_default());++// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js+var LATEST_PROTOCOL_VERSION = "2025-11-25";+var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];+var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";+var JSONRPC_VERSION = "2.0";+var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));+var ProgressTokenSchema = union([string2(), number2().int()]);+var CursorSchema = string2();+var TaskCreationParamsSchema = looseObject({+ /**+ * Requested duration in milliseconds to retain task from creation.+ */+ ttl: number2().optional(),+ /**+ * Time in milliseconds to wait between task status requests.+ */+ pollInterval: number2().optional()+});+var TaskMetadataSchema = object({+ ttl: number2().optional()+});+var RelatedTaskMetadataSchema = object({+ taskId: string2()+});+var RequestMetaSchema = looseObject({+ /**+ * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.+ */+ progressToken: ProgressTokenSchema.optional(),+ /**+ * If specified, this request is related to the provided task.+ */+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()+});+var BaseRequestParamsSchema = object({+ /**+ * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.+ */+ _meta: RequestMetaSchema.optional()+});+var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * If specified, the caller is requesting task-augmented execution for this request.+ * The request will return a CreateTaskResult immediately, and the actual result can be+ * retrieved later via tasks/result.+ *+ * Task augmentation is subject to capability negotiation - receivers MUST declare support+ * for task augmentation of specific request types in their capabilities.+ */+ task: TaskMetadataSchema.optional()+});+var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;+var RequestSchema = object({+ method: string2(),+ params: BaseRequestParamsSchema.loose().optional()+});+var NotificationsParamsSchema = object({+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: RequestMetaSchema.optional()+});+var NotificationSchema = object({+ method: string2(),+ params: NotificationsParamsSchema.loose().optional()+});+var ResultSchema = looseObject({+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: RequestMetaSchema.optional()+});+var RequestIdSchema = union([string2(), number2().int()]);+var JSONRPCRequestSchema = object({+ jsonrpc: literal(JSONRPC_VERSION),+ id: RequestIdSchema,+ ...RequestSchema.shape+}).strict();+var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;+var JSONRPCNotificationSchema = object({+ jsonrpc: literal(JSONRPC_VERSION),+ ...NotificationSchema.shape+}).strict();+var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;+var JSONRPCResultResponseSchema = object({+ jsonrpc: literal(JSONRPC_VERSION),+ id: RequestIdSchema,+ result: ResultSchema+}).strict();+var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;+var ErrorCode;+(function(ErrorCode2) {+ ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";+ ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";+ ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";+ ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";+ ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";+ ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";+ ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";+ ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";+})(ErrorCode || (ErrorCode = {}));+var JSONRPCErrorResponseSchema = object({+ jsonrpc: literal(JSONRPC_VERSION),+ id: RequestIdSchema.optional(),+ error: object({+ /**+ * The error type that occurred.+ */+ code: number2().int(),+ /**+ * A short description of the error. The message SHOULD be limited to a concise single sentence.+ */+ message: string2(),+ /**+ * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).+ */+ data: unknown().optional()+ })+}).strict();+var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;+var JSONRPCMessageSchema = union([+ JSONRPCRequestSchema,+ JSONRPCNotificationSchema,+ JSONRPCResultResponseSchema,+ JSONRPCErrorResponseSchema+]);+var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);+var EmptyResultSchema = ResultSchema.strict();+var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({+ /**+ * The ID of the request to cancel.+ *+ * This MUST correspond to the ID of a request previously issued in the same direction.+ */+ requestId: RequestIdSchema.optional(),+ /**+ * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.+ */+ reason: string2().optional()+});+var CancelledNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/cancelled"),+ params: CancelledNotificationParamsSchema+});+var IconSchema = object({+ /**+ * URL or data URI for the icon.+ */+ src: string2(),+ /**+ * Optional MIME type for the icon.+ */+ mimeType: string2().optional(),+ /**+ * Optional array of strings that specify sizes at which the icon can be used.+ * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.+ *+ * If not provided, the client should assume that the icon can be used at any size.+ */+ sizes: array(string2()).optional(),+ /**+ * Optional specifier for the theme this icon is designed for. `light` indicates+ * the icon is designed to be used with a light background, and `dark` indicates+ * the icon is designed to be used with a dark background.+ *+ * If not provided, the client should assume the icon can be used with any theme.+ */+ theme: _enum(["light", "dark"]).optional()+});+var IconsSchema = object({+ /**+ * Optional set of sized icons that the client can display in a user interface.+ *+ * Clients that support rendering icons MUST support at least the following MIME types:+ * - `image/png` - PNG images (safe, universal compatibility)+ * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)+ *+ * Clients that support rendering icons SHOULD also support:+ * - `image/svg+xml` - SVG images (scalable but requires security precautions)+ * - `image/webp` - WebP images (modern, efficient format)+ */+ icons: array(IconSchema).optional()+});+var BaseMetadataSchema = object({+ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */+ name: string2(),+ /**+ * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,+ * even by those unfamiliar with domain-specific terminology.+ *+ * If not provided, the name should be used for display (except for Tool,+ * where `annotations.title` should be given precedence over using `name`,+ * if present).+ */+ title: string2().optional()+});+var ImplementationSchema = BaseMetadataSchema.extend({+ ...BaseMetadataSchema.shape,+ ...IconsSchema.shape,+ version: string2(),+ /**+ * An optional URL of the website for this implementation.+ */+ websiteUrl: string2().optional(),+ /**+ * An optional human-readable description of what this implementation does.+ *+ * This can be used by clients or servers to provide context about their purpose+ * and capabilities. For example, a server might describe the types of resources+ * or tools it provides, while a client might describe its intended use case.+ */+ description: string2().optional()+});+var FormElicitationCapabilitySchema = intersection(object({+ applyDefaults: boolean2().optional()+}), record(string2(), unknown()));+var ElicitationCapabilitySchema = preprocess((value) => {+ if (value && typeof value === "object" && !Array.isArray(value)) {+ if (Object.keys(value).length === 0) {+ return { form: {} };+ }+ }+ return value;+}, intersection(object({+ form: FormElicitationCapabilitySchema.optional(),+ url: AssertObjectSchema.optional()+}), record(string2(), unknown()).optional()));+var ClientTasksCapabilitySchema = looseObject({+ /**+ * Present if the client supports listing tasks.+ */+ list: AssertObjectSchema.optional(),+ /**+ * Present if the client supports cancelling tasks.+ */+ cancel: AssertObjectSchema.optional(),+ /**+ * Capabilities for task creation on specific request types.+ */+ requests: looseObject({+ /**+ * Task support for sampling requests.+ */+ sampling: looseObject({+ createMessage: AssertObjectSchema.optional()+ }).optional(),+ /**+ * Task support for elicitation requests.+ */+ elicitation: looseObject({+ create: AssertObjectSchema.optional()+ }).optional()+ }).optional()+});+var ServerTasksCapabilitySchema = looseObject({+ /**+ * Present if the server supports listing tasks.+ */+ list: AssertObjectSchema.optional(),+ /**+ * Present if the server supports cancelling tasks.+ */+ cancel: AssertObjectSchema.optional(),+ /**+ * Capabilities for task creation on specific request types.+ */+ requests: looseObject({+ /**+ * Task support for tool requests.+ */+ tools: looseObject({+ call: AssertObjectSchema.optional()+ }).optional()+ }).optional()+});+var ClientCapabilitiesSchema = object({+ /**+ * Experimental, non-standard capabilities that the client supports.+ */+ experimental: record(string2(), AssertObjectSchema).optional(),+ /**+ * Present if the client supports sampling from an LLM.+ */+ sampling: object({+ /**+ * Present if the client supports context inclusion via includeContext parameter.+ * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).+ */+ context: AssertObjectSchema.optional(),+ /**+ * Present if the client supports tool use via tools and toolChoice parameters.+ */+ tools: AssertObjectSchema.optional()+ }).optional(),+ /**+ * Present if the client supports eliciting user input.+ */+ elicitation: ElicitationCapabilitySchema.optional(),+ /**+ * Present if the client supports listing roots.+ */+ roots: object({+ /**+ * Whether the client supports issuing notifications for changes to the roots list.+ */+ listChanged: boolean2().optional()+ }).optional(),+ /**+ * Present if the client supports task creation.+ */+ tasks: ClientTasksCapabilitySchema.optional(),+ /**+ * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).+ */+ extensions: record(string2(), AssertObjectSchema).optional()+});+var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.+ */+ protocolVersion: string2(),+ capabilities: ClientCapabilitiesSchema,+ clientInfo: ImplementationSchema+});+var InitializeRequestSchema = RequestSchema.extend({+ method: literal("initialize"),+ params: InitializeRequestParamsSchema+});+var ServerCapabilitiesSchema = object({+ /**+ * Experimental, non-standard capabilities that the server supports.+ */+ experimental: record(string2(), AssertObjectSchema).optional(),+ /**+ * Present if the server supports sending log messages to the client.+ */+ logging: AssertObjectSchema.optional(),+ /**+ * Present if the server supports sending completions to the client.+ */+ completions: AssertObjectSchema.optional(),+ /**+ * Present if the server offers any prompt templates.+ */+ prompts: object({+ /**+ * Whether this server supports issuing notifications for changes to the prompt list.+ */+ listChanged: boolean2().optional()+ }).optional(),+ /**+ * Present if the server offers any resources to read.+ */+ resources: object({+ /**+ * Whether this server supports clients subscribing to resource updates.+ */+ subscribe: boolean2().optional(),+ /**+ * Whether this server supports issuing notifications for changes to the resource list.+ */+ listChanged: boolean2().optional()+ }).optional(),+ /**+ * Present if the server offers any tools to call.+ */+ tools: object({+ /**+ * Whether this server supports issuing notifications for changes to the tool list.+ */+ listChanged: boolean2().optional()+ }).optional(),+ /**+ * Present if the server supports task creation.+ */+ tasks: ServerTasksCapabilitySchema.optional(),+ /**+ * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).+ */+ extensions: record(string2(), AssertObjectSchema).optional()+});+var InitializeResultSchema = ResultSchema.extend({+ /**+ * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.+ */+ protocolVersion: string2(),+ capabilities: ServerCapabilitiesSchema,+ serverInfo: ImplementationSchema,+ /**+ * Instructions describing how to use the server and its features.+ *+ * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.+ */+ instructions: string2().optional()+});+var InitializedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/initialized"),+ params: NotificationsParamsSchema.optional()+});+var PingRequestSchema = RequestSchema.extend({+ method: literal("ping"),+ params: BaseRequestParamsSchema.optional()+});+var ProgressSchema = object({+ /**+ * The progress thus far. This should increase every time progress is made, even if the total is unknown.+ */+ progress: number2(),+ /**+ * Total number of items to process (or total progress required), if known.+ */+ total: optional(number2()),+ /**+ * An optional message describing the current progress.+ */+ message: optional(string2())+});+var ProgressNotificationParamsSchema = object({+ ...NotificationsParamsSchema.shape,+ ...ProgressSchema.shape,+ /**+ * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.+ */+ progressToken: ProgressTokenSchema+});+var ProgressNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/progress"),+ params: ProgressNotificationParamsSchema+});+var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * An opaque token representing the current pagination position.+ * If provided, the server should return results starting after this cursor.+ */+ cursor: CursorSchema.optional()+});+var PaginatedRequestSchema = RequestSchema.extend({+ params: PaginatedRequestParamsSchema.optional()+});+var PaginatedResultSchema = ResultSchema.extend({+ /**+ * An opaque token representing the pagination position after the last returned result.+ * If present, there may be more results available.+ */+ nextCursor: CursorSchema.optional()+});+var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);+var TaskSchema = object({+ taskId: string2(),+ status: TaskStatusSchema,+ /**+ * Time in milliseconds to keep task results available after completion.+ * If null, the task has unlimited lifetime until manually cleaned up.+ */+ ttl: union([number2(), _null3()]),+ /**+ * ISO 8601 timestamp when the task was created.+ */+ createdAt: string2(),+ /**+ * ISO 8601 timestamp when the task was last updated.+ */+ lastUpdatedAt: string2(),+ pollInterval: optional(number2()),+ /**+ * Optional diagnostic message for failed tasks or other status information.+ */+ statusMessage: optional(string2())+});+var CreateTaskResultSchema = ResultSchema.extend({+ task: TaskSchema+});+var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);+var TaskStatusNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/tasks/status"),+ params: TaskStatusNotificationParamsSchema+});+var GetTaskRequestSchema = RequestSchema.extend({+ method: literal("tasks/get"),+ params: BaseRequestParamsSchema.extend({+ taskId: string2()+ })+});+var GetTaskResultSchema = ResultSchema.merge(TaskSchema);+var GetTaskPayloadRequestSchema = RequestSchema.extend({+ method: literal("tasks/result"),+ params: BaseRequestParamsSchema.extend({+ taskId: string2()+ })+});+var GetTaskPayloadResultSchema = ResultSchema.loose();+var ListTasksRequestSchema = PaginatedRequestSchema.extend({+ method: literal("tasks/list")+});+var ListTasksResultSchema = PaginatedResultSchema.extend({+ tasks: array(TaskSchema)+});+var CancelTaskRequestSchema = RequestSchema.extend({+ method: literal("tasks/cancel"),+ params: BaseRequestParamsSchema.extend({+ taskId: string2()+ })+});+var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);+var ResourceContentsSchema = object({+ /**+ * The URI of this resource.+ */+ uri: string2(),+ /**+ * The MIME type of this resource, if known.+ */+ mimeType: optional(string2()),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var TextResourceContentsSchema = ResourceContentsSchema.extend({+ /**+ * The text of the item. This must only be set if the item can actually be represented as text (not binary data).+ */+ text: string2()+});+var Base64Schema = string2().refine((val) => {+ try {+ atob(val);+ return true;+ } catch {+ return false;+ }+}, { message: "Invalid Base64 string" });+var BlobResourceContentsSchema = ResourceContentsSchema.extend({+ /**+ * A base64-encoded string representing the binary data of the item.+ */+ blob: Base64Schema+});+var RoleSchema = _enum(["user", "assistant"]);+var AnnotationsSchema = object({+ /**+ * Intended audience(s) for the resource.+ */+ audience: array(RoleSchema).optional(),+ /**+ * Importance hint for the resource, from 0 (least) to 1 (most).+ */+ priority: number2().min(0).max(1).optional(),+ /**+ * ISO 8601 timestamp for the most recent modification.+ */+ lastModified: iso_exports.datetime({ offset: true }).optional()+});+var ResourceSchema = object({+ ...BaseMetadataSchema.shape,+ ...IconsSchema.shape,+ /**+ * The URI of this resource.+ */+ uri: string2(),+ /**+ * A description of what this resource represents.+ *+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.+ */+ description: optional(string2()),+ /**+ * The MIME type of this resource, if known.+ */+ mimeType: optional(string2()),+ /**+ * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.+ *+ * This can be used by Hosts to display file sizes and estimate context window usage.+ */+ size: optional(number2()),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: optional(looseObject({}))+});+var ResourceTemplateSchema = object({+ ...BaseMetadataSchema.shape,+ ...IconsSchema.shape,+ /**+ * A URI template (according to RFC 6570) that can be used to construct resource URIs.+ */+ uriTemplate: string2(),+ /**+ * A description of what this template is for.+ *+ * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.+ */+ description: optional(string2()),+ /**+ * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.+ */+ mimeType: optional(string2()),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: optional(looseObject({}))+});+var ListResourcesRequestSchema = PaginatedRequestSchema.extend({+ method: literal("resources/list")+});+var ListResourcesResultSchema = PaginatedResultSchema.extend({+ resources: array(ResourceSchema)+});+var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({+ method: literal("resources/templates/list")+});+var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({+ resourceTemplates: array(ResourceTemplateSchema)+});+var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.+ *+ * @format uri+ */+ uri: string2()+});+var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;+var ReadResourceRequestSchema = RequestSchema.extend({+ method: literal("resources/read"),+ params: ReadResourceRequestParamsSchema+});+var ReadResourceResultSchema = ResultSchema.extend({+ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))+});+var ResourceListChangedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/resources/list_changed"),+ params: NotificationsParamsSchema.optional()+});+var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;+var SubscribeRequestSchema = RequestSchema.extend({+ method: literal("resources/subscribe"),+ params: SubscribeRequestParamsSchema+});+var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;+var UnsubscribeRequestSchema = RequestSchema.extend({+ method: literal("resources/unsubscribe"),+ params: UnsubscribeRequestParamsSchema+});+var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({+ /**+ * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.+ */+ uri: string2()+});+var ResourceUpdatedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/resources/updated"),+ params: ResourceUpdatedNotificationParamsSchema+});+var PromptArgumentSchema = object({+ /**+ * The name of the argument.+ */+ name: string2(),+ /**+ * A human-readable description of the argument.+ */+ description: optional(string2()),+ /**+ * Whether this argument must be provided.+ */+ required: optional(boolean2())+});+var PromptSchema = object({+ ...BaseMetadataSchema.shape,+ ...IconsSchema.shape,+ /**+ * An optional description of what this prompt provides+ */+ description: optional(string2()),+ /**+ * A list of arguments to use for templating the prompt.+ */+ arguments: optional(array(PromptArgumentSchema)),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: optional(looseObject({}))+});+var ListPromptsRequestSchema = PaginatedRequestSchema.extend({+ method: literal("prompts/list")+});+var ListPromptsResultSchema = PaginatedResultSchema.extend({+ prompts: array(PromptSchema)+});+var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * The name of the prompt or prompt template.+ */+ name: string2(),+ /**+ * Arguments to use for templating the prompt.+ */+ arguments: record(string2(), string2()).optional()+});+var GetPromptRequestSchema = RequestSchema.extend({+ method: literal("prompts/get"),+ params: GetPromptRequestParamsSchema+});+var TextContentSchema = object({+ type: literal("text"),+ /**+ * The text content of the message.+ */+ text: string2(),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var ImageContentSchema = object({+ type: literal("image"),+ /**+ * The base64-encoded image data.+ */+ data: Base64Schema,+ /**+ * The MIME type of the image. Different providers may support different image types.+ */+ mimeType: string2(),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var AudioContentSchema = object({+ type: literal("audio"),+ /**+ * The base64-encoded audio data.+ */+ data: Base64Schema,+ /**+ * The MIME type of the audio. Different providers may support different audio types.+ */+ mimeType: string2(),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var ToolUseContentSchema = object({+ type: literal("tool_use"),+ /**+ * The name of the tool to invoke.+ * Must match a tool name from the request's tools array.+ */+ name: string2(),+ /**+ * Unique identifier for this tool call.+ * Used to correlate with ToolResultContent in subsequent messages.+ */+ id: string2(),+ /**+ * Arguments to pass to the tool.+ * Must conform to the tool's inputSchema.+ */+ input: record(string2(), unknown()),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var EmbeddedResourceSchema = object({+ type: literal("resource"),+ resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),+ /**+ * Optional annotations for the client.+ */+ annotations: AnnotationsSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var ResourceLinkSchema = ResourceSchema.extend({+ type: literal("resource_link")+});+var ContentBlockSchema = union([+ TextContentSchema,+ ImageContentSchema,+ AudioContentSchema,+ ResourceLinkSchema,+ EmbeddedResourceSchema+]);+var PromptMessageSchema = object({+ role: RoleSchema,+ content: ContentBlockSchema+});+var GetPromptResultSchema = ResultSchema.extend({+ /**+ * An optional description for the prompt.+ */+ description: string2().optional(),+ messages: array(PromptMessageSchema)+});+var PromptListChangedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/prompts/list_changed"),+ params: NotificationsParamsSchema.optional()+});+var ToolAnnotationsSchema = object({+ /**+ * A human-readable title for the tool.+ */+ title: string2().optional(),+ /**+ * If true, the tool does not modify its environment.+ *+ * Default: false+ */+ readOnlyHint: boolean2().optional(),+ /**+ * If true, the tool may perform destructive updates to its environment.+ * If false, the tool performs only additive updates.+ *+ * (This property is meaningful only when `readOnlyHint == false`)+ *+ * Default: true+ */+ destructiveHint: boolean2().optional(),+ /**+ * If true, calling the tool repeatedly with the same arguments+ * will have no additional effect on the its environment.+ *+ * (This property is meaningful only when `readOnlyHint == false`)+ *+ * Default: false+ */+ idempotentHint: boolean2().optional(),+ /**+ * If true, this tool may interact with an "open world" of external+ * entities. If false, the tool's domain of interaction is closed.+ * For example, the world of a web search tool is open, whereas that+ * of a memory tool is not.+ *+ * Default: true+ */+ openWorldHint: boolean2().optional()+});+var ToolExecutionSchema = object({+ /**+ * Indicates the tool's preference for task-augmented execution.+ * - "required": Clients MUST invoke the tool as a task+ * - "optional": Clients MAY invoke the tool as a task or normal request+ * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task+ *+ * If not present, defaults to "forbidden".+ */+ taskSupport: _enum(["required", "optional", "forbidden"]).optional()+});+var ToolSchema = object({+ ...BaseMetadataSchema.shape,+ ...IconsSchema.shape,+ /**+ * A human-readable description of the tool.+ */+ description: string2().optional(),+ /**+ * A JSON Schema 2020-12 object defining the expected parameters for the tool.+ * Must have type: 'object' at the root level per MCP spec.+ */+ inputSchema: object({+ type: literal("object"),+ properties: record(string2(), AssertObjectSchema).optional(),+ required: array(string2()).optional()+ }).catchall(unknown()),+ /**+ * An optional JSON Schema 2020-12 object defining the structure of the tool's output+ * returned in the structuredContent field of a CallToolResult.+ * Must have type: 'object' at the root level per MCP spec.+ */+ outputSchema: object({+ type: literal("object"),+ properties: record(string2(), AssertObjectSchema).optional(),+ required: array(string2()).optional()+ }).catchall(unknown()).optional(),+ /**+ * Optional additional tool information.+ */+ annotations: ToolAnnotationsSchema.optional(),+ /**+ * Execution-related properties for this tool.+ */+ execution: ToolExecutionSchema.optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var ListToolsRequestSchema = PaginatedRequestSchema.extend({+ method: literal("tools/list")+});+var ListToolsResultSchema = PaginatedResultSchema.extend({+ tools: array(ToolSchema)+});+var CallToolResultSchema = ResultSchema.extend({+ /**+ * A list of content objects that represent the result of the tool call.+ *+ * If the Tool does not define an outputSchema, this field MUST be present in the result.+ * For backwards compatibility, this field is always present, but it may be empty.+ */+ content: array(ContentBlockSchema).default([]),+ /**+ * An object containing structured tool output.+ *+ * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.+ */+ structuredContent: record(string2(), unknown()).optional(),+ /**+ * Whether the tool call ended in an error.+ *+ * If not set, this is assumed to be false (the call was successful).+ *+ * Any errors that originate from the tool SHOULD be reported inside the result+ * object, with `isError` set to true, _not_ as an MCP protocol-level error+ * response. Otherwise, the LLM would not be able to see that an error occurred+ * and self-correct.+ *+ * However, any errors in _finding_ the tool, an error indicating that the+ * server does not support tool calls, or any other exceptional conditions,+ * should be reported as an MCP error response.+ */+ isError: boolean2().optional()+});+var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({+ toolResult: unknown()+}));+var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({+ /**+ * The name of the tool to call.+ */+ name: string2(),+ /**+ * Arguments to pass to the tool.+ */+ arguments: record(string2(), unknown()).optional()+});+var CallToolRequestSchema = RequestSchema.extend({+ method: literal("tools/call"),+ params: CallToolRequestParamsSchema+});+var ToolListChangedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/tools/list_changed"),+ params: NotificationsParamsSchema.optional()+});+var ListChangedOptionsBaseSchema = object({+ /**+ * If true, the list will be refreshed automatically when a list changed notification is received.+ * The callback will be called with the updated list.+ *+ * If false, the callback will be called with null items, allowing manual refresh.+ *+ * @default true+ */+ autoRefresh: boolean2().default(true),+ /**+ * Debounce time in milliseconds for list changed notification processing.+ *+ * Multiple notifications received within this timeframe will only trigger one refresh.+ * Set to 0 to disable debouncing.+ *+ * @default 300+ */+ debounceMs: number2().int().nonnegative().default(300)+});+var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);+var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({+ /**+ * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.+ */+ level: LoggingLevelSchema+});+var SetLevelRequestSchema = RequestSchema.extend({+ method: literal("logging/setLevel"),+ params: SetLevelRequestParamsSchema+});+var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({+ /**+ * The severity of this log message.+ */+ level: LoggingLevelSchema,+ /**+ * An optional name of the logger issuing this message.+ */+ logger: string2().optional(),+ /**+ * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.+ */+ data: unknown()+});+var LoggingMessageNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/message"),+ params: LoggingMessageNotificationParamsSchema+});+var ModelHintSchema = object({+ /**+ * A hint for a model name.+ */+ name: string2().optional()+});+var ModelPreferencesSchema = object({+ /**+ * Optional hints to use for model selection.+ */+ hints: array(ModelHintSchema).optional(),+ /**+ * How much to prioritize cost when selecting a model.+ */+ costPriority: number2().min(0).max(1).optional(),+ /**+ * How much to prioritize sampling speed (latency) when selecting a model.+ */+ speedPriority: number2().min(0).max(1).optional(),+ /**+ * How much to prioritize intelligence and capabilities when selecting a model.+ */+ intelligencePriority: number2().min(0).max(1).optional()+});+var ToolChoiceSchema = object({+ /**+ * Controls when tools are used:+ * - "auto": Model decides whether to use tools (default)+ * - "required": Model MUST use at least one tool before completing+ * - "none": Model MUST NOT use any tools+ */+ mode: _enum(["auto", "required", "none"]).optional()+});+var ToolResultContentSchema = object({+ type: literal("tool_result"),+ toolUseId: string2().describe("The unique identifier for the corresponding tool call."),+ content: array(ContentBlockSchema).default([]),+ structuredContent: object({}).loose().optional(),+ isError: boolean2().optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);+var SamplingMessageContentBlockSchema = discriminatedUnion("type", [+ TextContentSchema,+ ImageContentSchema,+ AudioContentSchema,+ ToolUseContentSchema,+ ToolResultContentSchema+]);+var SamplingMessageSchema = object({+ role: RoleSchema,+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({+ messages: array(SamplingMessageSchema),+ /**+ * The server's preferences for which model to select. The client MAY modify or omit this request.+ */+ modelPreferences: ModelPreferencesSchema.optional(),+ /**+ * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.+ */+ systemPrompt: string2().optional(),+ /**+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.+ * The client MAY ignore this request.+ *+ * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client+ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.+ */+ includeContext: _enum(["none", "thisServer", "allServers"]).optional(),+ temperature: number2().optional(),+ /**+ * The requested maximum number of tokens to sample (to prevent runaway completions).+ *+ * The client MAY choose to sample fewer tokens than the requested maximum.+ */+ maxTokens: number2().int(),+ stopSequences: array(string2()).optional(),+ /**+ * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.+ */+ metadata: AssertObjectSchema.optional(),+ /**+ * Tools that the model may use during generation.+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.+ */+ tools: array(ToolSchema).optional(),+ /**+ * Controls how the model uses tools.+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.+ * Default is `{ mode: "auto" }`.+ */+ toolChoice: ToolChoiceSchema.optional()+});+var CreateMessageRequestSchema = RequestSchema.extend({+ method: literal("sampling/createMessage"),+ params: CreateMessageRequestParamsSchema+});+var CreateMessageResultSchema = ResultSchema.extend({+ /**+ * The name of the model that generated the message.+ */+ model: string2(),+ /**+ * The reason why sampling stopped, if known.+ *+ * Standard values:+ * - "endTurn": Natural end of the assistant's turn+ * - "stopSequence": A stop sequence was encountered+ * - "maxTokens": Maximum token limit was reached+ *+ * This field is an open string to allow for provider-specific stop reasons.+ */+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())),+ role: RoleSchema,+ /**+ * Response content. Single content block (text, image, or audio).+ */+ content: SamplingContentSchema+});+var CreateMessageResultWithToolsSchema = ResultSchema.extend({+ /**+ * The name of the model that generated the message.+ */+ model: string2(),+ /**+ * The reason why sampling stopped, if known.+ *+ * Standard values:+ * - "endTurn": Natural end of the assistant's turn+ * - "stopSequence": A stop sequence was encountered+ * - "maxTokens": Maximum token limit was reached+ * - "toolUse": The model wants to use one or more tools+ *+ * This field is an open string to allow for provider-specific stop reasons.+ */+ stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),+ role: RoleSchema,+ /**+ * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".+ */+ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])+});+var BooleanSchemaSchema = object({+ type: literal("boolean"),+ title: string2().optional(),+ description: string2().optional(),+ default: boolean2().optional()+});+var StringSchemaSchema = object({+ type: literal("string"),+ title: string2().optional(),+ description: string2().optional(),+ minLength: number2().optional(),+ maxLength: number2().optional(),+ format: _enum(["email", "uri", "date", "date-time"]).optional(),+ default: string2().optional()+});+var NumberSchemaSchema = object({+ type: _enum(["number", "integer"]),+ title: string2().optional(),+ description: string2().optional(),+ minimum: number2().optional(),+ maximum: number2().optional(),+ default: number2().optional()+});+var UntitledSingleSelectEnumSchemaSchema = object({+ type: literal("string"),+ title: string2().optional(),+ description: string2().optional(),+ enum: array(string2()),+ default: string2().optional()+});+var TitledSingleSelectEnumSchemaSchema = object({+ type: literal("string"),+ title: string2().optional(),+ description: string2().optional(),+ oneOf: array(object({+ const: string2(),+ title: string2()+ })),+ default: string2().optional()+});+var LegacyTitledEnumSchemaSchema = object({+ type: literal("string"),+ title: string2().optional(),+ description: string2().optional(),+ enum: array(string2()),+ enumNames: array(string2()).optional(),+ default: string2().optional()+});+var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);+var UntitledMultiSelectEnumSchemaSchema = object({+ type: literal("array"),+ title: string2().optional(),+ description: string2().optional(),+ minItems: number2().optional(),+ maxItems: number2().optional(),+ items: object({+ type: literal("string"),+ enum: array(string2())+ }),+ default: array(string2()).optional()+});+var TitledMultiSelectEnumSchemaSchema = object({+ type: literal("array"),+ title: string2().optional(),+ description: string2().optional(),+ minItems: number2().optional(),+ maxItems: number2().optional(),+ items: object({+ anyOf: array(object({+ const: string2(),+ title: string2()+ }))+ }),+ default: array(string2()).optional()+});+var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);+var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);+var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);+var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({+ /**+ * The elicitation mode.+ *+ * Optional for backward compatibility. Clients MUST treat missing mode as "form".+ */+ mode: literal("form").optional(),+ /**+ * The message to present to the user describing what information is being requested.+ */+ message: string2(),+ /**+ * A restricted subset of JSON Schema.+ * Only top-level properties are allowed, without nesting.+ */+ requestedSchema: object({+ type: literal("object"),+ properties: record(string2(), PrimitiveSchemaDefinitionSchema),+ required: array(string2()).optional()+ })+});+var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({+ /**+ * The elicitation mode.+ */+ mode: literal("url"),+ /**+ * The message to present to the user explaining why the interaction is needed.+ */+ message: string2(),+ /**+ * The ID of the elicitation, which must be unique within the context of the server.+ * The client MUST treat this ID as an opaque value.+ */+ elicitationId: string2(),+ /**+ * The URL that the user should navigate to.+ */+ url: string2().url()+});+var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);+var ElicitRequestSchema = RequestSchema.extend({+ method: literal("elicitation/create"),+ params: ElicitRequestParamsSchema+});+var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({+ /**+ * The ID of the elicitation that completed.+ */+ elicitationId: string2()+});+var ElicitationCompleteNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/elicitation/complete"),+ params: ElicitationCompleteNotificationParamsSchema+});+var ElicitResultSchema = ResultSchema.extend({+ /**+ * The user action in response to the elicitation.+ * - "accept": User submitted the form/confirmed the action+ * - "decline": User explicitly decline the action+ * - "cancel": User dismissed without making an explicit choice+ */+ action: _enum(["accept", "decline", "cancel"]),+ /**+ * The submitted form data, only present when action is "accept".+ * Contains values matching the requested schema.+ * Per MCP spec, content is "typically omitted" for decline/cancel actions.+ * We normalize null to undefined for leniency while maintaining type compatibility.+ */+ content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())+});+var ResourceTemplateReferenceSchema = object({+ type: literal("ref/resource"),+ /**+ * The URI or URI template of the resource.+ */+ uri: string2()+});+var PromptReferenceSchema = object({+ type: literal("ref/prompt"),+ /**+ * The name of the prompt or prompt template+ */+ name: string2()+});+var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({+ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),+ /**+ * The argument's information+ */+ argument: object({+ /**+ * The name of the argument+ */+ name: string2(),+ /**+ * The value of the argument to use for completion matching.+ */+ value: string2()+ }),+ context: object({+ /**+ * Previously-resolved variables in a URI template or prompt.+ */+ arguments: record(string2(), string2()).optional()+ }).optional()+});+var CompleteRequestSchema = RequestSchema.extend({+ method: literal("completion/complete"),+ params: CompleteRequestParamsSchema+});+function assertCompleteRequestPrompt(request) {+ if (request.params.ref.type !== "ref/prompt") {+ throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);+ }+}+function assertCompleteRequestResourceTemplate(request) {+ if (request.params.ref.type !== "ref/resource") {+ throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);+ }+}+var CompleteResultSchema = ResultSchema.extend({+ completion: looseObject({+ /**+ * An array of completion values. Must not exceed 100 items.+ */+ values: array(string2()).max(100),+ /**+ * The total number of completion options available. This can exceed the number of values actually sent in the response.+ */+ total: optional(number2().int()),+ /**+ * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.+ */+ hasMore: optional(boolean2())+ })+});+var RootSchema = object({+ /**+ * The URI identifying the root. This *must* start with file:// for now.+ */+ uri: string2().startsWith("file://"),+ /**+ * An optional name for the root.+ */+ name: string2().optional(),+ /**+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)+ * for notes on _meta usage.+ */+ _meta: record(string2(), unknown()).optional()+});+var ListRootsRequestSchema = RequestSchema.extend({+ method: literal("roots/list"),+ params: BaseRequestParamsSchema.optional()+});+var ListRootsResultSchema = ResultSchema.extend({+ roots: array(RootSchema)+});+var RootsListChangedNotificationSchema = NotificationSchema.extend({+ method: literal("notifications/roots/list_changed"),+ params: NotificationsParamsSchema.optional()+});+var ClientRequestSchema = union([+ PingRequestSchema,+ InitializeRequestSchema,+ CompleteRequestSchema,+ SetLevelRequestSchema,+ GetPromptRequestSchema,+ ListPromptsRequestSchema,+ ListResourcesRequestSchema,+ ListResourceTemplatesRequestSchema,+ ReadResourceRequestSchema,+ SubscribeRequestSchema,+ UnsubscribeRequestSchema,+ CallToolRequestSchema,+ ListToolsRequestSchema,+ GetTaskRequestSchema,+ GetTaskPayloadRequestSchema,+ ListTasksRequestSchema,+ CancelTaskRequestSchema+]);+var ClientNotificationSchema = union([+ CancelledNotificationSchema,+ ProgressNotificationSchema,+ InitializedNotificationSchema,+ RootsListChangedNotificationSchema,+ TaskStatusNotificationSchema+]);+var ClientResultSchema = union([+ EmptyResultSchema,+ CreateMessageResultSchema,+ CreateMessageResultWithToolsSchema,+ ElicitResultSchema,+ ListRootsResultSchema,+ GetTaskResultSchema,+ ListTasksResultSchema,+ CreateTaskResultSchema+]);+var ServerRequestSchema = union([+ PingRequestSchema,+ CreateMessageRequestSchema,+ ElicitRequestSchema,+ ListRootsRequestSchema,+ GetTaskRequestSchema,+ GetTaskPayloadRequestSchema,+ ListTasksRequestSchema,+ CancelTaskRequestSchema+]);+var ServerNotificationSchema = union([+ CancelledNotificationSchema,+ ProgressNotificationSchema,+ LoggingMessageNotificationSchema,+ ResourceUpdatedNotificationSchema,+ ResourceListChangedNotificationSchema,+ ToolListChangedNotificationSchema,+ PromptListChangedNotificationSchema,+ TaskStatusNotificationSchema,+ ElicitationCompleteNotificationSchema+]);+var ServerResultSchema = union([+ EmptyResultSchema,+ InitializeResultSchema,+ CompleteResultSchema,+ GetPromptResultSchema,+ ListPromptsResultSchema,+ ListResourcesResultSchema,+ ListResourceTemplatesResultSchema,+ ReadResourceResultSchema,+ CallToolResultSchema,+ ListToolsResultSchema,+ GetTaskResultSchema,+ ListTasksResultSchema,+ CreateTaskResultSchema+]);+var McpError = class _McpError extends Error {+ constructor(code, message, data) {+ super(`MCP error ${code}: ${message}`);+ this.code = code;+ this.data = data;+ this.name = "McpError";+ }+ /**+ * Factory method to create the appropriate error type based on the error code and data+ */+ static fromError(code, message, data) {+ if (code === ErrorCode.UrlElicitationRequired && data) {+ const errorData = data;+ if (errorData.elicitations) {+ return new UrlElicitationRequiredError(errorData.elicitations, message);+ }+ }+ return new _McpError(code, message, data);+ }+};+var UrlElicitationRequiredError = class extends McpError {+ constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {+ super(ErrorCode.UrlElicitationRequired, message, {+ elicitations+ });+ }+ get elicitations() {+ return this.data?.elicitations ?? [];+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js+var ReadBuffer = class {+ append(chunk) {+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;+ }+ readMessage() {+ if (!this._buffer) {+ return null;+ }+ const index = this._buffer.indexOf("\n");+ if (index === -1) {+ return null;+ }+ const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");+ this._buffer = this._buffer.subarray(index + 1);+ return deserializeMessage(line);+ }+ clear() {+ this._buffer = void 0;+ }+};+function deserializeMessage(line) {+ return JSONRPCMessageSchema.parse(JSON.parse(line));+}+function serializeMessage(message) {+ return JSON.stringify(message) + "\n";+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js+var StdioServerTransport = class {+ constructor(_stdin = process2.stdin, _stdout = process2.stdout) {+ this._stdin = _stdin;+ this._stdout = _stdout;+ this._readBuffer = new ReadBuffer();+ this._started = false;+ this._ondata = (chunk) => {+ this._readBuffer.append(chunk);+ this.processReadBuffer();+ };+ this._onerror = (error2) => {+ this.onerror?.(error2);+ };+ }+ /**+ * Starts listening for messages on stdin.+ */+ async start() {+ if (this._started) {+ throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");+ }+ this._started = true;+ this._stdin.on("data", this._ondata);+ this._stdin.on("error", this._onerror);+ }+ processReadBuffer() {+ while (true) {+ try {+ const message = this._readBuffer.readMessage();+ if (message === null) {+ break;+ }+ this.onmessage?.(message);+ } catch (error2) {+ this.onerror?.(error2);+ }+ }+ }+ async close() {+ this._stdin.off("data", this._ondata);+ this._stdin.off("error", this._onerror);+ const remainingDataListeners = this._stdin.listenerCount("data");+ if (remainingDataListeners === 0) {+ this._stdin.pause();+ }+ this._readBuffer.clear();+ this.onclose?.();+ }+ send(message) {+ return new Promise((resolve2) => {+ const json = serializeMessage(message);+ if (this._stdout.write(json)) {+ resolve2();+ } else {+ this._stdout.once("drain", resolve2);+ }+ });+ }+};++// packages/core/dist/api/flow-client.js+init_logger();++// packages/core/dist/utils/errors.js+var FlowApiError = class extends Error {+ statusCode;+ statusText;+ body;+ url;+ constructor(statusCode, statusText, body, url) {+ super(`Flow API ${statusCode} ${statusText}: ${body}`);+ this.statusCode = statusCode;+ this.statusText = statusText;+ this.body = body;+ this.url = url;+ this.name = "FlowApiError";+ }+};+var ManagedSolutionError = class extends Error {+ operation;+ flowId;+ solutionUniqueName;+ solutionFriendlyName;+ remediation;+ code = "ManagedSolutionReadOnly";+ constructor(operation, flowId, solutionUniqueName, solutionFriendlyName, remediation = "Create an unmanaged solution layer or fork the flow into a new unmanaged solution. Pass forceManaged: true (CLI: --force-managed) only if you understand that your change will be overwritten on the next solution import.") {+ const solRef = solutionUniqueName ?? "unknown solution";+ super(`Refusing ${operation} on flow ${flowId}: it belongs to managed solution "${solRef}" and is read-only. ${remediation}`);+ this.operation = operation;+ this.flowId = flowId;+ this.solutionUniqueName = solutionUniqueName;+ this.solutionFriendlyName = solutionFriendlyName;+ this.remediation = remediation;+ this.name = "ManagedSolutionError";+ }+};+var DuplicateFlowError = class extends Error {+ displayName;+ environmentId;+ existingFlowId;+ existingFlowState;+ remediation;+ code = "DuplicateFlowName";+ constructor(displayName, environmentId, existingFlowId, existingFlowState, remediation = "A flow with this displayName already exists in the target environment. Use update_flow against the existing flow ID instead of creating a duplicate. Pass allowDuplicate: true (CLI: --allow-duplicate) only if you actually want a second flow with the same name.") {+ super(`Refusing create_flow: a flow named "${displayName}" already exists in environment ${environmentId} (existingFlowId=${existingFlowId}). ${remediation}`);+ this.displayName = displayName;+ this.environmentId = environmentId;+ this.existingFlowId = existingFlowId;+ this.existingFlowState = existingFlowState;+ this.remediation = remediation;+ this.name = "DuplicateFlowError";+ }+};+var PreviewTokenError = class extends Error {+ remediation;+ code;+ constructor(code, detail, remediation = "Call preview_update with the proposed definition to obtain a fresh token, review the returned diff, then call update_flow with the new token. Tokens are single-use and bound to the exact envId+flowId+proposal hash they were issued for.") {+ super(`${code}${detail ? ": " + detail : ""}. ${remediation}`);+ this.remediation = remediation;+ this.code = code;+ this.name = "PreviewTokenError";+ }+};++// packages/core/dist/utils/odata.js+function escapeODataString(s) {+ return s.replace(/'/g, "''");+}++// packages/core/dist/api/endpoints.js+var API_VERSION = "2016-11-01";+function qs(params) {+ const entries = Object.entries(params).filter((pair) => pair[1] !== void 0);+ entries.push(["api-version", API_VERSION]);+ return "?" + new URLSearchParams(entries).toString();+}+function environmentsUrl(baseUrl) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/environments${qs({})}`;+}+function environmentUrl(baseUrl, envId) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/environments/${envId}${qs({})}`;+}+function connQs(extra) {+ const params = { "api-version": PPAPI_API_VERSION };+ if (extra) {+ for (const [k, v] of Object.entries(extra)) {+ if (v !== void 0)+ params[k] = v;+ }+ }+ return "?" + new URLSearchParams(params).toString();+}+function ppapiConnectionsUrl(envId, opts) {+ const base = ppapiBaseUrl(envId);+ if (opts?.connector) {+ return `${base}/connectivity/connectors/${opts.connector}/connections${connQs()}`;+ }+ return `${base}/connectivity/connections${connQs()}`;+}+function ppapiConnectionUrl(envId, connector, connName) {+ const base = ppapiBaseUrl(envId);+ return `${base}/connectivity/connectors/${connector}/connections/${connName}${connQs({ "$filter": `environment eq '${envId}'` })}`;+}+function ppapiConnectionConsentUrl(envId, connector, connName) {+ const base = ppapiBaseUrl(envId);+ return `${base}/connectivity/connectors/${connector}/connections/${connName}/getConsentLink${connQs({ "$filter": `environment eq '${envId}'` })}`;+}+function ppapiConnectionPermissionsUrl(envId, connector, connName) {+ const base = ppapiBaseUrl(envId);+ return `${base}/connectivity/connectors/${connector}/connections/${connName}/permissions${connQs({ "$filter": `environment eq '${envId}'` })}`;+}+function ppapiConnectionModifyPermissionsUrl(envId, connector, connName) {+ const base = ppapiBaseUrl(envId);+ return `${base}/connectivity/connectors/${connector}/connections/${connName}/modifyPermissions${connQs({ "$filter": `environment eq '${envId}'` })}`;+}+function dataverseConnectionReferencesUrl(instanceUrl, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "connectionid,connectorid,connectionreferencedisplayname,connectionreferencelogicalname,statecode";+ let filter = "statecode eq 0";+ if (opts?.connectorFilter) {+ filter += ` and connectorid eq '/providers/Microsoft.PowerApps/apis/${escapeODataString(opts.connectorFilter)}'`;+ }+ return `${base}/api/data/v9.2/connectionreferences?$select=${select}&$filter=${encodeURIComponent(filter)}`;+}+var PPAPI_API_VERSION = "1";+var PPAPI_DEFAULT_SUFFIX = "environment.api.powerplatform.com";+function ppapiBaseUrl(envId, templateOverride) {+ const hex = envId.replace(/-/g, "");+ const prefix = hex.slice(0, 30);+ const shard = hex.slice(30, 32);+ const template = templateOverride ?? process.env.PA_PPAPI_BASE_URL;+ if (template) {+ return template.replace(/\{prefix\}/g, prefix).replace(/\{shard\}/g, shard).replace(/\{envId\}/g, envId).replace(/\{hex\}/g, hex);+ }+ const suffix = process.env.PA_PPAPI_SUFFIX ?? PPAPI_DEFAULT_SUFFIX;+ return `https://${prefix}.${shard}.${suffix}`;+}+function ppapiQs(extra) {+ const params = {+ "api-version": PPAPI_API_VERSION,+ addConnectorHideKey: "M365Copilot"+ };+ if (extra) {+ for (const [k, v] of Object.entries(extra)) {+ if (v !== void 0)+ params[k] = v;+ }+ }+ return "?" + new URLSearchParams(params).toString();+}+function ppapiSearchOperationsUrl(base) {+ return `${base}/powerautomate/operations${ppapiQs()}`;+}+function ppapiOperationSchemaUrl(base, connector, operation) {+ return `${base}/powerautomate/apis/${connector}/apiOperations/${operation}${ppapiQs({+ $expand: "properties/inputsDefinition,properties/responsesDefinition,properties/connector"+ })}`;+}+function ppapiListEnumUrl(base, connector, connection) {+ return `${base}/powerautomate/apis/${connector}/connections/${connection}/listEnum${ppapiQs()}`;+}+function ppapiListTreeUrl(base, connector, connection) {+ return `${base}/powerautomate/apis/${connector}/connections/${connection}/listTree${ppapiQs()}`;+}+function ppapiListDynamicPropertiesUrl(base, connector, connection) {+ return `${base}/powerautomate/apis/${connector}/connections/${connection}/listDynamicProperties${ppapiQs()}`;+}+function ppapiFlowQs(extra) {+ const params = { "api-version": PPAPI_API_VERSION };+ if (extra) {+ for (const [k, v] of Object.entries(extra)) {+ if (v !== void 0)+ params[k] = v;+ }+ }+ return "?" + new URLSearchParams(params).toString();+}+function ppapiConnectorUrl(envId, connectorName, opts) {+ const base = ppapiBaseUrl(envId);+ return `${base}/powerautomate/apis/${connectorName}${ppapiFlowQs({+ $expand: opts?.expand+ })}`;+}+function dataverseFlowSessionsUrl(instanceUrl, flowId, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const top = opts?.top ?? 25;+ const params = new URLSearchParams({+ $select: "flowsessionid,name,statuscode,createdon,completedon,context,outputs,errordetails,startedon,regardingobjectid",+ $filter: `_regardingobjectid_value eq '${flowId}'`,+ $orderby: "createdon desc",+ $top: top.toString()+ });+ return `${base}/api/data/v9.2/flowsessions?${params.toString()}`;+}+function dataverseDesktopFlowsUrl(instanceUrl, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const top = opts?.top ?? 50;+ const select = "workflowid,name,statecode,statuscode,createdon,modifiedon,description,ownerid";+ let filter = "category eq 6";+ if (opts?.nameFilter) {+ filter += ` and contains(name,'${escapeODataString(opts.nameFilter)}')`;+ }+ const params = new URLSearchParams({+ $select: select,+ $filter: filter,+ $orderby: "modifiedon desc",+ $top: top.toString()+ });+ return `${base}/api/data/v9.2/workflows?${params.toString()}`;+}+function dataverseTriggerDesktopFlowUrl(instanceUrl) {+ const base = instanceUrl.replace(/\/+$/, "");+ return `${base}/api/data/v9.2/flowsessions`;+}+function dataverseDesktopFlowSessionUrl(instanceUrl, sessionId) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "flowsessionid,name,statuscode,statecode,createdon,completedon,startedon,outputs,errordetails,errormessage";+ return `${base}/api/data/v9.2/flowsessions(${sessionId})?$select=${select}`;+}+function dataverseMachineGroupsUrl(instanceUrl, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "flowmachinegroupid,name,description,grouptype,statecode";+ let filter = "statecode eq 0";+ if (opts?.nameFilter) {+ filter += ` and name eq '${escapeODataString(opts.nameFilter)}'`;+ }+ const params = new URLSearchParams({+ $select: select,+ $filter: filter,+ $top: (opts?.top ?? 50).toString()+ });+ return `${base}/api/data/v9.2/flowmachinegroups?${params.toString()}`;+}+function dataverseMachinesUrl(instanceUrl, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "flowmachineid,name,description,flowmachinegroupid,statecode,connectivitystate";+ let filter = "statecode eq 0";+ if (opts?.groupId) {+ filter += ` and _flowmachinegroupid_value eq '${opts.groupId}'`;+ }+ const params = new URLSearchParams({+ $select: select,+ $filter: filter,+ $top: (opts?.top ?? 50).toString()+ });+ return `${base}/api/data/v9.2/flowmachines?${params.toString()}`;+}+function adminFlowsUrl(baseUrl, envId, opts) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/${envId}/v2/flows${qs({+ $top: opts?.top?.toString(),+ $filter: opts?.filter+ })}`;+}+function adminFlowUrl(baseUrl, envId, flowId) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/${envId}/flows/${flowId}${qs({})}`;+}+function adminFlowRestoreUrl(baseUrl, envId, flowId) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/${envId}/flows/${flowId}/restore${qs({})}`;+}+function adminFlowPermissionsUrl(baseUrl, envId, flowId) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/${envId}/flows/${flowId}/permissions${qs({})}`;+}+function adminFlowModifyPermissionsUrl(baseUrl, envId, flowId) {+ return `${baseUrl}/providers/Microsoft.ProcessSimple/scopes/admin/environments/${envId}/flows/${flowId}/modifyPermissions${qs({})}`;+}+function dataverseWorkflowUrl(instanceUrl, flowId) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = [+ "workflowid",+ "workflowidunique",+ "name",+ "category",+ "statecode",+ "statuscode",+ "ismanaged",+ "iscustomizable",+ "description",+ "_ownerid_value",+ "solutionid",+ "modifiedon",+ "createdon"+ ].join(",");+ return `${base}/api/data/v9.2/workflows(${flowId})?$select=${select}`;+}+function dataverseWorkflowByUniqueUrl(instanceUrl, workflowIdUnique) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = [+ "workflowid",+ "workflowidunique",+ "name",+ "category",+ "statecode",+ "ismanaged",+ "iscustomizable",+ "solutionid",+ "_ownerid_value"+ ].join(",");+ const filter = `workflowidunique eq ${workflowIdUnique}`;+ const params = new URLSearchParams({ $select: select, $filter: filter, $top: "1" });+ return `${base}/api/data/v9.2/workflows?${params.toString()}`;+}+function dataverseSolutionByIdUrl(instanceUrl, solutionId) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "solutionid,uniquename,friendlyname,version,ismanaged,description";+ return `${base}/api/data/v9.2/solutions(${solutionId})?$select=${select}`;+}+function dataverseSolutionsUrl(instanceUrl, opts) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "solutionid,uniquename,friendlyname,version,ismanaged,createdon,modifiedon,description";+ let filter = opts?.filter ?? "ismanaged eq false";+ const params = new URLSearchParams({+ $select: select,+ $filter: filter,+ $orderby: "modifiedon desc"+ });+ return `${base}/api/data/v9.2/solutions?${params.toString()}`;+}+function dataverseSolutionFlowsUrl(instanceUrl, solutionId) {+ const base = instanceUrl.replace(/\/+$/, "");+ const select = "workflowid,name,statecode,statuscode,category,createdon,modifiedon,description";+ const filter = `solutionid eq '${solutionId}' and category eq 5`;+ const params = new URLSearchParams({+ $select: select,+ $filter: filter,+ $orderby: "modifiedon desc"+ });+ return `${base}/api/data/v9.2/workflows?${params.toString()}`;+}+function dataverseExportSolutionUrl(instanceUrl) {+ const base = instanceUrl.replace(/\/+$/, "");+ return `${base}/api/data/v9.2/ExportSolution`;+}+function dataverseImportSolutionUrl(instanceUrl) {+ const base = instanceUrl.replace(/\/+$/, "");+ return `${base}/api/data/v9.2/ImportSolution`;+}+var GOVERNANCE_API_VERSION = "1";+var GOVERNANCE_BASE = "https://api.powerplatform.com";+var BAP_BASE = "https://api.bap.microsoft.com";+function governanceBaseUrl() {+ return process.env.PA_GOVERNANCE_BASE ?? GOVERNANCE_BASE;+}+function governanceUserRoutingUrl() {+ const base = governanceBaseUrl();+ return `${base}/governance/userRoutingEnvironment?api-version=${GOVERNANCE_API_VERSION}`;+}+function governanceRoutingStatusUrl(operationId) {+ const base = governanceBaseUrl();+ return `${base}/governance/environmentRoutingOperationStatus/${operationId}?api-version=${GOVERNANCE_API_VERSION}`;+}+function bapDefaultEnvironmentUrl() {+ return `${BAP_BASE}/providers/Microsoft.BusinessAppPlatform/environments/~default?api-version=2021-04-01`;+}+function graphUsersSearchUrl(query, top = 10) {+ const escaped = query.replace(/["']/g, "\\$&");+ const searchFilter = `"displayName:${escaped}" OR "mail:${escaped}"`;+ const select = "id,displayName,mail,userPrincipalName,jobTitle,department";+ const clampedTop = Math.max(1, Math.min(top, 100));+ const params = new URLSearchParams({+ $search: searchFilter,+ $select: select,+ $top: clampedTop.toString()+ });+ return `https://graph.microsoft.com/v1.0/users?${params.toString()}`;+}++// packages/core/dist/api/flow-client.js+init_backups();++// packages/core/dist/api/pagination.js+init_logger();+var DEFAULT_MAX_PAGES = 5;+async function followPagination(fetchPage, maxPages = DEFAULT_MAX_PAGES) {+ const allItems = [];+ let response = await fetchPage();+ allItems.push(...response.value);+ let page = 1;+ while (response.nextLink && page < maxPages) {+ logger.debug(`Following pagination page ${page + 1}`);+ response = await fetchPage(response.nextLink);+ allItems.push(...response.value);+ page++;+ }+ if (response.nextLink) {+ logger.debug(`Stopped pagination after ${maxPages} pages, more data available`);+ }+ return allItems;+}++// packages/core/dist/api/flow-diff.js+function jsonEqual(a, b) {+ if (a === b)+ return true;+ if (a === void 0 || b === void 0)+ return false;+ try {+ return JSON.stringify(a) === JSON.stringify(b);+ } catch {+ return false;+ }+}+function changedFields(a, b) {+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);+ const out = [];+ for (const k of keys) {+ if (!jsonEqual(a[k], b[k]))+ out.push(k);+ }+ return out.sort();+}+function actionType(a) {+ if (a && typeof a === "object" && "type" in a) {+ const t = a.type;+ return typeof t === "string" ? t : void 0;+ }+ return void 0;+}+function diffActions(current, proposed) {+ const cur = current ?? {};+ const prop = proposed ?? {};+ const curNames = new Set(Object.keys(cur));+ const propNames = new Set(Object.keys(prop));+ const added = [];+ const removed = [];+ const changed = [];+ let unchanged = 0;+ for (const name3 of propNames) {+ if (!curNames.has(name3)) {+ added.push({ name: name3, type: actionType(prop[name3]) });+ } else if (!jsonEqual(cur[name3], prop[name3])) {+ const fields = changedFields(cur[name3], prop[name3]);+ changed.push({+ name: name3,+ type: actionType(prop[name3]) ?? actionType(cur[name3]),+ fields+ });+ } else {+ unchanged++;+ }+ }+ for (const name3 of curNames) {+ if (!propNames.has(name3)) {+ removed.push({ name: name3, type: actionType(cur[name3]) });+ }+ }+ added.sort((a, b) => a.name.localeCompare(b.name));+ removed.sort((a, b) => a.name.localeCompare(b.name));+ changed.sort((a, b) => a.name.localeCompare(b.name));+ return { added, removed, changed, unchanged };+}+function diffTriggers(current, proposed) {+ const cur = current ?? {};+ const prop = proposed ?? {};+ const curNames = new Set(Object.keys(cur));+ const propNames = new Set(Object.keys(prop));+ const added = [];+ const removed = [];+ const changed_keys = [];+ for (const name3 of propNames) {+ if (!curNames.has(name3))+ added.push(name3);+ else if (!jsonEqual(cur[name3], prop[name3])) {+ changed_keys.push({+ name: name3,+ fields: changedFields(cur[name3], prop[name3])+ });+ }+ }+ for (const name3 of curNames) {+ if (!propNames.has(name3))+ removed.push(name3);+ }+ const changed = added.length > 0 || removed.length > 0 || changed_keys.length > 0;+ return { changed, added: added.sort(), removed: removed.sort(), changed_keys };+}+function diffConnectionRefs(current, proposed) {+ const cur = current ?? {};+ const prop = proposed ?? {};+ const curNames = new Set(Object.keys(cur));+ const propNames = new Set(Object.keys(prop));+ const added = [];+ const removed = [];+ const changed = [];+ for (const name3 of propNames) {+ if (!curNames.has(name3))+ added.push(name3);+ else if (!jsonEqual(cur[name3], prop[name3])) {+ changed.push({+ name: name3,+ fields: changedFields(cur[name3], prop[name3])+ });+ }+ }+ for (const name3 of curNames) {+ if (!propNames.has(name3))+ removed.push(name3);+ }+ return { added: added.sort(), removed: removed.sort(), changed };+}+function diffProperties(current, proposed) {+ const out = {};+ if (proposed.displayName !== void 0 && proposed.displayName !== current.displayName) {+ out.name = { from: current.displayName, to: proposed.displayName };+ }+ if (proposed.state !== void 0 && proposed.state !== current.state) {+ out.state = { from: current.state, to: proposed.state };+ }+ return out;+}+function buildSummary(d) {+ const parts = [];+ const a = d.actions;+ parts.push(`actions: +${a.added.length} \u2212${a.removed.length} ~${a.changed.length} (${a.unchanged} unchanged)`);+ if (d.trigger.changed) {+ parts.push(`trigger changed`);+ } else {+ parts.push(`trigger unchanged`);+ }+ const c = d.connectionReferences;+ if (c.added.length || c.removed.length || c.changed.length) {+ parts.push(`refs: +${c.added.length} \u2212${c.removed.length} ~${c.changed.length}`);+ }+ if (d.properties.name)+ parts.push(`renamed \u2192 "${d.properties.name.to}"`);+ if (d.properties.state)+ parts.push(`state ${d.properties.state.from} \u2192 ${d.properties.state.to}`);+ return parts.join("; ");+}+function diffFlow(current, proposed) {+ const curDef = current.definition ?? {};+ const propDef = proposed.definition ?? {};+ const trigger = diffTriggers(curDef.triggers, propDef.triggers);+ const actions = diffActions(curDef.actions, propDef.actions);+ const connectionReferences = diffConnectionRefs(current.connectionReferences, proposed.connectionReferences);+ const properties = diffProperties(current, proposed);+ const hasChanges = trigger.changed || actions.added.length > 0 || actions.removed.length > 0 || actions.changed.length > 0 || connectionReferences.added.length > 0 || connectionReferences.removed.length > 0 || connectionReferences.changed.length > 0 || properties.name !== void 0 || properties.state !== void 0;+ const diff = {+ hasChanges,+ summary: "",+ trigger,+ actions,+ connectionReferences,+ properties+ };+ diff.summary = buildSummary(diff);+ return diff;+}+function hashProposal(body) {+ const stable = stableStringify(body);+ let h = 2166136261;+ for (let i = 0; i < stable.length; i++) {+ h ^= stable.charCodeAt(i);+ h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;+ }+ return ("0000000" + h.toString(16)).slice(-8);+}+function stableStringify(v) {+ if (v === null || v === void 0 || typeof v !== "object")+ return JSON.stringify(v) ?? "null";+ if (Array.isArray(v))+ return "[" + v.map(stableStringify).join(",") + "]";+ const obj = v;+ const keys = Object.keys(obj).sort();+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}";+}++// packages/core/dist/api/flow-edit.js+var FlowEditError = class extends Error {+ code;+ path;+ constructor(code, message, path3) {+ super(message);+ this.code = code;+ this.path = path3;+ this.name = "FlowEditError";+ }+};+function isPlainObject2(v) {+ return typeof v === "object" && v !== null && !Array.isArray(v);+}+function parsePath(path3) {+ return path3.split("/").map((s) => s.trim()).filter((s) => s.length > 0);+}+function deepClone(v) {+ if (typeof structuredClone === "function")+ return structuredClone(v);+ return JSON.parse(JSON.stringify(v));+}+function deepMerge(target, source) {+ for (const [k, v] of Object.entries(source)) {+ const existing = target[k];+ if (isPlainObject2(existing) && isPlainObject2(v)) {+ deepMerge(existing, v);+ } else {+ target[k] = v;+ }+ }+ return target;+}+function resolveParent(root, segments, fullPath) {+ let node = root;+ for (let i = 0; i < segments.length - 1; i++) {+ if (!isPlainObject2(node)) {+ throw new FlowEditError("PathNotObject", `Cannot descend into "${segments.slice(0, i).join("/")}" \u2014 not an object.`, fullPath);+ }+ if (!(segments[i] in node)) {+ throw new FlowEditError("PathNotFound", `Path segment "${segments[i]}" does not exist (in "${fullPath}").`, fullPath);+ }+ node = node[segments[i]];+ }+ if (!isPlainObject2(node)) {+ throw new FlowEditError("PathNotObject", `Parent of "${fullPath}" is not an object.`, fullPath);+ }+ return { parent: node, key: segments[segments.length - 1] };+}+function getNode(root, segments, fullPath) {+ let node = root;+ for (const seg of segments) {+ if (!isPlainObject2(node) || !(seg in node)) {+ throw new FlowEditError("PathNotFound", `Path "${fullPath}" not found (stopped at "${seg}").`, fullPath);+ }+ node = node[seg];+ }+ return node;+}+function assertNoOrphanRunAfter(definition) {+ const actions = definition.actions;+ if (!isPlainObject2(actions))+ return;+ const names = new Set(Object.keys(actions));+ const orphans = [];+ for (const [name3, action] of Object.entries(actions)) {+ if (!isPlainObject2(action))+ continue;+ const runAfter = action.runAfter;+ if (!isPlainObject2(runAfter))+ continue;+ for (const dep of Object.keys(runAfter)) {+ if (!names.has(dep)) {+ orphans.push(`${name3}.runAfter \u2192 "${dep}" (missing)`);+ }+ }+ }+ if (orphans.length > 0) {+ throw new FlowEditError("OrphanRunAfter", `Edit would leave dangling runAfter dependencies: ${orphans.join("; ")}. Re-point or remove the dependent action(s) in the same edit.`);+ }+}+function applyFlowEdits(definition, operations) {+ if (!Array.isArray(operations) || operations.length === 0) {+ throw new FlowEditError("EmptyOperations", "No edit operations supplied.");+ }+ const next = deepClone(definition);+ const applied = [];+ for (const operation of operations) {+ const { op, path: path3 } = operation;+ if (op !== "set" && op !== "add" && op !== "remove" && op !== "merge") {+ throw new FlowEditError("InvalidOp", `Unknown op "${op}". Use one of: set, add, remove, merge.`, path3);+ }+ const segments = parsePath(path3 ?? "");+ if (op === "merge") {+ const value = operation.value;+ if (!isPlainObject2(value)) {+ throw new FlowEditError("MergeValueNotObject", `merge "${path3}" requires an object value.`, path3);+ }+ const targetNode = segments.length === 0 ? next : getNode(next, segments, path3);+ if (!isPlainObject2(targetNode)) {+ throw new FlowEditError("MergeTargetNotObject", `merge target "${path3}" is not an object.`, path3);+ }+ deepMerge(targetNode, value);+ applied.push({ op, path: path3 });+ continue;+ }+ if (segments.length === 0) {+ throw new FlowEditError("EmptyPath", `"${op}" requires a non-empty path.`, path3);+ }+ const { parent, key } = resolveParent(next, segments, path3);+ if (op === "remove") {+ if (!(key in parent)) {+ throw new FlowEditError("PathNotFound", `remove "${path3}" \u2014 key "${key}" does not exist.`, path3);+ }+ delete parent[key];+ } else if (op === "add") {+ if (key in parent) {+ throw new FlowEditError("KeyExists", `add "${path3}" \u2014 key "${key}" already exists. Use op:"set" to overwrite.`, path3);+ }+ parent[key] = operation.value;+ } else {+ parent[key] = operation.value;+ }+ applied.push({ op, path: path3 });+ }+ assertNoOrphanRunAfter(next);+ return { definition: next, applied };+}++// packages/core/dist/api/preview-tokens.js+import { randomUUID } from "node:crypto";+var DEFAULT_TTL_MS = 5 * 60 * 1e3;+var store = /* @__PURE__ */ new Map();+function pruneExpired(now) {+ for (const [tok, rec] of store) {+ if (rec.expiresAt <= now)+ store.delete(tok);+ }+}+function issueToken(args) {+ const now = Date.now();+ pruneExpired(now);+ const ttl = args.ttlMs ?? DEFAULT_TTL_MS;+ const token = randomUUID();+ const rec = {+ token,+ envId: args.envId,+ flowId: args.flowId,+ proposalHash: args.proposalHash,+ issuedAt: now,+ expiresAt: now + ttl+ };+ store.set(token, rec);+ return { token, expiresAt: new Date(rec.expiresAt).toISOString() };+}+function redeemToken(token, expected) {+ const now = Date.now();+ const rec = store.get(token);+ if (!rec) {+ pruneExpired(now);+ return { ok: false, code: "PreviewTokenNotFound" };+ }+ if (rec.expiresAt <= now) {+ store.delete(token);+ pruneExpired(now);+ return { ok: false, code: "PreviewTokenExpired" };+ }+ if (rec.envId !== expected.envId) {+ return {+ ok: false,+ code: "PreviewTokenMismatch",+ detail: `token was issued for env ${rec.envId}, request is for env ${expected.envId}`+ };+ }+ if (rec.flowId !== expected.flowId) {+ return {+ ok: false,+ code: "PreviewTokenMismatch",+ detail: `token was issued for flow ${rec.flowId}, request is for flow ${expected.flowId}`+ };+ }+ if (rec.proposalHash !== expected.proposalHash) {+ return {+ ok: false,+ code: "PreviewTokenMismatch",+ detail: `proposal drifted since preview (hash ${rec.proposalHash} != ${expected.proposalHash})`+ };+ }+ store.delete(token);+ return { ok: true };+}++// packages/core/dist/api/flow-client.js+import { execFile } from "node:child_process";+import { randomUUID as randomUUID2 } from "node:crypto";+function logConnectionSuccess(conn, connName, connector, mode) {+ const name3 = conn.name ?? connName;+ const display = conn.properties?.displayName;+ const owner = conn.properties?.createdBy?.userPrincipalName ?? conn.properties?.createdBy?.displayName;+ const modeLabel = mode === "no-auth-required" ? "no auth required" : mode === "first-party-silent" ? "first-party silent auth" : "browser consent";+ const parts = [+ `\u2713 Connection authenticated: ${name3}`,+ `connector=${connector}`,+ `mode=${modeLabel}`+ ];+ if (display && display !== name3)+ parts.push(`displayName="${display}"`);+ if (owner)+ parts.push(`owner=${owner}`);+ logger.info(parts.join(" | "));+}+function createSha256ContentDigest(value) {+ try {+ const json = JSON.stringify(value, Object.keys(value).sort());+ let h = 5381;+ for (let i = 0; i < json.length; i++)+ h = (h << 5) + h + json.charCodeAt(i) | 0;+ return (h >>> 0).toString(16).padStart(8, "0");+ } catch {+ return "00000000";+ }+}+var MAX_RETRIES = 3;+var INITIAL_DELAY_MS = 1e3;+var APIHUB_RESOURCE = "https://apihub.azure.com";+var CONNECTIVITY_RESOURCE = "https://api.powerplatform.com";+function extractLogicalNamesFromFlow(flow) {+ const refs = flow?.properties?.connectionReferences;+ if (!refs)+ return [];+ const out = [];+ for (const ref of Object.values(refs)) {+ const logical = ref?.connectionReferenceLogicalName;+ if (logical)+ out.push(logical);+ }+ return out;+}+var FlowClient = class _FlowClient {+ auth;+ config;+ constructor(auth2, config2) {+ this.auth = auth2;+ this.config = config2;+ }+ /** Resolve the PPAPI base URL for an environment, respecting config overrides. */+ ppapiBase(envId) {+ return ppapiBaseUrl(envId, this.config.ppapiBaseUrlTemplate);+ }+ /** Build PPAPI flow query string with api-version. */+ ppapiFlowQs(extra) {+ const params = { "api-version": "1" };+ for (const [k, v] of Object.entries(extra)) {+ if (v !== void 0)+ params[k] = v;+ }+ return "?" + new URLSearchParams(params).toString();+ }+ // --- Environments ---+ // listEnvironments uses Flow RP because PPAPI is environment-scoped+ // (you need the env ID to construct a PPAPI URL, creating a chicken-and-egg problem).+ // This is the only discovery endpoint that requires Flow RP.+ async listEnvironments() {+ const url = environmentsUrl(this.config.baseUrl);+ const data = await this.get(url);+ return data.value;+ }+ // --- Flows ---+ async listFlows(envId, opts) {+ const base = this.ppapiBase(envId);+ const qs2 = this.ppapiFlowQs({ $top: opts?.top?.toString(), $filter: opts?.filter });+ const url = `${base}/powerautomate/flows${qs2}`;+ return followPagination(async (nextUrl) => this.ppapiRequest("GET", nextUrl ?? url));+ }+ async getFlow(envId, flowId) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;+ return this.ppapiRequest("GET", url);+ }+ async createFlow(envId, body, opts = {}) {+ if (!opts.allowDuplicate) {+ await this.assertNoDuplicateDisplayName(envId, body.properties.displayName);+ }+ const injected = [];+ if (opts.autoInjectParams !== false) {+ const def = body.properties?.definition;+ if (def && typeof def === "object") {+ const d = def;+ if (!d.parameters || typeof d.parameters !== "object") {+ d.parameters = {};+ }+ if (!("$authentication" in d.parameters)) {+ d.parameters.$authentication = { type: "SecureObject", defaultValue: {} };+ injected.push("$authentication");+ }+ if (!("$connections" in d.parameters)) {+ d.parameters.$connections = { type: "Object", defaultValue: {} };+ injected.push("$connections");+ }+ }+ }+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows${this.ppapiFlowQs({})}`;+ const created = await this.ppapiRequest("POST", url, body);+ if (injected.length > 0) {+ created._autoInjected = injected;+ logger.info(`[create-flow] Auto-injected missing parameters: ${injected.join(", ")}. Pass autoInjectParams:false to opt out.`);+ }+ return created;+ }+ /**+ * Refuse to create a flow whose displayName collides with an existing flow+ * in the environment. Policy: "always update, never recreate." On lookup+ * failure (transient list error etc.) we fail open and allow the create —+ * the underlying ppapiRequest will still surface any real server-side+ * conflict.+ */+ async assertNoDuplicateDisplayName(envId, displayName) {+ let existing;+ try {+ existing = await this.listFlows(envId, {});+ } catch (err) {+ logger.warn(`[no-recreate-guard] listFlows failed during duplicate check (${err instanceof Error ? err.message : String(err)}); allowing create_flow to proceed`);+ return;+ }+ const match = existing.find((f) => (f.properties?.displayName ?? "") === displayName);+ if (match) {+ throw new DuplicateFlowError(displayName, envId, match.name, match.properties?.state);+ }+ }+ async updateFlow(envId, flowId, body, opts = {}) {+ if (opts.previewToken) {+ await this.assertPreviewTokenMatches(envId, flowId, body, opts.previewToken);+ }+ await this.assertNotManaged(envId, flowId, "update_flow", opts);+ await this.snapshotBeforeMutation(envId, flowId, "update_flow", opts);+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;+ return this.ppapiRequest("PATCH", url, body);+ }+ /**+ * Compute a diff between the current flow and the proposed update body,+ * issue a short-lived single-use token bound to (envId, flowId, proposal),+ * and return both. The caller can then call `updateFlow` with the token+ * to commit, after reviewing the diff.+ *+ * No mutation is performed by this method; failure modes are limited to+ * the underlying `getFlow` call.+ */+ async previewUpdate(envId, flowId, body, opts = {}) {+ const current = await this.getFlow(envId, flowId);+ const currentSnap = toSnapshot(current);+ const proposed = mergeProposal(currentSnap, body);+ const diff = diffFlow(currentSnap, proposed);+ const proposalHash = hashProposal(proposed);+ const { token, expiresAt } = issueToken({+ envId,+ flowId,+ proposalHash,+ ttlMs: opts.ttlMs+ });+ return {+ flowId,+ environmentId: envId,+ diff,+ proposalHash,+ token,+ expiresAt,+ note: diff.hasChanges ? "Review the diff above. Re-submit the SAME body to update_flow with previewToken to apply." : "No changes detected vs the live flow. update_flow is a no-op for this body."+ };+ }+ async assertPreviewTokenMatches(envId, flowId, body, token) {+ const current = await this.getFlow(envId, flowId);+ const proposed = mergeProposal(toSnapshot(current), body);+ const proposalHash = hashProposal(proposed);+ const result = redeemToken(token, { envId, flowId, proposalHash });+ if (!result.ok) {+ if (result.code === "PreviewTokenMismatch") {+ throw new PreviewTokenError("PreviewTokenMismatch", result.detail);+ }+ throw new PreviewTokenError(result.code);+ }+ }+ /**+ * Apply targeted ("surgical") edits to a flow definition without resending+ * the whole thing. The current definition is fetched, the ordered list of+ * operations is applied to a clone (see flow-edit.ts), and the result is+ * routed through the normal `updateFlow` path — so the managed-solution+ * guard, auto-backup, and preview-token concurrency check all still apply.+ *+ * Works for non-solution flows and unmanaged-solution flows alike. Managed+ * solution flows are rejected by the same guard as update_flow (pass+ * forceManaged to override). Flows with no connection references are fine —+ * the definition is edited in place regardless.+ *+ * With `dryRun: true`, no write happens: the resulting definition is diffed+ * against the live flow and a single-use preview token is returned. Re-call+ * with the same operations plus that `previewToken` to apply.+ */+ async editFlow(envId, flowId, operations, opts = {}) {+ const current = await this.getFlow(envId, flowId);+ const currentDef = current.properties?.definition ?? {};+ const { definition, applied } = applyFlowEdits(currentDef, operations);+ const body = { properties: { definition } };+ if (opts.dryRun) {+ const preview = await this.previewUpdate(envId, flowId, body);+ return {+ mode: "preview",+ applied,+ diff: preview.diff,+ token: preview.token,+ expiresAt: preview.expiresAt,+ note: "Dry run \u2014 no change applied. Re-call edit_flow with the SAME operations plus this previewToken to apply."+ };+ }+ const flow = await this.updateFlow(envId, flowId, body, {+ forceManaged: opts.forceManaged,+ previewToken: opts.previewToken,+ skipBackup: opts.skipBackup,+ backupNote: opts.backupNote ?? `edit_flow: ${applied.length} op(s)`+ });+ return { mode: "applied", applied, flow };+ }+ /**+ * Copy a flow within the same environment or across environments. The source+ * definition is read and re-created as a new, standalone flow (always created+ * Stopped by default). No native PA "copy" endpoint exists — this orchestrates+ * getFlow + connection-ref remapping + createFlow.+ *+ * Behaviour by flow shape:+ * - **No connection references** (built-in actions only, e.g. Compose/HTTP):+ * copied as-is, no resolution attempted.+ * - **Same-env copy**: source connection references are reused verbatim+ * (they are already valid in that environment).+ * - **Cross-env copy**: each connector is re-resolved in the target env via+ * resolveConnectionRefs (Dataverse-first, PPAPI fallback). Connectors with+ * no usable connection in the target are reported in `unresolvedConnectors`+ * and the new flow is left Stopped so it cannot run half-wired.+ * - **Solution-bound source** (managed or unmanaged): the copy is a plain+ * standalone flow — solution membership is intentionally dropped. A note+ * is returned when this is detected.+ */+ async copyFlow(envId, flowId, opts = {}) {+ const source = await this.getFlow(envId, flowId);+ const props = source.properties ?? {};+ const definition = props.definition;+ if (!definition) {+ throw new FlowApiError(404, "Source flow has no definition", `Flow ${flowId} returned no definition; cannot copy.`, "");+ }+ const sourceName = props.displayName ?? "Flow";+ const targetEnv = opts.targetEnv ?? envId;+ const sameEnv = targetEnv === envId;+ const newName = opts.name ?? `${sourceName} (Copy)`;+ const state = opts.state ?? "Stopped";+ const autoResolve = opts.autoResolveConnections !== false;+ const sourceRefs = props.connectionReferences;+ let connectionReferences = sourceRefs;+ const unresolvedConnectors = [];+ const hasRefs = !!sourceRefs && Object.keys(sourceRefs).length > 0;+ if (hasRefs && !sameEnv && autoResolve) {+ const connectorByRefKey = {};+ for (const [refKey, ref] of Object.entries(sourceRefs)) {+ connectorByRefKey[refKey] = connectorFromRef(refKey, ref);+ }+ const connectors = Array.from(new Set(Object.values(connectorByRefKey)));+ const resolved = await this.resolveConnectionRefs(targetEnv, connectors);+ const remapped = {};+ for (const [refKey, ref] of Object.entries(sourceRefs)) {+ const connector = connectorByRefKey[refKey];+ const target = resolved[connector];+ const newRef = { ...ref };+ const targetName = target?.connectionName;+ const isPlaceholder = !!target?._error || typeof targetName === "string" && (targetName.startsWith("NO_CONNECTION_FOUND_FOR_") || targetName.startsWith("LOOKUP_FAILED_FOR_"));+ if (target && !isPlaceholder && targetName) {+ newRef.connectionName = targetName;+ if (target.connectionReferenceLogicalName) {+ newRef.connectionReferenceLogicalName = target.connectionReferenceLogicalName;+ }+ } else {+ unresolvedConnectors.push(connector);+ }+ delete newRef._error;+ remapped[refKey] = newRef;+ }+ connectionReferences = remapped;+ }+ let note;+ try {+ const ctx = await this.getFlowContext(envId, flowId);+ if (!ctx.warning && ctx.inSolution) {+ note = `Source flow is in solution "${ctx.solutionFriendlyName ?? ctx.solutionUniqueName ?? "(unknown)"}"${ctx.isManaged ? " (managed)" : ""}; the copy is a standalone, non-solution flow.`;+ }+ } catch {+ }+ const created = await this.createFlow(targetEnv, {+ properties: {+ displayName: newName,+ definition,+ state,+ connectionReferences+ }+ });+ if (unresolvedConnectors.length > 0) {+ const warn = `Created Stopped with ${unresolvedConnectors.length} unresolved connector(s): ${unresolvedConnectors.join(", ")}. Create connections in the target env, then update the flow's references.`;+ note = note ? `${note} ${warn}` : warn;+ }+ return {+ flowId: created.name,+ environmentId: targetEnv,+ displayName: newName,+ sameEnv,+ unresolvedConnectors,+ note+ };+ }+ async deleteFlow(envId, flowId, opts = {}) {+ await this.assertNotManaged(envId, flowId, "delete_flow", opts);+ await this.snapshotBeforeMutation(envId, flowId, "delete_flow", opts);+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;+ await this.ppapiRequest("DELETE", url);+ }+ /**+ * Restore a flow from a previously captured backup. The current state of+ * the flow is itself snapshotted first (with operation="restore_backup")+ * so that a restore can be undone. If the flow no longer exists (e.g. it+ * was deleted), the backup definition is re-created via createFlow.+ */+ async restoreFlowFromBackup(envId, flowId, backupFilename, opts = {}) {+ const { readBackup: readBackup2 } = await Promise.resolve().then(() => (init_backups(), backups_exports));+ const backup = readBackup2(envId, flowId, backupFilename);+ const stored = backup.flow;+ if (!stored?.properties?.definition) {+ throw new Error(`Backup ${backupFilename} for ${flowId} has no definition; cannot restore.`);+ }+ let exists = true;+ try {+ await this.getFlow(envId, flowId);+ } catch (err) {+ if (err instanceof FlowApiError && err.statusCode === 404) {+ exists = false;+ } else {+ throw err;+ }+ }+ if (exists) {+ const updateBody = {+ properties: {+ displayName: stored.properties.displayName,+ definition: stored.properties.definition,+ connectionReferences: stored.properties.connectionReferences+ }+ };+ await this.updateFlow(envId, flowId, updateBody, {+ forceManaged: opts.forceManaged,+ backupNote: `restore from ${backupFilename}`+ });+ return { restored: true, mode: "update", flowId };+ }+ if (!stored.properties.definition) {+ throw new Error(`Backup ${backupFilename} has no definition; cannot recreate.`);+ }+ const created = await this.createFlow(envId, {+ properties: {+ displayName: stored.properties.displayName,+ definition: stored.properties.definition,+ connectionReferences: stored.properties.connectionReferences,+ state: stored.properties.state+ }+ }, { allowDuplicate: true });+ return { restored: true, mode: "recreate", flowId: created.name ?? flowId };+ }+ async publishFlow(envId, flowId, opts = {}) {+ await this.assertNotManaged(envId, flowId, "publish_flow", opts);+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/start${this.ppapiFlowQs({})}`;+ await this.ppapiRequest("POST", url);+ }+ async disableFlow(envId, flowId, opts = {}) {+ await this.assertNotManaged(envId, flowId, "disable_flow", opts);+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/stop${this.ppapiFlowQs({})}`;+ await this.ppapiRequest("POST", url);+ }+ // --- Runs ---+ async runFlow(envId, flowId, triggerBody, triggerName) {+ const resolvedTrigger = triggerName ?? await this.resolveTriggerName(envId, flowId);+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/triggers/${resolvedTrigger}/run${this.ppapiFlowQs({})}`;+ return this.ppapiRequest("POST", url, triggerBody ?? {});+ }+ /**+ * Resolve the trigger name from a flow's definition.+ * Returns the first trigger key (e.g., "manual", "Recurrence", "When_a_new_item_is_created").+ * Falls back to "manual" if the definition can't be read.+ */+ async resolveTriggerName(envId, flowId) {+ try {+ const flow = await this.getFlow(envId, flowId);+ const triggers = flow.properties?.definition?.triggers;+ if (triggers && typeof triggers === "object") {+ const names = Object.keys(triggers);+ if (names.length > 0)+ return names[0];+ }+ } catch {+ }+ return "manual";+ }+ async getTriggerCallbackUrl(envId, flowId, triggerName) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/triggers/${triggerName ?? "manual"}/listCallbackUrl${this.ppapiFlowQs({})}`;+ const raw = await this.ppapiRequest("POST", url);+ const data = "response" in raw && raw.response ? raw.response : raw;+ return data.value;+ }+ async runFlowViaCallback(envId, flowId, triggerBody, triggerName) {+ const resolvedTrigger = triggerName ?? await this.resolveTriggerName(envId, flowId);+ const callbackUrl = await this.getTriggerCallbackUrl(envId, flowId, resolvedTrigger);+ const headers = {+ "Content-Type": "application/json"+ };+ logger.debug(`POST ${callbackUrl}`);+ const response = await fetch(callbackUrl, {+ method: "POST",+ headers,+ body: JSON.stringify(triggerBody)+ });+ let body;+ const text = await response.text();+ try {+ body = text ? JSON.parse(text) : void 0;+ } catch {+ body = text;+ }+ if (!response.ok) {+ throw new FlowApiError(response.status, response.statusText, typeof body === "string" ? body : JSON.stringify(body), callbackUrl.split("?")[0]);+ }+ return { status: response.status, body };+ }+ async getRunHistory(envId, flowId, opts) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/runs${this.ppapiFlowQs({ $top: opts?.top?.toString(), $filter: opts?.filter })}`;+ const all = await followPagination(async (nextUrl) => this.ppapiRequest("GET", nextUrl ?? url));+ if (opts?.top && all.length > opts.top)+ return all.slice(0, opts.top);+ return all;+ }+ async getRunDetails(envId, flowId, runId) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/runs/${runId}${this.ppapiFlowQs({})}`;+ return this.ppapiRequest("GET", url);+ }+ async getRunActionDetails(envId, flowId, runId) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/runs/${runId}/actions${this.ppapiFlowQs({})}`;+ return followPagination(async (nextUrl) => this.ppapiRequest("GET", nextUrl ?? url));+ }+ /**+ * Cancel a single in-progress (Running/Waiting) flow run.+ * No-op-safe: PA returns an error for already-terminal runs, surfaced as a+ * FlowApiError. Endpoint mirrors the Logic Apps `runs/{run}/cancel` contract.+ */+ async cancelRun(envId, flowId, runId) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/runs/${runId}/cancel${this.ppapiFlowQs({})}`;+ await this.ppapiRequest("POST", url);+ return { cancelled: true, runId };+ }+ /**+ * Resubmit a past run using the same trigger inputs it originally received.+ * The PA/Logic Apps contract resubmits against the trigger history:+ * `triggers/{triggerName}/histories/{runId}/resubmit`. The trigger name is+ * discovered from the run unless supplied.+ */+ async resubmitRun(envId, flowId, runId, opts = {}) {+ let triggerName = opts.triggerName;+ if (!triggerName) {+ try {+ const run = await this.getRunDetails(envId, flowId, runId);+ triggerName = run.properties?.trigger?.name;+ } catch {+ }+ }+ triggerName = triggerName ?? "manual";+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/triggers/${triggerName}/histories/${runId}/resubmit${this.ppapiFlowQs({})}`;+ await this.ppapiRequest("POST", url);+ return { resubmitted: true, runId, triggerName };+ }+ /**+ * List iteration-level details for an action that runs inside a loop+ * (Apply_to_each / Do_until) within a run. Each repetition is one pass of the+ * loop and carries its own status, inputs/outputs links, and (on failure)+ * error — the only way to see WHICH iteration of a loop failed. Pass the name+ * of an action INSIDE the loop, not the loop container (the container returns+ * no repetitions). Mirrors the Logic Apps+ * `runs/{run}/actions/{action}/repetitions` contract.+ */+ async getRunActionRepetitions(envId, flowId, runId, actionName) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/flows/${flowId}/runs/${runId}/actions/${actionName}/repetitions${this.ppapiFlowQs({})}`;+ return followPagination(async (nextUrl) => this.ppapiRequest("GET", nextUrl ?? url));+ }+ /**+ * Bulk-cancel every in-progress run of a flow. Two paths (per+ * https://learn.microsoft.com/power-automate/how-tos-bulk-resubmit#cancel-flow-runs):+ *+ * 1. **Dataverse bulk action** (`CancelAllCloudFlowRuns`, bound to the+ * `workflow` entity) — used whenever the flow exists as a Dataverse+ * workflow record, which covers BOTH solution flows AND modern+ * non-solution flows. One server-side call cancels the whole queue;+ * statuses transition Running/Waiting → Canceling → Canceled (can take+ * up to 24h).+ * 2. **Per-run fallback** — for flows with no Dataverse workflow record+ * (e.g. environments without Dataverse): enumerate run history, filter to+ * Running/Waiting, and cancel each individually.+ *+ * Optionally turns the flow off afterwards (`turnOff`) so the underlying+ * issue can be fixed. Cancel happens first, then turn-off (turning a flow off+ * first would leave pending runs stuck Waiting until it is turned back on).+ */+ async cancelAllRuns(envId, flowId, opts = {}) {+ let workflowId = null;+ try {+ const ctx = await this.getFlowContext(envId, flowId);+ if (!ctx.warning)+ workflowId = ctx.workflowId;+ } catch {+ workflowId = null;+ }+ let result;+ if (workflowId) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const base = instanceUrl.replace(/\/$/, "");+ const url = `${base}/api/data/v9.2/workflows(${workflowId})/Microsoft.Dynamics.CRM.CancelAllCloudFlowRuns`;+ await this.dataversePost(url, {}, dvToken);+ result = {+ method: "dataverse-bulk",+ note: "Server-side bulk cancel queued via CancelAllCloudFlowRuns. Runs in Running/Waiting transition to Canceling then Canceled (can take up to 24h)."+ };+ } else {+ const cap = opts.maxFallback ?? 250;+ const active = (await this.getRunHistory(envId, flowId, { top: cap })).filter((r) => ["Running", "Waiting"].includes(r.properties?.status));+ let cancelled = 0;+ const failures = [];+ for (const r of active) {+ try {+ await this.cancelRun(envId, flowId, r.name);+ cancelled++;+ } catch (e) {+ failures.push({ runId: r.name, error: e instanceof Error ? e.message : String(e) });+ }+ }+ result = {+ method: "per-run",+ cancelled,+ attempted: active.length,+ failures,+ note: active.length === 0 ? "No Running/Waiting runs to cancel (and no Dataverse workflow record for a bulk action)." : `Cancelled ${cancelled}/${active.length} active runs individually (no Dataverse workflow record for a bulk action).`+ };+ }+ let turnedOff = false;+ if (opts.turnOff) {+ try {+ await this.disableFlow(envId, flowId, { forceManaged: opts.forceManaged });+ turnedOff = true;+ } catch (e) {+ logger.warn(`cancelAllRuns: turn-off failed: ${e instanceof Error ? e.message : String(e)}`);+ }+ }+ return { ...result, turnedOff };+ }+ /**+ * Diagnose a flow run: classify each failed action with an actionable+ * remediation. Read-only — fetches run details + actions and maps known+ * error codes to fixes. Complements the flow-debugger skill as a callable+ * primitive.+ */+ async diagnoseRun(envId, flowId, runId) {+ const run = await this.getRunDetails(envId, flowId, runId);+ const status = run.properties?.status ?? "Unknown";+ const actions = await this.getRunActionDetails(envId, flowId, runId);+ const failedActions = actions.filter((a) => {+ const s = a.properties?.status;+ return s === "Failed" || s === "TimedOut";+ }).map((a) => {+ const code = a.properties?.code ?? a.properties?.error?.code;+ const message = a.properties?.error?.message;+ return {+ name: a.name,+ code,+ message,+ remediation: remediateActionError(code, message)+ };+ });+ const summary = status === "Succeeded" ? "Run succeeded \u2014 no failed actions." : failedActions.length > 0 ? `Run ${status}; ${failedActions.length} failed action(s): ${failedActions.map((f) => f.name).join(", ")}.` : `Run ${status}; no per-action failures captured (check the trigger or run-level error).`;+ return {+ runId,+ status,+ error: run.properties?.error,+ failedActions,+ summary+ };+ }+ /**+ * Fetch trigger inputs from a past run. This is the same primitive the PA+ * designer uses for "Test with previous run data". For each requested run,+ * returns the resolved trigger input envelope (body / headers / queries)+ * along with a content digest the caller can use to dedupe identical inputs.+ *+ * Strategy:+ * 1. Use getRunHistory to list candidate runs (most-recent first).+ * 2. For each, fetch the trigger action's input envelope via the+ * run-actions endpoint. The trigger is always the first action in+ * `actions[]` and its `inputsLink.uri` (or inlined `inputs`) holds+ * the resolved trigger payload.+ *+ * Returns oldest→newest? No — most-recent first, matching what the+ * designer shows.+ */+ async getPastTriggerInputs(envId, flowId, opts = {}) {+ const { top = 5, runId, statusFilter = "any" } = opts;+ let runs;+ if (runId) {+ runs = [await this.getRunDetails(envId, flowId, runId)];+ } else {+ const filter = statusFilter === "any" ? void 0 : `status eq '${statusFilter}'`;+ runs = await this.getRunHistory(envId, flowId, { top, filter });+ }+ const out = [];+ for (const run of runs) {+ try {+ const actions = await this.getRunActionDetails(envId, flowId, run.name ?? runId);+ const triggerAction = Array.isArray(actions) && actions.length > 0 ? actions[0] : null;+ if (!triggerAction)+ continue;+ let triggerInputs = triggerAction.properties?.inputs;+ const inputsLink = triggerAction.properties?.inputsLink?.uri;+ if (!triggerInputs && inputsLink) {+ try {+ triggerInputs = await this.ppapiRequest("GET", inputsLink);+ } catch {+ triggerInputs = { _note: "inputsLink fetch failed; trigger inputs unavailable for this run" };+ }+ }+ const contentDigest = createSha256ContentDigest(triggerInputs);+ out.push({+ runId: run.name ?? runId ?? "",+ startTime: run.properties?.startTime ?? "",+ status: run.properties?.status ?? "",+ triggerName: triggerAction.name ?? "unknown",+ triggerInputs,+ contentDigest+ });+ } catch (err) {+ out.push({+ runId: run.name ?? "",+ startTime: run.properties?.startTime ?? "",+ status: run.properties?.status ?? "",+ triggerName: "unknown",+ triggerInputs: { _error: err instanceof Error ? err.message : String(err) },+ contentDigest: ""+ });+ }+ }+ return out;+ }+ /**+ * Pre-save sanity check: given a flow definition, return a structured+ * report of what will (probably) fail before/at save and after publish.+ *+ * Covers (today):+ * - validate_flow rules (delegated to validateDefinition)+ * - solutionWrapDetected — heuristic check for orgs that auto-wrap+ * new flows in a solution (eval finding F4). When wrap is detected+ * AND the definition has any unresolved connection references, we+ * flag SolutionWrapWillBlockPublish.+ * - connection-ref resolution status (which refs map to a Connected+ * connection, which don't)+ *+ * Future: DLP policy check, missing connector check, license tier check.+ * Lives here so MCP `preflight_flow` and the CLI `preflight` command+ * share one implementation.+ */+ async preflightFlow(envId, definition, opts = {}) {+ const { validateDefinition: validateDefinition2 } = await Promise.resolve().then(() => (init_flow_definition(), flow_definition_exports));+ const validationErrors = validateDefinition2(definition, opts.connectionReferences);+ const errors = validationErrors;+ const warnings = [];+ const refs = opts.connectionReferences ?? {};+ const refStatus = [];+ for (const [logicalName, ref] of Object.entries(refs)) {+ const connector = ref.id ? ref.id.split("/").pop() ?? "" : "";+ if (!ref.connectionName || ref.connectionName.startsWith("NO_CONNECTION_FOUND_FOR_") || ref.connectionName.startsWith("LOOKUP_FAILED_FOR_")) {+ refStatus.push({+ logicalName,+ connectionName: ref.connectionName ?? "",+ connector,+ status: "missing",+ remediation: `Call pick_or_create_connection with connector=${connector} to provision.`+ });+ continue;+ }+ try {+ const conn = await this.getConnection(envId, connector, ref.connectionName);+ const connected = conn.properties?.statuses?.some((s) => s.status === "Connected");+ refStatus.push({+ logicalName,+ connectionName: ref.connectionName,+ connector,+ status: connected ? "connected" : "not-connected",+ ...connected ? {} : { remediation: `Call fix_connection on ${ref.connectionName} to re-auth.` }+ });+ } catch {+ refStatus.push({+ logicalName,+ connectionName: ref.connectionName,+ connector,+ status: "missing",+ remediation: `Connection not found in env. Call pick_or_create_connection with connector=${connector}.`+ });+ }+ }+ const hasUnresolvedRef = refStatus.some((r) => r.status !== "connected");+ const solutionWrap = hasUnresolvedRef ? {+ detected: true,+ remediation: "If this env auto-wraps new flows in a solution, publish_flow will fail with CannotStartUnpublishedSolutionFlow until every connection reference is Connected. Resolve all refs first."+ } : { detected: false };+ let overall = "ready";+ if (errors.length > 0)+ overall = "block";+ else if (refStatus.some((r) => r.status === "missing"))+ overall = "block";+ else if (warnings.length > 0 || refStatus.some((r) => r.status !== "connected"))+ overall = "warn";+ const summary = [];+ if (errors.length > 0)+ summary.push(`${errors.length} validation error(s) \u2014 will reject at save`);+ if (warnings.length > 0)+ summary.push(`${warnings.length} validation warning(s)`);+ if (refStatus.length > 0) {+ const connected = refStatus.filter((r) => r.status === "connected").length;+ const broken = refStatus.length - connected;+ summary.push(`${connected}/${refStatus.length} connection refs Connected${broken ? `; ${broken} need attention` : ""}`);+ }+ if (solutionWrap.detected && hasUnresolvedRef) {+ summary.push("Solution-wrap risk: unresolved refs will block publish");+ }+ if (overall === "ready")+ summary.push("Ready to save + publish");+ return { overall, validation: { valid: errors.length === 0, errors, warnings }, connectionRefs: refStatus, solutionWrap, summary };+ }+ // --- Flow Sessions (Dataverse) ---+ async getFlowSessions(envId, flowId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseFlowSessionsUrl(instanceUrl, flowId, opts);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ // --- Desktop Flows (Dataverse) ---+ async getDataverseInstanceUrl(envId) {+ let env;+ try {+ env = await this.getEnvironment(envId);+ } catch {+ const url = environmentUrl(this.config.baseUrl ?? "https://api.flow.microsoft.com", envId);+ env = await this.get(url);+ }+ const instanceUrl = env.properties?.linkedEnvironmentMetadata?.instanceUrl;+ if (!instanceUrl) {+ throw new FlowApiError(400, "No Dataverse instance", "Environment has no linked Dataverse instance.", "");+ }+ return instanceUrl;+ }+ async listDesktopFlows(envId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseDesktopFlowsUrl(instanceUrl, opts);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ async triggerDesktopFlow(envId, flowId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseTriggerDesktopFlowUrl(instanceUrl);+ const body = {+ "[email protected]": `/workflows(${flowId})`,+ statuscode: 1,+ statecode: 0+ };+ if (opts?.inputs) {+ body.inputs = JSON.stringify(opts.inputs);+ }+ if (opts?.machineGroupId) {+ body["[email protected]"] = `/flowmachinegroups(${opts.machineGroupId})`;+ }+ return this.dataversePost(url, body, dvToken);+ }+ async getDesktopFlowSession(envId, sessionId) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseDesktopFlowSessionUrl(instanceUrl, sessionId);+ return this.dataverseGet(url, dvToken);+ }+ /**+ * Trigger a desktop flow and poll until completion.+ * Status codes: 1=Waiting, 2=InProgress, 4=Failed, 5=Cancelled, 8=Succeeded+ */+ async runDesktopFlowAndWait(envId, flowId, opts) {+ const timeout = opts?.timeoutMs ?? 3e5;+ const pollInterval = opts?.pollIntervalMs ?? 5e3;+ const progress2 = opts?.onProgress ?? (() => {+ });+ const session = await this.triggerDesktopFlow(envId, flowId, {+ inputs: opts?.inputs,+ machineGroupId: opts?.machineGroupId+ });+ const sessionId = session.flowsessionid;+ const deadline = Date.now() + timeout;+ const TERMINAL_CODES = /* @__PURE__ */ new Set([4, 5, 8]);+ while (Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, pollInterval));+ const current = await this.getDesktopFlowSession(envId, sessionId);+ progress2(current);+ if (TERMINAL_CODES.has(current.statuscode)) {+ return current;+ }+ }+ throw new FlowApiError(408, "Desktop flow run timed out", `Session ${sessionId} did not complete within ${timeout / 1e3}s`, "");+ }+ async listMachineGroups(envId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseMachineGroupsUrl(instanceUrl, opts);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ async resolveMachineGroup(envId, name3) {+ const groups = await this.listMachineGroups(envId, { nameFilter: name3 });+ if (groups.length === 0) {+ throw new FlowApiError(404, "Machine group not found", `No machine group named "${name3}" found in this environment.`, "");+ }+ return groups[0];+ }+ async listMachines(envId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseMachinesUrl(instanceUrl, opts);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ // --- Connection Mode ---+ static DATAVERSE_CONNECTOR = "shared_commondataserviceforapps";+ async setConnectionMode(envId, flowId, connectorKey, mode) {+ const flow = await this.getFlow(envId, flowId);+ const connRefs = flow.properties.connectionReferences;+ if (!connRefs || !(connectorKey in connRefs)) {+ throw new FlowApiError(404, "Connection reference not found", `"${connectorKey}" not found. Available: ${connRefs ? Object.keys(connRefs).join(", ") : "(none)"}`, "");+ }+ const ref = { ...connRefs[connectorKey] };+ ref.source = mode;+ if (connectorKey === _FlowClient.DATAVERSE_CONNECTOR) {+ if (mode === "Embedded") {+ ref.connectionProperties = { authentication: { type: "ManagedServiceIdentity" } };+ } else {+ delete ref.connectionProperties;+ }+ } else if (mode === "Invoker") {+ delete ref.connectionProperties;+ }+ const updatedRefs = { ...connRefs, [connectorKey]: ref };+ return this.updateFlow(envId, flowId, { properties: { connectionReferences: updatedRefs } });+ }+ // --- Environment Routing ---+ /**+ * Resolve the user's routing environment via Governance RP.+ * Returns the raw response and HTTP status for the caller to interpret.+ */+ async getUserRoutingEnvironment() {+ const url = governanceUserRoutingUrl();+ const token = await this.auth.getAccessToken();+ logger.debug(`GET ${url}`);+ const response = await fetch(url, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json"+ }+ });+ const text = await response.text();+ const body = text ? JSON.parse(text) : {};+ return { status: response.status, body };+ }+ /**+ * Poll for routing provisioning operation completion.+ */+ async getRoutingOperationStatus(operationId) {+ const url = governanceRoutingStatusUrl(operationId);+ const token = await this.auth.getAccessToken();+ logger.debug(`GET ${url}`);+ const response = await fetch(url, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json"+ }+ });+ if (!response.ok) {+ const body = await response.text();+ throw new FlowApiError(response.status, response.statusText, body, url);+ }+ return await response.json();+ }+ /**+ * Get the default environment via BAP-RP (~default).+ */+ async getDefaultEnvironment() {+ const url = bapDefaultEnvironmentUrl();+ const token = await this.auth.getAccessToken();+ logger.debug(`GET ${url}`);+ const response = await fetch(url, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json"+ }+ });+ if (!response.ok) {+ const body = await response.text();+ throw new FlowApiError(response.status, response.statusText, body, url);+ }+ return await response.json();+ }+ /**+ * Full environment resolution: routing → poll → fallback.+ * Implements the deterministic resolution flow from the Governance RP spec.+ */+ async resolveEnvironment(opts) {+ const maxWait = opts?.maxWaitMs ?? 12e4;+ const pollInterval = opts?.pollIntervalMs ?? 3e3;+ const progress2 = opts?.onProgress ?? (() => {+ });+ try {+ progress2("Resolving user routing environment...");+ const { status, body } = await this.getUserRoutingEnvironment();+ if (status === 200) {+ const envId = body.environmentId ?? body.properties?.environmentId;+ if (envId) {+ progress2(`Routing resolved: ${envId}`);+ return { environmentId: envId, source: "routing", provisioned: false };+ }+ }+ if (status === 202) {+ const operationId = body.operationId ?? body.operationId;+ if (operationId) {+ progress2("Personal Developer Environment provisioning in progress...");+ const resolved = await this.pollRoutingCompletion(operationId, maxWait, pollInterval, progress2);+ if (resolved)+ return resolved;+ }+ }+ progress2(`Routing returned ${status}, falling back to default environment...`);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ progress2(`Routing failed (${msg}), falling back to default environment...`);+ }+ return this.resolveDefaultEnvironment(progress2);+ }+ async pollRoutingCompletion(operationId, maxWaitMs, pollIntervalMs, progress2) {+ const deadline = Date.now() + maxWaitMs;+ while (Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, pollIntervalMs));+ try {+ const op = await this.getRoutingOperationStatus(operationId);+ progress2(`Provisioning status: ${op.status}`);+ if (op.status === "Succeeded") {+ const envId = op.properties?.environmentId;+ if (envId) {+ progress2(`PDE provisioned: ${envId}`);+ return { environmentId: envId, source: "provisioned", provisioned: true };+ }+ }+ if (op.status === "Failed") {+ progress2(`Provisioning failed: ${op.error?.message ?? "unknown error"}`);+ return null;+ }+ } catch (err) {+ progress2(`Polling error: ${err instanceof Error ? err.message : err}`);+ return null;+ }+ }+ progress2("Provisioning timed out");+ return null;+ }+ async resolveDefaultEnvironment(progress2) {+ try {+ progress2("Resolving default environment via BAP...");+ const env = await this.getDefaultEnvironment();+ if (env.name) {+ progress2(`Default environment: ${env.name}`);+ return { environmentId: env.name, source: "default", provisioned: false };+ }+ } catch {+ progress2("BAP ~default unavailable, listing environments...");+ }+ const envs = await this.listEnvironments();+ const defaultEnv = envs.find((e) => e.properties.isDefault);+ if (defaultEnv) {+ progress2(`Default environment (from list): ${defaultEnv.name}`);+ return { environmentId: defaultEnv.name, source: "default", provisioned: false };+ }+ if (envs.length > 0) {+ progress2(`No default found, using first environment: ${envs[0].name}`);+ return { environmentId: envs[0].name, source: "default", provisioned: false };+ }+ throw new FlowApiError(404, "No environments", "No Power Automate environments found for this user.", "");+ }+ // --- Connectors ---+ async listConnectors(envId, opts) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/apis${this.ppapiFlowQs({ $top: opts?.top?.toString() })}`;+ const data = await this.ppapiRequest("GET", url);+ return data.value.map((c) => ({+ name: c.name,+ displayName: c.properties.displayName,+ description: c.properties.description,+ tier: c.properties.tier+ }));+ }+ async getConnector(envId, connectorName) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate/apis/${connectorName}${this.ppapiFlowQs({ $expand: "swagger" })}`;+ const connector = await this.ppapiRequest("GET", url);+ const swagger = connector.properties.swagger;+ const operations = [];+ if (swagger?.paths) {+ for (const [path3, methods] of Object.entries(swagger.paths)) {+ for (const [method, op] of Object.entries(methods)) {+ if (!op.operationId)+ continue;+ const params = [];+ if (op.parameters) {+ this.extractParameters(op.parameters, params, swagger);+ }+ operations.push({+ operationId: op.operationId,+ summary: op.summary ?? op.description,+ method: method.toUpperCase(),+ path: path3,+ parameters: params+ });+ }+ }+ }+ return {+ name: connector.name,+ displayName: connector.properties.displayName,+ operations+ };+ }+ async invokeOperation(envId, connectorName, connectionId, operationId, params) {+ const connectorUrl = ppapiConnectorUrl(envId, connectorName, { expand: "swagger" });+ const connector = await this.ppapiRequest("GET", connectorUrl);+ const runtimeUrl = connector.properties.primaryRuntimeUrl;+ if (!runtimeUrl) {+ throw new FlowApiError(400, "No runtime URL", `Connector ${connectorName} does not have a primaryRuntimeUrl.`, "");+ }+ const swagger = connector.properties.swagger;+ if (!swagger?.paths) {+ throw new FlowApiError(400, "No swagger", `Connector ${connectorName} does not have a swagger definition.`, "");+ }+ const allowedOps = this.collectDynamicOperationIds(swagger);+ if (!allowedOps.has(operationId)) {+ throw new FlowApiError(403, "Operation not allowed", `Operation "${operationId}" is not a dynamic value/schema/tree resolver. invoke-operation only supports operations referenced by x-ms-dynamic-values, x-ms-dynamic-tree, or x-ms-dynamic-schema. Allowed operations for this connector: ${[...allowedOps].join(", ") || "(none found)"}`, "");+ }+ let opMethod = "GET";+ let opPath = "";+ for (const [path3, methods] of Object.entries(swagger.paths)) {+ for (const [method, op] of Object.entries(methods)) {+ if (op.operationId === operationId) {+ opMethod = method.toUpperCase();+ opPath = path3;+ break;+ }+ }+ if (opPath)+ break;+ }+ if (!opPath) {+ throw new FlowApiError(404, "Operation not found", `Operation ${operationId} not found in connector ${connectorName} swagger.`, "");+ }+ let operationPath = opPath.replace(/^\/?{connectionId}\/?/, "");+ const opDef = swagger.paths[opPath][opMethod.toLowerCase()];+ const queryParamNames = /* @__PURE__ */ new Set();+ if (opDef?.parameters) {+ for (let p of opDef.parameters) {+ if (p.$ref && swagger.parameters) {+ const refName = p.$ref.replace("#/parameters/", "");+ if (swagger.parameters[refName])+ p = swagger.parameters[refName];+ }+ if (p.in === "query")+ queryParamNames.add(p.name);+ }+ }+ const queryParams = {};+ if (params) {+ for (const [key, val] of Object.entries(params)) {+ const placeholder = `{${key}}`;+ if (operationPath.includes(placeholder)) {+ operationPath = operationPath.replace(new RegExp(`\\{${key}\\}`, "g"), encodeURIComponent(String(val)));+ } else if (queryParamNames.has(key)) {+ queryParams[key] = String(val);+ }+ }+ }+ let invokeUrl = runtimeUrl.replace(/\/+$/, "") + "/" + connectionId + "/" + operationPath;+ if (Object.keys(queryParams).length > 0) {+ const qs2 = new URLSearchParams(queryParams).toString();+ invokeUrl += (invokeUrl.includes("?") ? "&" : "?") + qs2;+ }+ const apihubToken = await this.auth.getAccessToken(APIHUB_RESOURCE);+ return this.requestWithToken(opMethod, invokeUrl, apihubToken);+ }+ // --- PPAPI (PowerPlatform API) ---+ async searchOperations(envId, opts) {+ const base = this.ppapiBase(envId);+ const url = ppapiSearchOperationsUrl(base);+ const body = {};+ if (opts?.query)+ body.searchText = opts.query;+ if (opts?.connector)+ body.operationGroupName = opts.connector;+ const filter = opts?.filter ?? "all";+ if (filter === "actions") {+ body.allTagsToInclude = ["Action"];+ body.anyTagsToExclude = ["Deprecated", "Trigger"];+ } else if (filter === "triggers") {+ body.allTagsToInclude = ["Trigger"];+ body.anyTagsToExclude = ["Deprecated"];+ } else {+ body.anyTagsToExclude = ["Deprecated"];+ }+ const data = await this.ppapiRequest("POST", url, body);+ let results = data.value.map((item) => ({+ name: item.name,+ displayName: item.properties.summary,+ description: item.properties.description,+ type: item.properties.usage,+ connector: item.properties.operationGroup ? {+ name: item.properties.operationGroup.name,+ displayName: item.properties.operationGroup.displayName+ } : void 0+ }));+ if (opts?.top) {+ results = results.slice(0, opts.top);+ }+ return results;+ }+ async getOperationSchema(envId, connector, operation) {+ const base = this.ppapiBase(envId);+ const url = ppapiOperationSchemaUrl(base, connector, operation);+ return this.ppapiRequest("GET", url);+ }+ /**+ * Per-process cache of operation schemas. The same `getOperationSchema` call+ * costs ~1-2s and the schema doesn't change between agent turns. Keeps+ * `resolveParams` round-trips down for tight create-flow loops.+ */+ _opSchemaCache = /* @__PURE__ */ new Map();+ static OP_SCHEMA_TTL_MS = 5 * 60 * 1e3;+ async cachedOperationSchema(envId, connector, operation) {+ const key = `${envId}\0${connector}\0${operation}`;+ const hit = this._opSchemaCache.get(key);+ if (hit && Date.now() - hit.ts < _FlowClient.OP_SCHEMA_TTL_MS)+ return hit.schema;+ const schema = await this.getOperationSchema(envId, connector, operation);+ this._opSchemaCache.set(key, { ts: Date.now(), schema });+ return schema;+ }+ async getDynamicListValues(envId, connector, connection, extension, params) {+ const base = this.ppapiBase(envId);+ const url = ppapiListEnumUrl(base, connector, connection);+ const body = {+ dynamicInvocationDefinition: extension+ };+ if (params)+ body.parameters = params;+ return this.ppapiRequest("POST", url, body);+ }+ async getDynamicTreeValues(envId, connector, connection, extension, params, selection) {+ const base = this.ppapiBase(envId);+ const url = ppapiListTreeUrl(base, connector, connection);+ const body = {+ dynamicInvocationDefinition: extension+ };+ if (params)+ body.parameters = params;+ if (selection)+ body.selectionState = selection;+ return this.ppapiRequest("POST", url, body);+ }+ async getDynamicSchema(envId, connector, connection, extension, params, alias, location) {+ const base = this.ppapiBase(envId);+ const url = ppapiListDynamicPropertiesUrl(base, connector, connection);+ const body = {+ dynamicInvocationDefinition: extension+ };+ if (params)+ body.parameters = params;+ if (alias)+ body.contextParameterAlias = alias;+ if (location)+ body.location = location;+ return this.ppapiRequest("POST", url, body);+ }+ // --- Microsoft Graph ---+ async searchUsers(query, top = 10) {+ const url = graphUsersSearchUrl(query, top);+ const token = await this.auth.getAccessToken("https://graph.microsoft.com");+ const data = await this.requestWithToken("GET", url, token, void 0, { ConsistencyLevel: "eventual" });+ return data.value;+ }+ // --- PPAPI HTTP helper ---+ async ppapiRequest(method, url, body) {+ let lastError;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ try {+ const token = await this.auth.getAccessToken();+ return await this.requestWithToken(method, url, token, body);+ } catch (err) {+ lastError = err;+ if (err instanceof FlowApiError) {+ if (err.statusCode !== 429 && err.statusCode < 500) {+ throw err;+ }+ }+ if (attempt < MAX_RETRIES) {+ const delay2 = INITIAL_DELAY_MS * Math.pow(2, attempt);+ logger.warn(`PPAPI request failed (attempt ${attempt + 1}/${MAX_RETRIES + 1}), retrying in ${delay2}ms`);+ await new Promise((resolve2) => setTimeout(resolve2, delay2));+ }+ }+ }+ throw lastError;+ }+ /**+ * HTTP helper for /connectivity/ endpoints which require+ * audience=https://api.powerplatform.com (NOT the Flow service token).+ * Same retry logic as ppapiRequest.+ */+ async connectivityRequest(method, url, body) {+ let lastError;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ try {+ const token = await this.auth.getAccessToken(CONNECTIVITY_RESOURCE);+ return await this.requestWithToken(method, url, token, body);+ } catch (err) {+ lastError = err;+ if (!(err instanceof FlowApiError))+ throw err;+ if (err.statusCode !== 429 && err.statusCode < 500)+ throw err;+ if (attempt < MAX_RETRIES) {+ const delay2 = INITIAL_DELAY_MS * Math.pow(2, attempt);+ logger.warn(`Connectivity request failed (attempt ${attempt + 1}/${MAX_RETRIES + 1}), retrying in ${delay2}ms`);+ await new Promise((resolve2) => setTimeout(resolve2, delay2));+ }+ }+ }+ throw lastError;+ }+ /**+ * Scan all swagger paths/operations to collect operationIds that are+ * referenced as dynamic resolvers (x-ms-dynamic-values, x-ms-dynamic-tree,+ * x-ms-dynamic-schema, x-ms-dynamic-list).+ */+ collectDynamicOperationIds(swagger) {+ const ops = /* @__PURE__ */ new Set();+ const scan = (obj) => {+ if (!obj || typeof obj !== "object")+ return;+ const record2 = obj;+ for (const key of Object.keys(record2)) {+ if ((key === "x-ms-dynamic-values" || key === "x-ms-dynamic-tree" || key === "x-ms-dynamic-schema" || key === "x-ms-dynamic-list") && typeof record2[key] === "object" && record2[key] !== null) {+ this.extractDynOpIds(record2[key], ops);+ }+ if (typeof record2[key] === "object") {+ scan(record2[key]);+ }+ }+ };+ scan(swagger);+ return ops;+ }+ extractDynOpIds(dynObj, out) {+ if (typeof dynObj.operationId === "string") {+ out.add(dynObj.operationId);+ }+ for (const nested of ["open", "browse"]) {+ if (typeof dynObj[nested] === "object" && dynObj[nested] !== null) {+ const sub = dynObj[nested];+ if (typeof sub.operationId === "string") {+ out.add(sub.operationId);+ }+ }+ }+ }+ extractParameters(swaggerParams, out, swagger) {+ for (let p of swaggerParams) {+ if (p.$ref && swagger?.parameters) {+ const refName = p.$ref.replace("#/parameters/", "");+ const resolved = swagger.parameters[refName];+ if (resolved)+ p = resolved;+ }+ if (p.in === "body" && p.schema) {+ let schema = p.schema;+ if (schema.$ref && swagger?.definitions) {+ const defName = schema.$ref.replace("#/definitions/", "");+ const def = swagger.definitions[defName];+ if (def)+ schema = def;+ }+ const props = schema.properties;+ const required2 = schema.required ?? [];+ const defDynSchema = schema["x-ms-dynamic-schema"];+ if (props && Object.keys(props).length > 0) {+ for (const [propName, propDef] of Object.entries(props)) {+ const param = {+ name: `body/${propName}`,+ type: propDef.type ?? void 0,+ required: required2.includes(propName),+ description: propDef["x-ms-summary"] ?? propDef.description+ };+ const dynValues = propDef["x-ms-dynamic-values"];+ if (dynValues) {+ param.dynamicValues = {+ operationId: dynValues.operationId,+ parameters: dynValues.parameters+ };+ }+ const dynTree = propDef["x-ms-dynamic-tree"];+ if (dynTree) {+ param.dynamicTree = {+ open: dynTree.open ? {+ operationId: dynTree.open.operationId,+ parameters: dynTree.open.parameters+ } : void 0,+ browse: dynTree.browse ? {+ operationId: dynTree.browse.operationId,+ parameters: dynTree.browse.parameters+ } : void 0+ };+ }+ const dynSchema = propDef["x-ms-dynamic-schema"];+ if (dynSchema) {+ param.dynamicSchema = {+ operationId: dynSchema.operationId,+ parameters: dynSchema.parameters+ };+ }+ out.push(param);+ }+ } else if (defDynSchema) {+ out.push({+ name: p.name ?? "body",+ required: p.required,+ description: p["x-ms-summary"] ?? p.description,+ dynamicSchema: {+ operationId: defDynSchema.operationId,+ parameters: defDynSchema.parameters+ }+ });+ } else {+ out.push({+ name: p.name ?? "body",+ required: p.required,+ description: p["x-ms-summary"] ?? p.description+ });+ }+ } else {+ const param = {+ name: p.name,+ type: p.type,+ required: p.required,+ description: p["x-ms-summary"] ?? p.description+ };+ if (p["x-ms-dynamic-values"]) {+ param.dynamicValues = {+ operationId: p["x-ms-dynamic-values"].operationId,+ parameters: p["x-ms-dynamic-values"].parameters+ };+ }+ if (p["x-ms-dynamic-tree"]) {+ param.dynamicTree = {+ open: p["x-ms-dynamic-tree"].open ? {+ operationId: p["x-ms-dynamic-tree"].open.operationId,+ parameters: p["x-ms-dynamic-tree"].open.parameters+ } : void 0,+ browse: p["x-ms-dynamic-tree"].browse ? {+ operationId: p["x-ms-dynamic-tree"].browse.operationId,+ parameters: p["x-ms-dynamic-tree"].browse.parameters+ } : void 0+ };+ }+ if (p["x-ms-dynamic-schema"]) {+ param.dynamicSchema = {+ operationId: p["x-ms-dynamic-schema"].operationId,+ parameters: p["x-ms-dynamic-schema"].parameters+ };+ }+ out.push(param);+ }+ }+ }+ // --- PPAPI Connections ---+ async getConnections(envId, opts) {+ const url = ppapiConnectionsUrl(envId, opts);+ const data = await this.connectivityRequest("GET", url);+ return data.value;+ }+ /**+ * Auto-discover connections for a list of connectors and return a+ * connectionReferences-shaped object ready to drop into a flow definition.+ *+ * Strategy (mirrors `commands/connections.ts::resolveRefs`):+ * 1. Single Dataverse `listConnections` call (most reliable auth).+ * 2. For connectors not found in Dataverse, parallel PPAPI lookups.+ * 3. Prefer `Connected` status; fall back to first connection; record a+ * placeholder + actionable error if no connection exists.+ *+ * This is the single source of truth — the CLI `resolve-refs` command and+ * the MCP `resolve_refs` tool both call this.+ */+ async resolveConnectionRefs(envId, connectorNames) {+ const refs = {};+ let dvConnections = [];+ try {+ dvConnections = await this.listConnections(envId);+ } catch {+ }+ const ppapiNeeded = [];+ for (const connector of connectorNames) {+ const dvMatch = dvConnections.find((c) => c.connectorid === `/providers/Microsoft.PowerApps/apis/${connector}`);+ if (dvMatch?.connectionid) {+ const ref = {+ connectionName: dvMatch.connectionid,+ source: "Embedded",+ id: `/providers/Microsoft.PowerApps/apis/${connector}`,+ tier: "NotSpecified"+ };+ if (dvMatch.connectionreferencelogicalname) {+ ref.connectionReferenceLogicalName = dvMatch.connectionreferencelogicalname;+ }+ refs[connector] = ref;+ } else {+ ppapiNeeded.push(connector);+ }+ }+ if (ppapiNeeded.length === 0)+ return refs;+ const results = await Promise.allSettled(ppapiNeeded.map(async (connector) => {+ const connections = await this.getConnections(envId, { connector });+ return { connector, connections };+ }));+ for (const result of results) {+ if (result.status === "fulfilled") {+ const { connector, connections } = result.value;+ const connected = connections.find((c) => c.properties?.statuses?.some((s) => s.status === "Connected"));+ const id = `/providers/Microsoft.PowerApps/apis/${connector}`;+ if (connected) {+ refs[connector] = { connectionName: connected.name, source: "Embedded", id, tier: "NotSpecified" };+ } else if (connections.length > 0) {+ refs[connector] = { connectionName: connections[0].name, source: "Embedded", id, tier: "NotSpecified" };+ } else {+ refs[connector] = {+ connectionName: `NO_CONNECTION_FOUND_FOR_${connector}`,+ source: "Embedded",+ id,+ tier: "NotSpecified",+ _error: `No connection found for ${connector}. Create one with: create-connection --env=... --connector=${connector}`+ };+ }+ } else {+ const connector = ppapiNeeded[results.indexOf(result)];+ refs[connector] = {+ connectionName: `LOOKUP_FAILED_FOR_${connector}`,+ source: "Embedded",+ id: `/providers/Microsoft.PowerApps/apis/${connector}`,+ tier: "NotSpecified",+ _error: `Could not query connections for ${connector}: ${result.reason?.message ?? String(result.reason)}`+ };+ }+ }+ return refs;+ }+ /**+ * Idempotent "get me a Connected connectionName for this connector."+ * Removes the "no connection? now what?" dead end that the eval (E9)+ * identified as the single biggest L0 agent blocker.+ *+ * Strategy:+ * 1. Reuse `resolveConnectionRefs([connector])` (Dataverse first, PPAPI+ * fallback — handles F5 Dataverse-only envs).+ * 2. If a real `connectionName` came back (not a NO_CONNECTION_FOUND_FOR_*+ * or LOOKUP_FAILED_FOR_* placeholder), verify it is `Connected` via+ * `getConnection`. Return it.+ * 3. If no connection exists OR the existing one is not Connected and+ * `mode === "find-or-create"`, call `createConnection` — which prefers+ * first-party silent auth for M365 connectors (no browser pop) and+ * falls back to browser consent for non-first-party OAuth.+ * 4. Return a structured discriminator: `{mode, connectionName, status,+ * authMode, connector}` so the agent can branch on it.+ */+ async pickOrCreateConnection(envId, connector, opts = {}) {+ const mode = opts.mode ?? "find-or-create";+ let refs = {};+ if (mode !== "create-only") {+ refs = await this.resolveConnectionRefs(envId, [connector]);+ }+ const ref = refs[connector];+ const rawName = ref?.connectionName;+ const isPlaceholder = !rawName || rawName.startsWith("NO_CONNECTION_FOUND_FOR_") || rawName.startsWith("LOOKUP_FAILED_FOR_");+ if (!isPlaceholder && mode !== "create-only") {+ try {+ const conn = await this.getConnection(envId, connector, rawName);+ const statuses2 = conn.properties?.statuses ?? [];+ const connected2 = statuses2.some((s) => s.status === "Connected");+ const refPath = typeof ref?.connectionReferenceLogicalName === "string" ? "dataverse" : "ppapi";+ if (connected2) {+ return {+ mode: "found",+ connectionName: rawName,+ status: "Connected",+ authMode: "unknown",+ // we don't know how it was originally auth'd+ connector,+ refSourcePath: refPath,+ statuses: statuses2+ };+ }+ if (mode === "find-only") {+ return {+ mode: "found-not-connected",+ connectionName: rawName,+ status: statuses2[0]?.status ?? "Unknown",+ authMode: "unknown",+ connector,+ refSourcePath: refPath,+ statuses: statuses2,+ _error: "Connection exists but is not Connected. Re-run with mode=find-or-create or call fix-connection."+ };+ }+ } catch (err) {+ if (mode === "find-only") {+ return {+ mode: "found-not-connected",+ connectionName: rawName,+ status: "NotFound",+ authMode: "unknown",+ connector,+ refSourcePath: "ppapi",+ _error: err instanceof Error ? err.message : String(err)+ };+ }+ }+ }+ if (mode === "find-only") {+ return {+ mode: "no-connection-and-create-disabled",+ connectionName: "",+ status: "NotFound",+ authMode: "no-auth-required",+ connector,+ refSourcePath: "ppapi",+ _error: `No connection found for ${connector}. Re-run with mode=find-or-create to auto-create.`+ };+ }+ const created = await this.createConnection(envId, connector, opts);+ const statuses = created.properties?.statuses ?? [];+ const connected = statuses.some((s) => s.status === "Connected");+ const authMode = (() => {+ if (statuses.length === 0)+ return "no-auth-required";+ const silentConnectors = /* @__PURE__ */ new Set([+ "shared_teams",+ "shared_office365",+ "shared_office365users",+ "shared_office365groups",+ "shared_sharepointonline",+ "shared_onedriveforbusiness",+ "shared_approvals",+ "shared_commondataservice",+ "shared_commondataserviceforapps",+ "shared_planner",+ "shared_outlook",+ "shared_excelonlinebusiness"+ ]);+ if (silentConnectors.has(connector))+ return "silent";+ return "browser-consent";+ })();+ return {+ mode: "created",+ connectionName: created.name ?? "",+ status: connected ? "Connected" : statuses[0]?.status ?? "Pending",+ authMode,+ connector,+ refSourcePath: "created",+ statuses,+ ...connected ? {} : { _error: `Connection created but not yet Connected. Run: fix-connection --connector=${connector} --connection=${created.name}` }+ };+ }+ /**+ * Designer-emulating "resolve every dropdown an operation needs in one+ * call" — the eval (E10) flagged this as the single biggest leverage for+ * "create-a-flow-with-several-connector-actions". Replaces N round-trips+ * of getDynamicList/Tree/Schema with one.+ *+ * Design notes baked in from E10 / F5:+ * - Connection auto-discovery via `pickOrCreateConnection({mode: "find-only"})`+ * if no `connection` passed (handles F5 Dataverse-only envs).+ * - Schema cached per session (5 min TTL) — the 1-2s schema fetch was a+ * big chunk of E10's 8-15s baseline.+ * - All dropdowns resolved in parallel (Promise.allSettled).+ * - Per-dropdown errors are returned as `error` on that param's entry,+ * NOT thrown — the eval saw 3/3 dropdowns error in some operations;+ * we still want to return the params we did resolve.+ */+ async resolveParams(envId, connector, operation, opts = {}, progress2) {+ let connection = opts.connection;+ let connectionSource = "provided";+ if (!connection) {+ await progress2?.send(0, 100, `Discovering connection for ${connector}\u2026`);+ const picked = await this.pickOrCreateConnection(envId, connector, { mode: "find-only" });+ if (picked.mode === "found" || picked.mode === "found-not-connected") {+ connection = picked.connectionName;+ connectionSource = picked.refSourcePath === "dataverse" ? "resolved-dataverse" : "resolved-ppapi";+ } else {+ return {+ connector,+ operation,+ connection: "",+ connectionSource: "not-found",+ parameters: [],+ _summary: { total: 0, withValues: 0, errored: 0, static: 0 }+ };+ }+ }+ await progress2?.send(10, 100, `Fetching schema ${connector}/${operation}\u2026`);+ const opSchema = await this.cachedOperationSchema(envId, connector, operation);+ const inputsDef = opSchema.properties?.inputsDefinition;+ const paramDefs = inputsDef?.properties ?? inputsDef?.parameters ?? {};+ const requiredParams = inputsDef?.required ?? [];+ const paramEntries = Object.entries(paramDefs);+ const total = paramEntries.length;+ const tasks = paramEntries.map(async ([paramName, paramDef], idx) => {+ const title = paramDef["title"] ?? paramDef["x-ms-summary"];+ const required2 = requiredParams.includes(paramName) || paramDef["required"];+ const type = paramDef["type"];+ const dynList = paramDef["x-ms-dynamic-list"];+ const dynValues = paramDef["x-ms-dynamic-values"];+ const dynTree = paramDef["x-ms-dynamic-tree"];+ const dynProps = paramDef["x-ms-dynamic-properties"];+ try {+ if (dynList || dynValues) {+ const extension = dynList ?? dynValues;+ await progress2?.send(20 + Math.floor(idx / total * 70), 100, `Resolving dropdown: ${paramName}\u2026`);+ const listResult = await this.getDynamicListValues(envId, connector, connection, extension, opts.currentInputs);+ return {+ name: paramName,+ title,+ required: required2,+ type,+ dynamicType: "dropdown",+ values: listResult.value.map((v) => ({ value: v.value, displayName: v.displayName }))+ };+ }+ if (dynTree) {+ await progress2?.send(20 + Math.floor(idx / total * 70), 100, `Resolving tree: ${paramName}\u2026`);+ const treeResult = await this.getDynamicTreeValues(envId, connector, connection, dynTree, opts.currentInputs);+ return {+ name: paramName,+ title,+ required: required2,+ type,+ dynamicType: "tree",+ values: treeResult.value.map((v) => ({+ value: v.value,+ displayName: `${v.displayName}${v.isParent ? " (folder)" : ""}`+ }))+ };+ }+ if (dynProps) {+ return {+ name: paramName,+ title,+ required: required2,+ type,+ dynamicType: "dynamic-schema",+ _hint: "Schema depends on other parameter values. Pass concrete values for parent params via currentInputs to resolve.",+ values: [{ value: dynProps, displayName: "(dynamic \u2014 resolves at runtime based on other params)" }]+ };+ }+ const enumValues = paramDef["enum"];+ const enumDisplays = paramDef["x-ms-enum-values"];+ return {+ name: paramName,+ title,+ required: required2,+ type,+ dynamicType: enumValues ? "enum" : "static",+ values: enumDisplays ?? enumValues?.map((v) => ({ value: v, displayName: String(v) }))+ };+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ let hint = "Try passing concrete values for any parent parameters via currentInputs.";+ if (msg.includes("BadRequest"))+ hint = "Required parent parameter likely missing. Inspect the dynamic-list definition.";+ else if (msg.includes("Forbidden") || msg.includes("403"))+ hint = "Connection lacks permission. Try fix-connection.";+ else if (msg.includes("NotFound") || msg.includes("404"))+ hint = "Backing resource missing. Check parent param values.";+ return {+ name: paramName,+ title,+ required: required2,+ type,+ dynamicType: dynTree ? "tree" : "dropdown",+ error: msg,+ _hint: hint+ };+ }+ });+ const resolved = await Promise.all(tasks);+ await progress2?.send(100, 100, `Resolved ${resolved.length} params for ${connector}/${operation}`);+ const _summary = {+ total: resolved.length,+ withValues: resolved.filter((r) => r.values && r.values.length > 0).length,+ errored: resolved.filter((r) => r.error).length,+ static: resolved.filter((r) => r.dynamicType === "static" || r.dynamicType === "enum").length+ };+ return {+ connector,+ operation,+ connection,+ connectionSource,+ parameters: resolved,+ _summary+ };+ }+ async getConnection(envId, connector, connName) {+ const url = ppapiConnectionUrl(envId, connector, connName);+ return this.connectivityRequest("GET", url);+ }+ async createConnection(envId, connector, opts) {+ const safeName = connector.replace(/_/g, "-").slice(0, 20);+ const connName = `${safeName}-${randomUUID2().slice(0, 8)}`;+ logger.info(`Creating connection '${connName}' for connector '${connector}'\u2026`);+ const createUrl = ppapiConnectionUrl(envId, connector, connName);+ const createBody = {+ properties: {+ connectionParameters: opts?.params ?? {},+ environment: { name: envId }+ }+ };+ const connection = await this.connectivityRequest("PUT", createUrl, createBody);+ const isConnected = connection.properties?.statuses?.some((s) => s.status === "Connected");+ if (isConnected) {+ logConnectionSuccess(connection, connName, connector, "no-auth-required");+ return connection;+ }+ const authed = await this.authenticateConnection(envId, connector, connName, connection, opts);+ const finallyConnected = authed.properties?.statuses?.some((s) => s.status === "Connected");+ if (finallyConnected) {+ const mode = authed.properties?.firstExpirationTime ? "oauth-consent" : "first-party-silent";+ logConnectionSuccess(authed, connName, connector, mode);+ } else {+ logger.info(`Connection '${connName}' created but not yet authenticated. Status: ${(authed.properties?.statuses ?? []).map((s) => s.status).join(", ") || "Unknown"}. Run: flowagent fix-connection --env=${envId} --connector=${connector} --connection=${connName}`);+ }+ return authed;+ }+ async testConnection(envId, connector, connName) {+ const connection = await this.getConnection(envId, connector, connName);+ const statuses = connection.properties?.statuses ?? [];+ const connected = statuses.some((s) => s.status === "Connected");+ return { connected, statuses, connection };+ }+ async fixConnection(envId, connector, connName, opts) {+ const connection = await this.getConnection(envId, connector, connName);+ const isConnected = connection.properties?.statuses?.some((s) => s.status === "Connected");+ if (isConnected) {+ logger.info("Connection is already authenticated.");+ return connection;+ }+ return this.authenticateConnection(envId, connector, connName, connection, opts);+ }+ async deleteConnection(envId, connector, connName) {+ const url = ppapiConnectionUrl(envId, connector, connName);+ await this.connectivityRequest("DELETE", url);+ }+ async getConnectionPermissions(envId, connector, connName) {+ const url = ppapiConnectionPermissionsUrl(envId, connector, connName);+ const data = await this.connectivityRequest("GET", url);+ return data.value;+ }+ async shareConnection(envId, connector, connName, principalId, roleName, principalType) {+ const url = ppapiConnectionModifyPermissionsUrl(envId, connector, connName);+ const body = {+ put: [+ {+ properties: {+ roleName,+ principal: {+ id: principalId,+ type: principalType ?? "User"+ }+ }+ }+ ]+ };+ await this.connectivityRequest("POST", url, body);+ }+ async unshareConnection(envId, connector, connName, permissionId) {+ const url = ppapiConnectionModifyPermissionsUrl(envId, connector, connName);+ await this.connectivityRequest("POST", url, { delete: [{ id: permissionId }] });+ }+ async updateConnection(envId, connector, connName, opts) {+ const current = await this.getConnection(envId, connector, connName);+ const url = ppapiConnectionUrl(envId, connector, connName);+ const body = {+ properties: {+ ...current.properties,+ ...opts.displayName !== void 0 ? { displayName: opts.displayName } : {},+ ...opts.params !== void 0 ? { connectionParameters: opts.params } : {},+ environment: { name: envId }+ }+ };+ return this.connectivityRequest("PUT", url, body);+ }+ async authenticateConnection(envId, connector, connName, fallbackConnection, opts) {+ try {+ const consentUrl = ppapiConnectionConsentUrl(envId, connector, connName);+ const consent = await this.connectivityRequest("POST", consentUrl, { redirectUrl: "https://make.powerautomate.com" });+ if (consent.firstPartyLoginUri) {+ logger.info("Authenticating connection (first-party silent auth)...");+ const apihubToken = await this.auth.getAccessToken(APIHUB_RESOURCE);+ await this.requestWithToken("POST", consent.firstPartyLoginUri, apihubToken, { accessToken: apihubToken });+ const conn = await this.getConnection(envId, connector, connName);+ const connected = conn.properties?.statuses?.some((s) => s.status === "Connected");+ if (connected) {+ logger.info("Connection authenticated successfully.");+ return conn;+ }+ logger.debug("Silent auth completed but connection not yet Connected, trying browser consent...");+ }+ if (consent.consentLink) {+ if (opts?.noBrowser) {+ logger.info(`Consent URL (open manually): ${consent.consentLink}`);+ } else {+ logger.info("Opening browser for OAuth consent...");+ this.openBrowser(consent.consentLink);+ }+ return this.pollConnectionStatus(envId, connector, connName, 12e4);+ }+ } catch (err) {+ logger.debug(`Consent link request failed (connector may not require OAuth): ${err}`);+ }+ return fallbackConnection;+ }+ openBrowser(url) {+ const platform = process.platform;+ let cmd;+ let args;+ if (platform === "win32") {+ cmd = "cmd";+ args = ["/c", "start", "", url];+ } else if (platform === "darwin") {+ cmd = "open";+ args = [url];+ } else {+ cmd = "xdg-open";+ args = [url];+ }+ execFile(cmd, args, (err) => {+ if (err) {+ logger.warn(`Failed to open browser: ${err.message}`);+ logger.info(`Open this URL manually: ${url}`);+ }+ });+ }+ async pollConnectionStatus(envId, connector, connName, timeoutMs) {+ const start = Date.now();+ const pollInterval = 3e3;+ logger.info("Waiting for OAuth consent in browser...");+ while (Date.now() - start < timeoutMs) {+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));+ try {+ const conn = await this.getConnection(envId, connector, connName);+ const connected = conn.properties?.statuses?.some((s) => s.status === "Connected");+ if (connected) {+ logger.info("Connection authenticated successfully.");+ return conn;+ }+ } catch (err) {+ logger.debug(`Poll check failed (will retry): ${err}`);+ }+ }+ logger.warn(`OAuth consent not completed within ${timeoutMs / 1e3}s. Connection "${connName}" created but not authenticated.`);+ return this.getConnection(envId, connector, connName);+ }+ // --- Environment details ---+ async getEnvironment(envId) {+ const base = this.ppapiBase(envId);+ const url = `${base}/powerautomate${this.ppapiFlowQs({})}`;+ return this.ppapiRequest("GET", url);+ }+ // --- Connections (via Dataverse) ---+ async listConnections(envId, opts) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseConnectionReferencesUrl(instanceUrl, opts);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ // --- Solutions (Dataverse) ---+ /**+ * Resolve a flow's solution-membership and managed status from Dataverse.+ *+ * The PPAPI `flowId` is the published `workflowid` in Dataverse. We look+ * that up first; if found AND it has a `_solutionid_value`, we expand+ * the solution row to read `ismanaged` / `uniquename` / `friendlyname`.+ *+ * Returns a `warning` field with a reason code when the lookup couldn't+ * complete (no-dataverse-instance, workflow-not-found, dataverse-error).+ * Callers should treat `warning != null` as "no solution context" and+ * fall through to non-solution code paths.+ */+ async getFlowContext(envId, flowId) {+ let ppapiFlow = null;+ try {+ ppapiFlow = await this.getFlow(envId, flowId);+ } catch (err) {+ logger.debug(`getFlowContext: PPAPI getFlow failed: ${err}`);+ }+ const ctx = {+ flowId,+ displayName: ppapiFlow?.properties.displayName,+ workflowId: null,+ workflowIdUnique: null,+ inSolution: false,+ solutionId: null,+ solutionUniqueName: null,+ solutionFriendlyName: null,+ isManaged: false,+ workflowIsManaged: false,+ isCustomizable: true,+ category: null,+ ownerId: null,+ connectionReferenceLogicalNames: extractLogicalNamesFromFlow(ppapiFlow),+ warning: null+ };+ let instanceUrl;+ try {+ instanceUrl = await this.getDataverseInstanceUrl(envId);+ } catch {+ ctx.warning = "no-dataverse-instance";+ return ctx;+ }+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ let workflow = null;+ try {+ const url = dataverseWorkflowUrl(instanceUrl, flowId);+ workflow = await this.dataverseGet(url, dvToken);+ } catch (err) {+ if (err?.statusCode === 404) {+ try {+ const fbUrl = dataverseWorkflowByUniqueUrl(instanceUrl, flowId);+ const list = await this.dataverseGet(fbUrl, dvToken);+ if (list.value && list.value.length > 0) {+ workflow = list.value[0];+ } else {+ ctx.warning = "workflow-not-found";+ return ctx;+ }+ } catch (fbErr) {+ if (fbErr?.statusCode === 404) {+ ctx.warning = "workflow-not-found";+ } else {+ ctx.warning = "dataverse-error";+ logger.debug(`getFlowContext: dataverse workflowidunique fallback failed: ${fbErr}`);+ }+ return ctx;+ }+ } else {+ ctx.warning = "dataverse-error";+ logger.debug(`getFlowContext: dataverse workflow lookup failed: ${err}`);+ return ctx;+ }+ }+ if (!workflow) {+ ctx.warning = "workflow-not-found";+ return ctx;+ }+ ctx.workflowId = workflow.workflowid ?? null;+ ctx.workflowIdUnique = workflow.workflowidunique ?? null;+ ctx.workflowIsManaged = !!workflow.ismanaged;+ ctx.category = typeof workflow.category === "number" ? workflow.category : null;+ ctx.ownerId = workflow._ownerid_value ?? null;+ const iscust = workflow.iscustomizable;+ ctx.isCustomizable = typeof iscust === "boolean" ? iscust : !!(iscust && iscust.Value);+ const solutionId = workflow.solutionid ?? null;+ if (!solutionId) {+ ctx.inSolution = false;+ return ctx;+ }+ ctx.inSolution = true;+ ctx.solutionId = solutionId;+ try {+ const url = dataverseSolutionByIdUrl(instanceUrl, solutionId);+ const sol = await this.dataverseGet(url, dvToken);+ ctx.solutionUniqueName = sol.uniquename ?? null;+ ctx.solutionFriendlyName = sol.friendlyname ?? null;+ ctx.isManaged = !!sol.ismanaged;+ } catch (err) {+ logger.debug(`getFlowContext: solution lookup failed: ${err}`);+ ctx.isManaged = ctx.workflowIsManaged;+ }+ return ctx;+ }+ /**+ * Refuse a mutating operation if the target flow lives inside a managed+ * Dataverse solution, unless the caller explicitly opted in with+ * forceManaged: true.+ *+ * Fail-open policy for context-resolution warnings: if Dataverse is+ * unreachable or the workflow row cannot be found, the guard does NOT+ * block the operation — it logs a warn and lets the call proceed. This+ * matches existing FlowAgent semantics where a missing Dataverse instance+ * does not block PPAPI-only flows.+ *+ * Used by: updateFlow, deleteFlow, publishFlow, disableFlow, shareFlow,+ * unshareFlow.+ */+ async assertNotManaged(envId, flowId, operation, opts) {+ if (opts?.forceManaged) {+ logger.warn(`[managed-guard] ${operation} on ${flowId}: forceManaged=true, skipping managed-solution check`);+ return;+ }+ let ctx;+ try {+ ctx = await this.getFlowContext(envId, flowId);+ } catch (err) {+ logger.warn(`[managed-guard] ${operation} on ${flowId}: context lookup failed (${err instanceof Error ? err.message : String(err)}); allowing operation`);+ return;+ }+ if (ctx.warning) {+ logger.debug(`[managed-guard] ${operation} on ${flowId}: context warning "${ctx.warning}", allowing operation (fail-open)`);+ return;+ }+ if (ctx.isManaged) {+ throw new ManagedSolutionError(operation, flowId, ctx.solutionUniqueName, ctx.solutionFriendlyName);+ }+ }+ /**+ * Capture a backup snapshot before a destructive operation. Best-effort:+ * snapshot failures are logged but never block the operation. Callers may+ * pass `skipBackup: true` to opt out (e.g. in test code).+ */+ async snapshotBeforeMutation(envId, flowId, operation, opts) {+ if (opts?.skipBackup)+ return;+ try {+ const flow = await this.getFlow(envId, flowId);+ let context = void 0;+ try {+ context = await this.getFlowContext(envId, flowId);+ } catch {+ }+ snapshot({+ envId,+ flowId,+ operation,+ flow,+ context,+ note: opts?.backupNote+ });+ } catch (err) {+ logger.warn(`[backup] ${operation} on ${flowId}: could not capture pre-mutation snapshot (${err instanceof Error ? err.message : String(err)}); proceeding anyway`);+ }+ }+ async listSolutions(envId) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseSolutionsUrl(instanceUrl);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ async listSolutionFlows(envId, solutionId) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseSolutionFlowsUrl(instanceUrl, solutionId);+ const data = await this.dataverseGet(url, dvToken);+ return data.value;+ }+ async exportSolution(envId, uniqueName, managed) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseExportSolutionUrl(instanceUrl);+ const data = await this.dataversePost(url, {+ SolutionName: uniqueName,+ Managed: managed+ }, dvToken);+ return data.ExportSolutionFile;+ }+ async importSolution(envId, base64Zip, overwrite) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = dataverseImportSolutionUrl(instanceUrl);+ await this.dataversePost(url, {+ CustomizationFile: base64Zip,+ OverwriteUnmanagedCustomizations: overwrite,+ PublishWorkflows: true+ }, dvToken);+ }+ // --- Flow Sharing (Dataverse) ---+ async shareFlow(envId, flowId, principalId, role, opts = {}) {+ await this.assertNotManaged(envId, flowId, "share_flow", opts);+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = `${instanceUrl.replace(/\/+$/, "")}/api/data/v9.2/GrantAccess`;+ const accessMask = role === "co-owner" ? "ReadAccess,WriteAccess,DeleteAccess" : "ReadAccess";+ await this.dataversePost(url, {+ Target: {+ workflowid: flowId,+ "@odata.type": "Microsoft.Dynamics.CRM.workflow"+ },+ PrincipalAccess: {+ Principal: {+ systemuserid: principalId,+ "@odata.type": "Microsoft.Dynamics.CRM.systemuser"+ },+ AccessMask: accessMask+ }+ }, dvToken);+ }+ async unshareFlow(envId, flowId, principalId, opts = {}) {+ await this.assertNotManaged(envId, flowId, "unshare_flow", opts);+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = `${instanceUrl.replace(/\/+$/, "")}/api/data/v9.2/RevokeAccess`;+ await this.dataversePost(url, {+ Target: {+ workflowid: flowId,+ "@odata.type": "Microsoft.Dynamics.CRM.workflow"+ },+ Revokee: {+ systemuserid: principalId,+ "@odata.type": "Microsoft.Dynamics.CRM.systemuser"+ }+ }, dvToken);+ }+ async getFlowPermissions(envId, flowId) {+ const instanceUrl = await this.getDataverseInstanceUrl(envId);+ const dvToken = await this.auth.getAccessToken(instanceUrl);+ const url = `${instanceUrl.replace(/\/+$/, "")}/api/data/v9.2/RetrieveSharedPrincipalsAndAccess(Target=@t)?@t={'@odata.id':'workflows(${flowId})'}`;+ const data = await this.dataverseGet(url, dvToken);+ return data.PrincipalAccesses;+ }+ // --- Admin Flows (Flow RP Admin API) ---+ // Admin operations use Flow RP because PPAPI does not have admin-scoped equivalents.+ // These require Power Platform Admin or Global Admin Azure AD role.+ // When PPAPI adds admin endpoints, migrate these methods.+ async adminListFlows(envId, opts) {+ const url = adminFlowsUrl(this.config.baseUrl, envId, opts);+ const data = await this.get(url);+ return data.value;+ }+ async adminGetFlow(envId, flowId) {+ const url = adminFlowUrl(this.config.baseUrl, envId, flowId);+ return this.get(url);+ }+ async adminRestoreFlow(envId, flowId) {+ const url = adminFlowRestoreUrl(this.config.baseUrl, envId, flowId);+ await this.post(url);+ }+ async adminGetFlowPermissions(envId, flowId) {+ const url = adminFlowPermissionsUrl(this.config.baseUrl, envId, flowId);+ return this.get(url);+ }+ async adminModifyFlowPermissions(envId, flowId, body) {+ const url = adminFlowModifyPermissionsUrl(this.config.baseUrl, envId, flowId);+ await this.post(url, body);+ }+ // --- Dataverse HTTP ---+ async dataverseGet(url, token) {+ logger.debug(`GET ${url}`);+ const response = await fetch(url, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ "OData-MaxVersion": "4.0",+ "OData-Version": "4.0"+ }+ });+ if (!response.ok) {+ const body = await response.text();+ throw new FlowApiError(response.status, response.statusText, body, url);+ }+ return await response.json();+ }+ async dataversePost(url, body, token) {+ logger.debug(`POST ${url}`);+ const response = await fetch(url, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/json; charset=utf-8",+ Accept: "application/json",+ "OData-MaxVersion": "4.0",+ "OData-Version": "4.0"+ },+ body: JSON.stringify(body)+ });+ if (!response.ok) {+ const text2 = await response.text();+ throw new FlowApiError(response.status, response.statusText, text2, url);+ }+ const text = await response.text();+ if (!text)+ return void 0;+ return JSON.parse(text);+ }+ // --- HTTP primitives ---+ async get(url) {+ return this.request("GET", url);+ }+ async post(url, body) {+ return this.request("POST", url, body);+ }+ async patch(url, body) {+ return this.request("PATCH", url, body);+ }+ async delete(url) {+ await this.request("DELETE", url);+ }+ async requestWithToken(method, url, token, body, extraHeaders) {+ const headers = {+ Authorization: `Bearer ${token}`,+ Accept: "application/json",+ ...extraHeaders+ };+ if (body !== void 0) {+ headers["Content-Type"] = "application/json";+ }+ logger.debug(`${method} ${url}`);+ const response = await fetch(url, {+ method,+ headers,+ body: body !== void 0 ? JSON.stringify(body) : void 0+ });+ if (!response.ok) {+ const responseBody = await response.text();+ throw new FlowApiError(response.status, response.statusText, responseBody, url);+ }+ if (response.status === 204 || response.headers.get("content-length") === "0") {+ return void 0;+ }+ const text = await response.text();+ if (!text) {+ return void 0;+ }+ return JSON.parse(text);+ }+ async request(method, url, body) {+ let lastError;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ try {+ const token = await this.auth.getAccessToken();+ const headers = {+ Authorization: `Bearer ${token}`,+ Accept: "application/json"+ };+ if (body !== void 0) {+ headers["Content-Type"] = "application/json";+ }+ logger.debug(`${method} ${url}`);+ const response = await fetch(url, {+ method,+ headers,+ body: body !== void 0 ? JSON.stringify(body) : void 0+ });+ if (!response.ok) {+ const responseBody = await response.text();+ throw new FlowApiError(response.status, response.statusText, responseBody, url);+ }+ if (response.status === 204 || response.headers.get("content-length") === "0") {+ return void 0;+ }+ const text = await response.text();+ if (!text) {+ return void 0;+ }+ return JSON.parse(text);+ } catch (err) {+ lastError = err;+ if (err instanceof FlowApiError) {+ if (err.statusCode !== 429 && err.statusCode < 500) {+ throw err;+ }+ }+ if (attempt < MAX_RETRIES) {+ const delay2 = INITIAL_DELAY_MS * Math.pow(2, attempt);+ logger.warn(`Request failed (attempt ${attempt + 1}/${MAX_RETRIES + 1}), retrying in ${delay2}ms`);+ await new Promise((resolve2) => setTimeout(resolve2, delay2));+ }+ }+ }+ throw lastError;+ }+};+function connectorFromRef(refKey, ref) {+ const id = typeof ref?.id === "string" ? ref.id : void 0;+ if (id) {+ const marker = "/apis/";+ const idx = id.lastIndexOf(marker);+ if (idx >= 0) {+ const tail = id.slice(idx + marker.length).split("/")[0];+ if (tail)+ return tail;+ }+ }+ return refKey;+}+function remediateActionError(code, message) {+ const c = (code ?? "").toLowerCase();+ const m = (message ?? "").toLowerCase();+ if (c.includes("unauthorized") || c === "401" || m.includes("unauthorized") || m.includes("token")) {+ return "Connection auth expired or insufficient. Re-authenticate the connection (fix_connection) and confirm it is Connected.";+ }+ if (c.includes("forbidden") || c === "403" || m.includes("forbidden") || m.includes("permission")) {+ return "The caller lacks permission, or a DLP policy blocks the connector. Verify the connection identity's access and tenant DLP groups.";+ }+ if (c.includes("notfound") || c === "404") {+ return "A referenced resource (item, list, table, record) was not found. Check the IDs/paths in the action inputs \u2014 they may be stale after an env copy.";+ }+ if (c.includes("badrequest") || c === "400" || m.includes("invalid")) {+ return "The action inputs were rejected. Re-check required parameters and expression outputs feeding this action (inspect inputsLink).";+ }+ if (c.includes("toomanyrequests") || c === "429" || m.includes("throttl") || m.includes("rate limit")) {+ return "The connector throttled the request. Add a concurrency limit or retry policy, or reduce call volume; consider Process capacity for high-throughput flows.";+ }+ if (c.includes("timeout") || c === "504" || m.includes("timed out")) {+ return "The action timed out. Check the downstream service, increase the action timeout, or split long-running work.";+ }+ if (c.includes("actionfailed") || m.includes("dependent action")) {+ return "This action failed because an upstream action it depends on failed. Diagnose the first failing action in the run.";+ }+ if (c.includes("serviceunavailable") || c === "503" || c === "500" || c.includes("internalserver")) {+ return "The downstream service returned a server error. Often transient \u2014 resubmit the run; if persistent, check the connector's service health.";+ }+ return message ? "Inspect the action's inputs/outputs (inputsLink/outputsLink) and the connector docs for this error." : "No error message captured. Re-run with get_run_actions to inspect the action's inputs/outputs.";+}+function toSnapshot(flow) {+ const p = flow.properties ?? {};+ return {+ displayName: typeof p.displayName === "string" ? p.displayName : void 0,+ state: typeof p.state === "string" ? p.state : void 0,+ definition: p.definition ?? {},+ connectionReferences: p.connectionReferences ?? {}+ };+}+function mergeProposal(current, body) {+ const props = body.properties ?? {};+ return {+ displayName: typeof props.displayName === "string" ? props.displayName : current.displayName,+ state: typeof props.state === "string" ? props.state : current.state,+ definition: props.definition ?? current.definition ?? {},+ connectionReferences: props.connectionReferences ?? current.connectionReferences ?? {}+ };+}++// packages/core/dist/index.js+init_backups();++// packages/core/dist/api/expression-reference.js+var EXPRESSION_FUNCTIONS = [+ // --- String ---+ { name: "concat", category: "string", signature: "concat(text1, text2, ...)", description: "Combine two or more strings.", example: "concat('Hello, ', variables('name'))" },+ { name: "substring", category: "string", signature: "substring(text, startIndex, length)", description: "Return a substring by start index and length.", example: "substring('PowerAutomate', 0, 5) // 'Power'" },+ { name: "replace", category: "string", signature: "replace(text, oldText, newText)", description: "Replace all occurrences of a substring.", example: "replace('a-b-c', '-', '_') // 'a_b_c'" },+ { name: "split", category: "string", signature: "split(text, delimiter)", description: "Split a string into an array on a delimiter.", example: "split('a,b,c', ',') // ['a','b','c']" },+ { name: "toLower", category: "string", signature: "toLower(text)", description: "Lowercase a string.", example: "toLower('ABC') // 'abc'" },+ { name: "toUpper", category: "string", signature: "toUpper(text)", description: "Uppercase a string.", example: "toUpper('abc') // 'ABC'" },+ { name: "trim", category: "string", signature: "trim(text)", description: "Remove leading/trailing whitespace.", example: "trim(' hi ') // 'hi'" },+ { name: "indexOf", category: "string", signature: "indexOf(text, searchText)", description: "First index of a substring, or -1.", example: "indexOf('[email protected]', '@') // 5" },+ { name: "startsWith", category: "string", signature: "startsWith(text, searchText)", description: "True if text begins with searchText.", example: "startsWith('shared_teams', 'shared_') // true" },+ { name: "endsWith", category: "string", signature: "endsWith(text, searchText)", description: "True if text ends with searchText.", example: "endsWith('report.pdf', '.pdf') // true" },+ { name: "guid", category: "string", signature: "guid()", description: "Generate a new GUID string.", example: "guid() // 'c2ecc88d-...'" },+ { name: "formatNumber", category: "string", signature: "formatNumber(number, format, locale?)", description: "Format a number with a .NET format string.", example: "formatNumber(1234.5, 'C2', 'en-US') // '$1,234.50'" },+ // --- Collection ---+ { name: "length", category: "collection", signature: "length(collection)", description: "Count items in an array or characters in a string.", example: "length(body('List_rows')?['value'])" },+ { name: "first", category: "collection", signature: "first(collection)", description: "First item of an array/string.", example: "first(variables('items'))" },+ { name: "last", category: "collection", signature: "last(collection)", description: "Last item of an array/string.", example: "last(split(variables('path'), '/'))" },+ { name: "contains", category: "collection", signature: "contains(collection, value)", description: "True if a collection/string contains the value.", example: "contains(triggerBody()?['subject'], 'urgent')" },+ { name: "union", category: "collection", signature: "union(coll1, coll2, ...)", description: "Combine collections, removing duplicates.", example: "union(variables('a'), variables('b'))" },+ { name: "intersection", category: "collection", signature: "intersection(coll1, coll2, ...)", description: "Items common to all collections.", example: "intersection(variables('a'), variables('b'))" },+ { name: "take", category: "collection", signature: "take(collection, count)", description: "First N items of a collection.", example: "take(body('List')?['value'], 5)" },+ { name: "skip", category: "collection", signature: "skip(collection, count)", description: "All items after the first N.", example: "skip(variables('items'), 1)" },+ { name: "join", category: "collection", signature: "join(array, delimiter)", description: "Join array items into a string.", example: "join(variables('emails'), '; ')" },+ { name: "empty", category: "collection", signature: "empty(value)", description: "True if a collection/string/object is empty.", example: "empty(body('Get_items')?['value'])" },+ // --- Logical ---+ { name: "if", category: "logical", signature: "if(condition, ifTrue, ifFalse)", description: "Branch on a boolean condition.", example: "if(greater(variables('n'), 0), 'positive', 'non-positive')" },+ { name: "and", category: "logical", signature: "and(expr1, expr2, ...)", description: "True if all expressions are true.", example: "and(greater(x,0), less(x,10))" },+ { name: "or", category: "logical", signature: "or(expr1, expr2, ...)", description: "True if any expression is true.", example: "or(equals(s,'a'), equals(s,'b'))" },+ { name: "not", category: "logical", signature: "not(expression)", description: "Negate a boolean.", example: "not(empty(variables('items')))" },+ { name: "equals", category: "logical", signature: "equals(value1, value2)", description: "True if two values are equal.", example: "equals(triggerBody()?['status'], 'Approved')" },+ { name: "greater", category: "logical", signature: "greater(value1, value2)", description: "True if value1 > value2.", example: "greater(length(variables('items')), 0)" },+ { name: "less", category: "logical", signature: "less(value1, value2)", description: "True if value1 < value2.", example: "less(variables('retries'), 3)" },+ { name: "coalesce", category: "logical", signature: "coalesce(value1, value2, ...)", description: "First non-null value.", example: "coalesce(triggerBody()?['name'], 'Unknown')" },+ // --- Conversion ---+ { name: "json", category: "conversion", signature: "json(text)", description: "Parse a JSON string into an object/array.", example: "json(triggerBody())?['id']" },+ { name: "string", category: "conversion", signature: "string(value)", description: "Convert a value to its string form.", example: "string(variables('count'))" },+ { name: "int", category: "conversion", signature: "int(value)", description: "Convert a value to an integer.", example: "int(triggerBody()?['quantity'])" },+ { name: "float", category: "conversion", signature: "float(value)", description: "Convert a value to a float.", example: "float('3.14')" },+ { name: "bool", category: "conversion", signature: "bool(value)", description: "Convert a value to a boolean.", example: "bool('true')" },+ { name: "array", category: "conversion", signature: "array(value)", description: "Wrap a value in a single-item array.", example: "array('one') // ['one']" },+ { name: "base64", category: "conversion", signature: "base64(value)", description: "Base64-encode a string.", example: "base64('hello')" },+ { name: "base64ToString", category: "conversion", signature: "base64ToString(value)", description: "Decode base64 to a string.", example: "base64ToString(variables('encoded'))" },+ { name: "createArray", category: "conversion", signature: "createArray(item1, item2, ...)", description: "Build an array from values.", example: "createArray('a', 'b', 'c')" },+ // --- Math ---+ { name: "add", category: "math", signature: "add(num1, num2)", description: "Add two numbers.", example: "add(variables('total'), 1)" },+ { name: "sub", category: "math", signature: "sub(num1, num2)", description: "Subtract num2 from num1.", example: "sub(variables('total'), 1)" },+ { name: "mul", category: "math", signature: "mul(num1, num2)", description: "Multiply two numbers.", example: "mul(variables('price'), variables('qty'))" },+ { name: "div", category: "math", signature: "div(num1, num2)", description: "Divide num1 by num2.", example: "div(variables('sum'), variables('count'))" },+ { name: "mod", category: "math", signature: "mod(num1, num2)", description: "Remainder of num1 / num2.", example: "mod(variables('i'), 2)" },+ { name: "rand", category: "math", signature: "rand(minInclusive, maxExclusive)", description: "Random integer in a range.", example: "rand(1, 100)" },+ { name: "max", category: "math", signature: "max(num1, num2, ...)", description: "Largest of the given numbers (or an array).", example: "max(1, 5, 3) // 5" },+ { name: "min", category: "math", signature: "min(num1, num2, ...)", description: "Smallest of the given numbers (or an array).", example: "min(createArray(4, 2, 9)) // 2" },+ // --- Date ---+ { name: "utcNow", category: "date", signature: "utcNow(format?)", description: "Current UTC timestamp, optionally formatted.", example: "utcNow('yyyy-MM-dd')" },+ { name: "addDays", category: "date", signature: "addDays(timestamp, days, format?)", description: "Add (or subtract) days to a timestamp.", example: "addDays(utcNow(), -7)" },+ { name: "addHours", category: "date", signature: "addHours(timestamp, hours, format?)", description: "Add hours to a timestamp.", example: "addHours(utcNow(), 1)" },+ { name: "addMinutes", category: "date", signature: "addMinutes(timestamp, minutes, format?)", description: "Add minutes to a timestamp.", example: "addMinutes(utcNow(), 30)" },+ { name: "formatDateTime", category: "date", signature: "formatDateTime(timestamp, format, locale?)", description: "Reformat a timestamp.", example: "formatDateTime(utcNow(), 'MMM dd, yyyy')" },+ { name: "ticks", category: "date", signature: "ticks(timestamp)", description: "100-nanosecond ticks since 0001-01-01 (for date math).", example: "div(sub(ticks(utcNow()), ticks(variables('start'))), 600000000) // minutes" },+ { name: "convertTimeZone", category: "date", signature: "convertTimeZone(timestamp, sourceTz, destTz, format?)", description: "Convert between time zones.", example: "convertTimeZone(utcNow(), 'UTC', 'Pacific Standard Time')" },+ { name: "dayOfWeek", category: "date", signature: "dayOfWeek(timestamp)", description: "Day of week as 0 (Sunday)\u20136 (Saturday).", example: "dayOfWeek(utcNow())" },+ // --- Reference (run/trigger/action data) ---+ { name: "triggerBody", category: "reference", signature: "triggerBody()", description: "The body of the flow's trigger output.", example: "triggerBody()?['title']" },+ { name: "triggerOutputs", category: "reference", signature: "triggerOutputs()", description: "Full trigger output envelope (headers, body, queries).", example: "triggerOutputs()?['headers']?['x-correlation-id']" },+ { name: "body", category: "reference", signature: "body(actionName)", description: "The body output of a named action.", example: "body('List_rows')?['value']" },+ { name: "outputs", category: "reference", signature: "outputs(actionName)", description: "Full output envelope of a named action.", example: "outputs('Compose')?['statusCode']" },+ { name: "variables", category: "reference", signature: "variables(name)", description: "Current value of a flow variable.", example: "variables('counter')" },+ { name: "parameters", category: "reference", signature: "parameters(name)", description: "Value of a definition/environment parameter.", example: "parameters('$connections')" },+ { name: "items", category: "reference", signature: "items(loopName)", description: "Current item inside an Apply_to_each loop.", example: "items('Apply_to_each')?['id']" },+ { name: "item", category: "reference", signature: "item()", description: "Current item in the innermost loop (shorthand).", example: "item()?['value']" },+ // --- Workflow ---+ { name: "workflow", category: "workflow", signature: "workflow()", description: "Metadata about the running flow (name, run id, tags).", example: "workflow()?['run']?['name']" },+ { name: "actions", category: "workflow", signature: "actions(actionName)", description: "Full result object of an action (status, code, outputs).", example: "actions('HTTP')?['outputs']?['statusCode']" },+ { name: "result", category: "workflow", signature: "result(scopeName)", description: "Results of all actions inside a scope (for error handling).", example: "result('Try_scope')" }+];+function searchExpressionHelp(opts = {}) {+ let fns = EXPRESSION_FUNCTIONS;+ if (opts.category) {+ fns = fns.filter((f) => f.category === opts.category);+ }+ if (opts.query) {+ const q = opts.query.toLowerCase();+ fns = fns.filter((f) => f.name.toLowerCase().includes(q) || f.signature.toLowerCase().includes(q) || f.description.toLowerCase().includes(q));+ }+ return {+ count: fns.length,+ categories: Array.from(new Set(fns.map((f) => f.category))),+ functions: fns+ };+}++// packages/core/dist/auth/az-cli-auth.js+import { spawnSync } from "node:child_process";++// packages/core/dist/auth/disk-token-cache.js+import * as fs from "node:fs";+import * as path from "node:path";+import * as os from "node:os";+import { createHash } from "node:crypto";+var SCHEMA_VERSION = 1;+function defaultCacheDir() {+ const envOverride = process.env.FLOWAGENT_TOKEN_CACHE_DIR;+ if (envOverride)+ return envOverride;+ const platform = process.platform;+ if (platform === "win32") {+ const base = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");+ return path.join(base, "flowagent", "tokens");+ }+ if (platform === "darwin") {+ return path.join(os.homedir(), "Library", "Caches", "flowagent", "tokens");+ }+ const xdg = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");+ return path.join(xdg, "flowagent", "tokens");+}+function parseJwtClaims(token) {+ try {+ const parts = token.split(".");+ if (parts.length !== 3)+ return {};+ const payload = Buffer.from(parts[1].replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf-8");+ const claims = JSON.parse(payload);+ return {+ tenantId: typeof claims.tid === "string" ? claims.tid : void 0,+ accountId: typeof claims.oid === "string" && claims.oid || typeof claims.upn === "string" && claims.upn || typeof claims.sub === "string" && claims.sub || void 0+ };+ } catch {+ return {};+ }+}+function cacheKeyFile(cacheDir, resource, tenantId, accountId) {+ const composite = `${resource}\0${tenantId ?? ""}\0${accountId ?? ""}`;+ const hash = createHash("sha256").update(composite).digest("hex").slice(0, 32);+ return path.join(cacheDir, `${hash}.json`);+}+function unkeyedFile(cacheDir, resource) {+ const hash = createHash("sha256").update(resource).digest("hex").slice(0, 32);+ return path.join(cacheDir, `_unknown-${hash}.json`);+}+var DiskTokenCache = class {+ cacheDir;+ disabled;+ // Per-process memo of (resource → tenantId + accountId) once we've seen one+ // token for that resource. Lets the second read pick the right keyed file+ // without re-parsing.+ identityHints = /* @__PURE__ */ new Map();+ constructor(opts = {}) {+ this.cacheDir = opts.cacheDir ?? defaultCacheDir();+ this.disabled = opts.disabled === true || process.env.FLOWAGENT_DISABLE_DISK_CACHE === "1" || process.env.FLOWAGENT_DISABLE_DISK_CACHE === "true";+ }+ /** Try to read a cached token matching the current az identity.+ *+ * Strategy:+ * - If we've already seen a token for this resource in this process,+ * use the remembered `{tenantId, accountId}` to find the precise file.+ * - Otherwise scan the cache dir for any entry matching this resource,+ * adopt its identity for the rest of the process.+ * - As a final fallback, try the legacy unkeyed file (older format).+ *+ * Returns null if disabled, missing, malformed, or expired.+ */+ read(resource) {+ if (this.disabled)+ return null;+ try {+ const hint = this.identityHints.get(resource);+ if (hint) {+ const file = cacheKeyFile(this.cacheDir, resource, hint.tenantId, hint.accountId);+ const entry = readEntry(file);+ if (entry && entry.resource === resource && Date.now() < entry.expiresAt) {+ return { token: entry.token, expiresAt: entry.expiresAt };+ }+ }+ if (!fs.existsSync(this.cacheDir))+ return null;+ const files = fs.readdirSync(this.cacheDir).filter((f) => f.endsWith(".json"));+ let bestMatch = null;+ for (const f of files) {+ const entry = readEntry(path.join(this.cacheDir, f));+ if (!entry)+ continue;+ if (entry.resource !== resource)+ continue;+ if (Date.now() >= entry.expiresAt)+ continue;+ if (!bestMatch || entry.writtenAt > bestMatch.writtenAt) {+ bestMatch = entry;+ }+ }+ if (bestMatch) {+ this.identityHints.set(resource, {+ tenantId: bestMatch.tenantId,+ accountId: bestMatch.accountId+ });+ return { token: bestMatch.token, expiresAt: bestMatch.expiresAt };+ }+ return null;+ } catch {+ return null;+ }+ }+ /** Persist a token. Atomic via tmp + rename. */+ write(resource, token) {+ if (this.disabled)+ return;+ try {+ fs.mkdirSync(this.cacheDir, { recursive: true });+ const { tenantId, accountId } = parseJwtClaims(token.token);+ this.identityHints.set(resource, { tenantId, accountId });+ const entry = {+ v: SCHEMA_VERSION,+ resource,+ tenantId,+ accountId,+ token: token.token,+ expiresAt: token.expiresAt,+ writtenAt: Date.now()+ };+ const dest = tenantId || accountId ? cacheKeyFile(this.cacheDir, resource, tenantId, accountId) : unkeyedFile(this.cacheDir, resource);+ atomicWrite(dest, JSON.stringify(entry));+ } catch {+ }+ }+ /** Remove all cached entries (used by sign-out flows + tests). */+ clear() {+ try {+ if (!fs.existsSync(this.cacheDir))+ return;+ for (const f of fs.readdirSync(this.cacheDir)) {+ if (f.endsWith(".json")) {+ try {+ fs.unlinkSync(path.join(this.cacheDir, f));+ } catch {+ }+ }+ }+ } catch {+ }+ this.identityHints.clear();+ }+ /** Test/debug accessor. */+ get directory() {+ return this.cacheDir;+ }+ get isDisabled() {+ return this.disabled;+ }+};+function readEntry(file) {+ if (!fs.existsSync(file))+ return null;+ let raw;+ try {+ raw = fs.readFileSync(file, "utf-8");+ } catch {+ return null;+ }+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ if (typeof parsed !== "object" || parsed === null || parsed.v !== SCHEMA_VERSION || typeof parsed.token !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.resource !== "string") {+ return null;+ }+ return parsed;+}+function atomicWrite(dest, contents) {+ const tmp = `${dest}.tmp-${process.pid}-${Date.now()}`;+ fs.writeFileSync(tmp, contents, { encoding: "utf-8", mode: 384 });+ try {+ fs.chmodSync(tmp, 384);+ } catch {+ }+ fs.renameSync(tmp, dest);+}++// packages/core/dist/auth/az-cli-auth.js+var REFRESH_BUFFER_MS = 5 * 60 * 1e3;+var DEFAULT_RESOURCE = "https://service.flow.microsoft.com";+var AzCliTokenProvider = class {+ tokenCache = /* @__PURE__ */ new Map();+ diskCache;+ constructor(opts = {}) {+ if (opts.diskCache === false) {+ this.diskCache = null;+ } else if (opts.diskCache instanceof DiskTokenCache) {+ this.diskCache = opts.diskCache;+ } else {+ this.diskCache = new DiskTokenCache(opts.diskCache);+ }+ }+ async getAccessToken(resource) {+ const res = resource ?? DEFAULT_RESOURCE;+ const memHit = this.tokenCache.get(res);+ if (memHit && Date.now() < memHit.expiresAt - REFRESH_BUFFER_MS) {+ return memHit.token;+ }+ if (this.diskCache) {+ const diskHit = this.diskCache.read(res);+ if (diskHit && Date.now() < diskHit.expiresAt - REFRESH_BUFFER_MS) {+ this.tokenCache.set(res, diskHit);+ return diskHit.token;+ }+ }+ const isWindows = process.platform === "win32";+ const result = spawnSync("az", ["account", "get-access-token", "--resource", res, "--output", "json"], { encoding: "utf-8", shell: isWindows, windowsHide: true });+ if (result.error && result.error.code === "ENOENT") {+ throw new AzCliAuthError("not-installed", "Azure CLI is not installed. Install it from https://aka.ms/installazurecli then run: az login");+ }+ if (result.status !== 0) {+ const stderr = (result.stderr ?? "").toString();+ const stdout = (result.stdout ?? "").toString();+ const combined = `${stderr}+${stdout}`.trim();+ const firstLine = combined.split(/\r?\n/).find((l) => l.trim().length > 0) ?? "az failed";+ if (/Please run ['"]?az login['"]?/i.test(combined) || /Please explicitly log in/i.test(combined) || /AADSTS50173|AADSTS50079|AADSTS50158|AADSTS70043/i.test(combined) || /No subscription found|Run ['"]?az login['"]?/i.test(combined)) {+ throw new AzCliAuthError("not-logged-in", "You are not signed in to Azure. Run this command to sign in: az login");+ }+ if (/AADSTS700082|AADSTS50076/i.test(combined)) {+ throw new AzCliAuthError("token-expired", "Your Azure session has expired. Run this command to sign in again: az login");+ }+ if (/AADSTS/i.test(combined)) {+ throw new AzCliAuthError("permission-denied", "Your Azure account doesn't have access to Power Automate. Check with your IT admin that your account has a Power Automate license. Technical detail: " + firstLine);+ }+ throw new AzCliAuthError("token-failed", "Could not get a Power Automate access token. Try signing in again with: az login\nDetail: " + firstLine);+ }+ let parsed;+ try {+ parsed = JSON.parse(result.stdout);+ } catch (err) {+ throw new AzCliAuthError("token-failed", "Azure CLI returned non-JSON output for get-access-token. Try: az login\nDetail: " + (err instanceof Error ? err.message : String(err)));+ }+ const entry = {+ token: parsed.accessToken,+ expiresAt: new Date(parsed.expiresOn).getTime()+ };+ this.tokenCache.set(res, entry);+ if (this.diskCache) {+ try {+ this.diskCache.write(res, entry);+ } catch {+ }+ }+ return parsed.accessToken;+ }+};+var AzCliAuthError = class extends Error {+ code;+ constructor(code, message) {+ super(message);+ this.code = code;+ this.name = "AzCliAuthError";+ }+};+var cachedTenantId = null;+function getAzTenantId() {+ if (cachedTenantId !== null)+ return cachedTenantId ?? void 0;+ const result = spawnSync("az", ["account", "show", "--query", "tenantId", "-o", "tsv"], { encoding: "utf-8", shell: false });+ if (result.status === 0 && result.stdout) {+ cachedTenantId = result.stdout.trim() || void 0;+ } else {+ cachedTenantId = void 0;+ }+ return cachedTenantId;+}++// packages/core/dist/auth/composite-auth.js+var CONNECTIVITY_RESOURCE2 = "https://api.powerplatform.com";+function buildCompositeAuth(opts = {}) {+ const azAuth = opts.azProvider ?? new AzCliTokenProvider(opts);+ let msalAuth = null;+ async function getMsalAuth() {+ if (msalAuth)+ return msalAuth;+ if (opts.msalFactory) {+ msalAuth = opts.msalFactory();+ return msalAuth;+ }+ const tenantId = getAzTenantId();+ const mod = await Promise.resolve().then(() => (init_msal_auth(), msal_auth_exports));+ const Cls = mod.MsalTokenProvider;+ msalAuth = new Cls(void 0, tenantId);+ return msalAuth;+ }+ return {+ async getAccessToken(resource) {+ if (resource === CONNECTIVITY_RESOURCE2) {+ const provider = await getMsalAuth();+ return provider.getAccessToken(resource);+ }+ return azAuth.getAccessToken(resource);+ }+ };+}++// packages/core/dist/index.js+init_msal_auth();+init_msal_disk_cache();++// packages/core/dist/config.js+init_logger();+import { readFileSync as readFileSync4 } from "node:fs";+import { join as join4 } from "node:path";+import { homedir as homedir3 } from "node:os";+function loadFileConfig(configDir) {+ const configPath = join4(configDir, "config.json");+ try {+ const raw = readFileSync4(configPath, "utf-8");+ return JSON.parse(raw);+ } catch {+ logger.debug(`No config file found at ${configPath}`);+ return {};+ }+}+function loadConfig() {+ const configDir = join4(homedir3(), ".power-automate-cli");+ const fileConfig = loadFileConfig(configDir);+ return {+ defaultEnvironmentId: process.env.PA_DEFAULT_ENVIRONMENT ?? fileConfig.defaultEnvironmentId,+ baseUrl: process.env.PA_BASE_URL ?? fileConfig.baseUrl ?? "https://api.flow.microsoft.com",+ configDir,+ ppapiBaseUrlTemplate: process.env.PA_PPAPI_BASE_URL+ };+}++// packages/core/dist/connection-refs.js+async function enrichRefsWithLogicalNames(client, envId, refs, log) {+ const needsEnrichment = Object.values(refs).some((r) => !r.connectionReferenceLogicalName);+ if (!needsEnrichment)+ return refs;+ let dvRefs;+ try {+ dvRefs = await client.listConnections(envId);+ } catch {+ log?.("Dataverse connection references unavailable; using direct connections");+ return refs;+ }+ const connectorToLogical = {};+ for (const dv of dvRefs) {+ if (dv.connectorid && dv.connectionreferencelogicalname) {+ connectorToLogical[dv.connectorid] = dv.connectionreferencelogicalname;+ }+ }+ const enriched = { ...refs };+ let count = 0;+ for (const [key, ref] of Object.entries(enriched)) {+ if (ref.connectionReferenceLogicalName)+ continue;+ const connectorId = ref.id ?? `/providers/Microsoft.PowerApps/apis/${key}`;+ const logicalName = connectorToLogical[connectorId];+ if (logicalName) {+ enriched[key] = { ...ref, connectionReferenceLogicalName: logicalName };+ count++;+ }+ }+ if (count > 0) {+ log?.(`Resolved ${count} connection reference logical name(s) from Dataverse`);+ }+ return enriched;+}++// packages/core/dist/current-env-store.js+var CurrentEnvStore = class {+ state;+ subscribers = /* @__PURE__ */ new Set();+ constructor(initialEnvId = process.env.PA_DEFAULT_ENVIRONMENT) {+ this.state = initialEnvId ? { envId: initialEnvId, displayName: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "env-var" } : { envId: null, displayName: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "none" };+ }+ get() {+ return this.state;+ }+ set(envId, opts) {+ const prevId = this.state.envId;+ this.state = {+ envId,+ displayName: opts.displayName ?? this.state.displayName ?? null,+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),+ source: opts.source+ };+ if (prevId !== envId) {+ for (const cb of this.subscribers) {+ try {+ cb(this.state);+ } catch {+ }+ }+ }+ return this.state;+ }+ subscribe(cb) {+ this.subscribers.add(cb);+ return () => {+ this.subscribers.delete(cb);+ };+ }+ subscriberCount() {+ return this.subscribers.size;+ }+};+var legacyCurrentEnvStore = new CurrentEnvStore();++// packages/core/dist/current-flow-store.js+var CurrentFlowStore = class {+ state;+ constructor() {+ this.state = { flowId: null, displayName: null, envId: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "none" };+ }+ get() {+ return this.state;+ }+ set(flowId, opts) {+ this.state = {+ flowId,+ displayName: opts.displayName ?? this.state.displayName ?? null,+ envId: opts.envId ?? this.state.envId ?? null,+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),+ source: opts.source+ };+ return this.state;+ }+ clear() {+ this.state = { flowId: null, displayName: null, envId: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "none" };+ return this.state;+ }+};+var legacyCurrentFlowStore = new CurrentFlowStore();++// packages/core/dist/templates.js+var FLOWAGENT_TEMPLATE_ID = "fa2c7b91-3e04-4d8a-b6f1-a9e5c8d20147";+function injectTemplateMetadata(definition) {+ const existing = definition.metadata ?? {};+ if (existing.templateId)+ return definition;+ return { ...definition, metadata: { ...existing, templateId: FLOWAGENT_TEMPLATE_ID } };+}+var SCHEMA = "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#";+var BASE_PARAMS = {+ $authentication: { defaultValue: {}, type: "SecureObject" },+ $connections: { defaultValue: {}, type: "Object" }+};+function listTemplates() {+ return Object.values(TEMPLATES).map((t) => ({+ id: t.id,+ name: t.name,+ description: t.description,+ connectors: t.connectors+ }));+}+function getTemplate(id) {+ return TEMPLATES[id];+}+function generateConnectionRefs(connectors) {+ const refs = {};+ for (const connector of connectors) {+ refs[connector] = {+ connectionName: `REPLACE_WITH_${connector.toUpperCase()}_CONNECTION`,+ source: "Embedded",+ id: `/providers/Microsoft.PowerApps/apis/${connector}`,+ tier: "NotSpecified"+ };+ }+ return refs;+}+var TEMPLATES = {+ "approval-notification": {+ id: "approval-notification",+ name: "Approval with Notification",+ description: "Manual trigger \u2192 create approval \u2192 wait \u2192 conditional email/Teams notification based on outcome",+ connectors: ["shared_approvals", "shared_office365", "shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Button",+ inputs: {+ schema: {+ type: "object",+ properties: {+ title: { title: "Title", type: "string", "x-ms-dynamically-added": true },+ details: { title: "Details", type: "string", "x-ms-dynamically-added": true },+ requesterEmail: { title: "Requester Email", type: "string", "x-ms-dynamically-added": true }+ },+ required: ["title", "requesterEmail"]+ }+ }+ }+ },+ actions: {+ Start_an_Approval: {+ type: "OpenApiConnectionWebhook",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_approvals",+ operationId: "StartAndWaitForAnApproval",+ connectionName: "shared_approvals"+ },+ parameters: {+ approvalType: "Basic",+ "WebhookApprovalCreationInput/title": "Review: @{triggerBody()['title']}",+ "WebhookApprovalCreationInput/assignedTo": "@triggerBody()['requesterEmail']",+ "WebhookApprovalCreationInput/details": "@triggerBody()['details']",+ "WebhookApprovalCreationInput/enableNotifications": true+ }+ },+ runAfter: {}+ },+ Send_Result_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "@triggerBody()['requesterEmail']",+ "emailMessage/Subject": "Approval Result: @{triggerBody()['title']}",+ "emailMessage/Body": "<p>Outcome: <strong>@{body('Start_an_Approval')?['outcome']}</strong></p><p>Comments: @{body('Start_an_Approval')?['responses'][0]?['comments']}</p>"+ }+ },+ runAfter: { Start_an_Approval: ["Succeeded"] }+ },+ Post_Result_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "@triggerBody()['requesterEmail']",+ "body/messageBody": "<p><strong>Approval Result:</strong> @{triggerBody()['title']}<br/>Outcome: @{body('Start_an_Approval')?['outcome']}</p>"+ }+ },+ runAfter: { Start_an_Approval: ["Succeeded"] }+ }+ }+ }+ },+ "agent-route": {+ id: "agent-route",+ name: "Agent-Assisted Router",+ description: "Manual trigger \u2192 invoke Copilot Studio agent \u2192 conditional Teams notification based on agent response",+ connectors: ["shared_microsoftcopilotstudio", "shared_teams", "shared_office365"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Button",+ inputs: {+ schema: {+ type: "object",+ properties: {+ inputText: { title: "Input Text", type: "string", "x-ms-dynamically-added": true },+ recipientEmail: { title: "Recipient Email", type: "string", "x-ms-dynamically-added": true }+ },+ required: ["inputText", "recipientEmail"]+ }+ }+ }+ },+ actions: {+ Invoke_Agent: {+ type: "OpenApiConnectionWebhook",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_microsoftcopilotstudio",+ operationId: "ExecuteCopilotAsyncV2",+ connectionName: "shared_microsoftcopilotstudio"+ },+ parameters: {+ Copilot: "REPLACE_WITH_AGENT_SCHEMA_NAME",+ "body/message": "@triggerBody()['inputText']"+ }+ },+ runAfter: {}+ },+ Post_Agent_Response_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "@triggerBody()['recipientEmail']",+ "body/messageBody": "<p><strong>Agent Response:</strong><br/>@{body('Invoke_Agent')?['lastResponse']}</p>"+ }+ },+ runAfter: { Invoke_Agent: ["Succeeded"] }+ },+ Send_Summary_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "@triggerBody()['recipientEmail']",+ "emailMessage/Subject": "Agent Analysis Complete",+ "emailMessage/Body": "<p>The agent has completed analysis of your request.</p><p><strong>Result:</strong> @{body('Invoke_Agent')?['lastResponse']}</p>"+ }+ },+ runAfter: { Invoke_Agent: ["Succeeded"] }+ }+ }+ }+ },+ "scheduled-digest": {+ id: "scheduled-digest",+ name: "Scheduled Digest",+ description: "Daily recurrence \u2192 query Dataverse \u2192 compose summary \u2192 email + Teams notification",+ connectors: ["shared_commondataserviceforapps", "shared_office365", "shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ Recurrence: {+ type: "Recurrence",+ recurrence: {+ frequency: "Day",+ interval: 1,+ schedule: { hours: ["8"], minutes: ["0"] }+ }+ }+ },+ actions: {+ List_Records: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "ListRecords",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE_NAME",+ "$filter": "createdon ge @{addDays(utcNow(), -1)}",+ "$top": 50+ }+ },+ runAfter: {}+ },+ Compose_Summary: {+ type: "Compose",+ inputs: "Total records: @{length(body('List_Records')?['value'])}",+ runAfter: { List_Records: ["Succeeded"] }+ },+ Send_Digest_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "Daily Digest \u2014 @{utcNow('yyyy-MM-dd')}",+ "emailMessage/Body": "<p><strong>Daily Summary</strong></p><p>@{outputs('Compose_Summary')}</p>"+ }+ },+ runAfter: { Compose_Summary: ["Succeeded"] }+ },+ Post_Digest_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "REPLACE_WITH_RECIPIENT_EMAIL",+ "body/messageBody": "<p><strong>Daily Digest \u2014 @{utcNow('yyyy-MM-dd')}</strong><br/>@{outputs('Compose_Summary')}</p>"+ }+ },+ runAfter: { Compose_Summary: ["Succeeded"] }+ }+ }+ }+ },+ "webhook-dispatcher": {+ id: "webhook-dispatcher",+ name: "Webhook Event Dispatcher",+ description: "HTTP trigger \u2192 log event to Dataverse \u2192 conditional Teams/email notification based on priority",+ connectors: ["shared_commondataserviceforapps", "shared_teams", "shared_office365"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Http",+ inputs: {+ schema: {+ type: "object",+ properties: {+ eventType: { type: "string" },+ priority: { type: "string" },+ message: { type: "string" },+ source: { type: "string" }+ },+ required: ["eventType", "priority", "message"]+ }+ }+ }+ },+ actions: {+ Log_Event_to_Dataverse: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "CreateRecord",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE_NAME",+ "item/subject": "@{triggerBody()['eventType']} \u2014 @{triggerBody()['priority']}",+ "item/description": "@triggerBody()['message']"+ }+ },+ runAfter: {}+ },+ Condition_Priority: {+ type: "If",+ expression: {+ and: [{ equals: ["@triggerBody()['priority']", "high"] }]+ },+ actions: {+ Post_Urgent_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "REPLACE_WITH_RECIPIENT_EMAIL",+ "body/messageBody": "<p><strong>URGENT:</strong> @{triggerBody()['eventType']}<br/>@{triggerBody()['message']}</p>"+ }+ },+ runAfter: {}+ }+ },+ else: {+ actions: {+ Send_Standard_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "Event: @{triggerBody()['eventType']}",+ "emailMessage/Body": "<p>@{triggerBody()['message']}</p><p>Source: @{triggerBody()['source']}</p>"+ }+ },+ runAfter: {}+ }+ }+ },+ runAfter: { Log_Event_to_Dataverse: ["Succeeded"] }+ }+ }+ }+ },+ "agent-orchestrator": {+ id: "agent-orchestrator",+ name: "Agent Orchestrator with Human Escalation",+ description: "HTTP trigger \u2192 invoke Copilot Studio agent \u2192 condition on confidence \u2192 approval if low \u2192 return result",+ connectors: ["shared_microsoftcopilotstudio", "shared_approvals", "shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Http",+ inputs: {+ schema: {+ type: "object",+ properties: {+ input: { type: "string" },+ escalation_threshold: { type: "number" }+ },+ required: ["input"]+ }+ }+ }+ },+ actions: {+ Invoke_Agent: {+ type: "OpenApiConnectionWebhook",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_microsoftcopilotstudio",+ operationId: "ExecuteCopilotAsyncV2",+ connectionName: "shared_microsoftcopilotstudio"+ },+ parameters: {+ Copilot: "REPLACE_WITH_AGENT_SCHEMA_NAME",+ "body/message": "@triggerBody()?['input']"+ }+ },+ runAfter: {}+ },+ Extract_Result: {+ type: "Compose",+ inputs: {+ response: "@body('Invoke_Agent')?['lastResponse']",+ confidence: "@coalesce(body('Invoke_Agent')?['confidence'], 50)"+ },+ runAfter: { Invoke_Agent: ["Succeeded"] }+ },+ Condition_Low_Confidence: {+ type: "If",+ expression: {+ and: [{+ less: [+ "@int(outputs('Extract_Result')?['confidence'])",+ "@coalesce(triggerBody()?['escalation_threshold'], 70)"+ ]+ }]+ },+ actions: {+ Start_Escalation_Approval: {+ type: "OpenApiConnectionWebhook",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_approvals",+ operationId: "StartAndWaitForAnApproval",+ connectionName: "shared_approvals"+ },+ parameters: {+ approvalType: "Basic",+ "WebhookApprovalCreationInput/title": "Low-confidence agent result \u2014 human review needed",+ "WebhookApprovalCreationInput/assignedTo": "REPLACE_WITH_ESCALATION_EMAIL",+ "WebhookApprovalCreationInput/details": "Agent confidence: @{outputs('Extract_Result')?['confidence']}%\n\nInput: @{triggerBody()?['input']}\n\nAgent response: @{outputs('Extract_Result')?['response']}",+ "WebhookApprovalCreationInput/enableNotifications": true+ }+ },+ runAfter: {}+ },+ Post_Escalation_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "REPLACE_WITH_ESCALATION_EMAIL",+ "body/messageBody": "<p><strong>Escalation resolved:</strong> @{body('Start_Escalation_Approval')?['outcome']}</p><p>Comments: @{body('Start_Escalation_Approval')?['responses'][0]?['comments']}</p>"+ }+ },+ runAfter: { Start_Escalation_Approval: ["Succeeded"] }+ }+ },+ else: { actions: {} },+ runAfter: { Extract_Result: ["Succeeded"] }+ },+ Return_Response: {+ type: "Response",+ kind: "Http",+ inputs: {+ statusCode: 200,+ headers: { "Content-Type": "application/json" },+ body: {+ result: "@outputs('Extract_Result')?['response']",+ confidence: "@outputs('Extract_Result')?['confidence']",+ escalated: "@equals(outputs('Condition_Low_Confidence')?['status'], 'ActionSkipped')"+ }+ },+ runAfter: { Condition_Low_Confidence: ["Succeeded"] }+ }+ }+ }+ },+ "agent-skill": {+ id: "agent-skill",+ name: "Agent Skill (Copilot Studio calls this flow)",+ description: "Skills trigger (agent calls flow) \u2192 process input \u2192 Respond to agent with structured output",+ connectors: [],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ When_an_agent_calls_a_flow: {+ type: "Request",+ kind: "Skills",+ inputs: {+ schema: {+ type: "object",+ properties: {+ text: {+ title: "REPLACE_WITH_INPUT_NAME",+ type: "string",+ "x-ms-content-hint": "TEXT",+ description: "REPLACE_WITH_INPUT_DESCRIPTION"+ }+ },+ required: ["text"]+ }+ }+ }+ },+ actions: {+ Process_Input: {+ type: "Compose",+ inputs: "REPLACE_WITH_LOGIC \u2014 input is @{triggerBody()?['text']}",+ runAfter: {}+ },+ Respond_to_agent: {+ type: "Response",+ kind: "Skills",+ inputs: {+ statusCode: 200,+ body: {+ result: "@{outputs('Process_Input')}"+ },+ schema: {+ type: "object",+ properties: {+ result: {+ title: "REPLACE_WITH_OUTPUT_NAME",+ type: "string",+ "x-ms-content-hint": "TEXT",+ description: "REPLACE_WITH_OUTPUT_DESCRIPTION"+ }+ }+ }+ },+ runAfter: { Process_Input: ["Succeeded"] }+ }+ }+ }+ },+ "ai-prompt-flow": {+ id: "ai-prompt-flow",+ name: "AI Prompt via Azure OpenAI",+ description: "HTTP trigger \u2192 Azure OpenAI HTTP action \u2192 extract response \u2192 return via Response action",+ connectors: [],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Http",+ inputs: {+ schema: {+ type: "object",+ properties: {+ prompt: { type: "string" },+ context: { type: "string" }+ },+ required: ["prompt"]+ }+ }+ }+ },+ actions: {+ Call_Azure_OpenAI: {+ type: "Http",+ inputs: {+ method: "POST",+ uri: "REPLACE_WITH_AOAI_ENDPOINT",+ headers: {+ "Content-Type": "application/json",+ "api-key": "REPLACE_WITH_AOAI_KEY"+ },+ body: {+ model: "REPLACE_WITH_MODEL",+ messages: [+ {+ role: "system",+ content: "REPLACE_WITH_SYSTEM_PROMPT"+ },+ {+ role: "user",+ content: "@{triggerBody()?['prompt']}"+ }+ ]+ }+ },+ runAfter: {},+ runtimeConfiguration: {+ secureData: {+ properties: ["inputs"]+ }+ }+ },+ Extract_Response: {+ type: "Compose",+ inputs: "@body('Call_Azure_OpenAI')?['choices'][0]?['message']?['content']",+ runAfter: { Call_Azure_OpenAI: ["Succeeded"] }+ },+ Return_Response: {+ type: "Response",+ kind: "Http",+ inputs: {+ statusCode: 200,+ headers: { "Content-Type": "application/json" },+ body: {+ result: "@outputs('Extract_Response')",+ prompt: "@triggerBody()?['prompt']"+ }+ },+ runAfter: { Extract_Response: ["Succeeded"] }+ }+ }+ }+ },+ "child-flow": {+ id: "child-flow",+ name: "Child Flow (called from parent flow)",+ description: "Manual trigger with typed inputs \u2192 process \u2192 respond with output. Called from 'Run a Child Flow' action in parent.",+ connectors: [],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "Button",+ inputs: {+ schema: {+ type: "object",+ properties: {+ input_text: { type: "string", title: "Input Text", "x-ms-content-hint": "TEXT", description: "REPLACE_WITH_INPUT_DESCRIPTION" }+ },+ required: ["input_text"]+ }+ }+ }+ },+ actions: {+ Process_Input: {+ type: "Compose",+ inputs: "REPLACE \u2014 input is @{triggerBody()['input_text']}",+ runAfter: {}+ },+ Respond_to_parent: {+ type: "Response",+ kind: "PowerApp",+ inputs: {+ statusCode: 200,+ body: { result: "@{outputs('Process_Input')}" },+ schema: {+ type: "object",+ properties: {+ result: { type: "string", title: "Result", "x-ms-content-hint": "TEXT", description: "REPLACE_WITH_OUTPUT_DESCRIPTION" }+ }+ }+ },+ runAfter: { Process_Input: ["Succeeded"] }+ }+ }+ }+ },+ "ai-digest-flow": {+ id: "ai-digest-flow",+ name: "AI-Powered Daily Digest",+ description: "Daily recurrence \u2192 list Dataverse rows \u2192 AI summarize via Azure OpenAI \u2192 email + Teams notification",+ connectors: ["shared_commondataserviceforapps", "shared_office365", "shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ Recurrence: {+ type: "Recurrence",+ recurrence: {+ frequency: "Day",+ interval: 1,+ schedule: { hours: ["8"], minutes: ["0"] }+ }+ }+ },+ actions: {+ List_Records: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "ListRecords",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE",+ "$filter": "createdon ge @{addDays(utcNow(), -1)}",+ "$top": 50+ }+ },+ runAfter: {}+ },+ Summarize_with_AI: {+ type: "Http",+ inputs: {+ method: "POST",+ uri: "REPLACE_WITH_AOAI_ENDPOINT",+ headers: {+ "Content-Type": "application/json",+ "api-key": "REPLACE_WITH_AOAI_KEY"+ },+ body: {+ model: "REPLACE_WITH_MODEL",+ messages: [+ {+ role: "system",+ content: "Summarize the following records into a concise daily digest with key highlights and action items."+ },+ {+ role: "user",+ content: "@{string(body('List_Records')?['value'])}"+ }+ ]+ }+ },+ runAfter: { List_Records: ["Succeeded"] },+ runtimeConfiguration: {+ secureData: {+ properties: ["inputs"]+ }+ }+ },+ Extract_Summary: {+ type: "Compose",+ inputs: "@body('Summarize_with_AI')?['choices'][0]?['message']?['content']",+ runAfter: { Summarize_with_AI: ["Succeeded"] }+ },+ Send_Digest_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENTS",+ "emailMessage/Subject": "AI Daily Digest \u2014 @{utcNow('yyyy-MM-dd')}",+ "emailMessage/Body": "<p><strong>AI-Generated Daily Digest</strong></p><p>@{outputs('Extract_Summary')}</p><p><em>Records processed: @{length(body('List_Records')?['value'])}</em></p>"+ }+ },+ runAfter: { Extract_Summary: ["Succeeded"] }+ },+ Post_Digest_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "REPLACE_WITH_RECIPIENTS",+ "body/messageBody": "<p><strong>AI Daily Digest \u2014 @{utcNow('yyyy-MM-dd')}</strong><br/>@{outputs('Extract_Summary')}</p>"+ }+ },+ runAfter: { Extract_Summary: ["Succeeded"] }+ }+ }+ }+ },+ "canvas-app-flow": {+ id: "canvas-app-flow",+ name: "Canvas App Flow (PowerApps V2 Trigger)",+ description: "PowerApps V2 trigger with typed inputs \u2192 Compose \u2192 Post to Teams \u2192 Response back to app. Most common PA + Power Apps pattern.",+ connectors: ["shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "PowerApp",+ inputs: {+ schema: {+ type: "object",+ properties: {+ text: {+ title: "InputText",+ type: "string",+ "x-ms-content-hint": "TEXT",+ "x-ms-dynamically-added": true,+ description: "Text input from the canvas app"+ },+ email: {+ title: "UserEmail",+ type: "string",+ "x-ms-content-hint": "TEXT",+ "x-ms-dynamically-added": true,+ description: "Email of the requesting user"+ }+ },+ required: ["text", "email"]+ }+ }+ }+ },+ actions: {+ Compose_Result: {+ type: "Compose",+ inputs: "Processed: @{triggerBody()['text']} \u2014 submitted by @{triggerBody()['email']}",+ runAfter: {}+ },+ Post_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "@triggerBody()['email']",+ "body/messageBody": "<p><strong>App Submission:</strong><br/>@{outputs('Compose_Result')}</p>"+ }+ },+ runAfter: { Compose_Result: ["Succeeded"] }+ },+ Respond_to_App: {+ type: "Response",+ kind: "PowerApp",+ inputs: {+ statusCode: 200,+ body: {+ result: "@{outputs('Compose_Result')}"+ },+ schema: {+ type: "object",+ properties: {+ result: {+ title: "Result",+ type: "string",+ "x-ms-content-hint": "TEXT",+ description: "Processing result returned to the canvas app"+ }+ }+ }+ },+ runAfter: { Post_to_Teams: ["Succeeded"] }+ }+ }+ }+ },+ "model-driven-command": {+ id: "model-driven-command",+ name: "Model-Driven App Command Bar Flow",+ description: "PowerApps V2 trigger (record ID from command bar) \u2192 Get Dataverse row \u2192 Compose summary \u2192 Post to Teams \u2192 Response",+ connectors: ["shared_commondataserviceforapps", "shared_teams"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ manual: {+ type: "Request",+ kind: "PowerApp",+ inputs: {+ schema: {+ type: "object",+ properties: {+ recordId: {+ title: "RecordId",+ type: "string",+ "x-ms-content-hint": "TEXT",+ "x-ms-dynamically-added": true,+ description: "ID of the record from the command bar"+ },+ userEmail: {+ title: "UserEmail",+ type: "string",+ "x-ms-content-hint": "TEXT",+ "x-ms-dynamically-added": true,+ description: "Email of the user who clicked the command"+ }+ },+ required: ["recordId", "userEmail"]+ }+ }+ }+ },+ actions: {+ Get_Record: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "GetItem",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE_NAME",+ recordId: "@triggerBody()['recordId']"+ }+ },+ runAfter: {}+ },+ Compose_Summary: {+ type: "Compose",+ inputs: "Record: @{body('Get_Record')?['name']} (ID: @{triggerBody()['recordId']})",+ runAfter: { Get_Record: ["Succeeded"] }+ },+ Post_to_Teams: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_teams",+ operationId: "PostMessageToConversation",+ connectionName: "shared_teams"+ },+ parameters: {+ poster: "Flow bot",+ location: "Chat with Flow bot",+ "body/recipient": "@triggerBody()['userEmail']",+ "body/messageBody": "<p><strong>Record Details:</strong><br/>@{outputs('Compose_Summary')}</p>"+ }+ },+ runAfter: { Compose_Summary: ["Succeeded"] }+ },+ Respond_to_App: {+ type: "Response",+ kind: "PowerApp",+ inputs: {+ statusCode: 200,+ body: {+ result: "@{outputs('Compose_Summary')}"+ },+ schema: {+ type: "object",+ properties: {+ result: {+ title: "Result",+ type: "string",+ "x-ms-content-hint": "TEXT",+ description: "Summary returned to the model-driven app"+ }+ }+ }+ },+ runAfter: { Post_to_Teams: ["Succeeded"] }+ }+ }+ }+ },+ "dataverse-event-flow": {+ id: "dataverse-event-flow",+ name: "Dataverse Event Notification",+ description: "Dataverse row change trigger (add/modify/delete) \u2192 Compose change summary \u2192 Condition on change type \u2192 Send notification email",+ connectors: ["shared_commondataserviceforapps", "shared_office365"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ When_a_row_changes: {+ type: "OpenApiConnectionNotification",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "SubscribeWebhookTrigger",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ subscriptionRequest: {+ entityname: "REPLACE_WITH_TABLE_NAME",+ scope: 4,+ message: 3+ }+ }+ }+ }+ },+ actions: {+ Compose_Change_Summary: {+ type: "Compose",+ inputs: "Change detected on @{triggerBody()?['name']} (ID: @{triggerBody()?['_record_id']})",+ runAfter: {}+ },+ Condition_Change_Type: {+ type: "If",+ expression: {+ and: [{ equals: ["@triggerBody()?['SdkMessage']", "Create"] }]+ },+ actions: {+ Send_New_Record_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "New Record Created",+ "emailMessage/Body": "<p><strong>New record:</strong> @{outputs('Compose_Change_Summary')}</p>"+ }+ },+ runAfter: {}+ }+ },+ else: {+ actions: {+ Send_Update_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "Record Updated or Deleted",+ "emailMessage/Body": "<p><strong>Change:</strong> @{outputs('Compose_Change_Summary')}</p>"+ }+ },+ runAfter: {}+ }+ }+ },+ runAfter: { Compose_Change_Summary: ["Succeeded"] }+ }+ }+ }+ },+ "power-pages-flow": {+ id: "power-pages-flow",+ name: "Power Pages Form Handler",+ description: "Power Pages trigger \u2192 process form submission \u2192 Create Dataverse row \u2192 Return JSON response. Attach to a Power Pages site via Set up > Cloud flows.",+ connectors: ["shared_commondataserviceforapps"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ When_Power_Pages_calls_a_flow: {+ type: "Request",+ kind: "PowerPages",+ inputs: {+ schema: {+ type: "object",+ properties: {+ name: { type: "string" },+ email: { type: "string" },+ message: { type: "string" }+ },+ required: ["name", "email"]+ }+ }+ }+ },+ actions: {+ Create_Dataverse_Record: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "CreateRecord",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE_NAME",+ "item/name": "@triggerBody()['name']",+ "item/emailaddress": "@triggerBody()['email']",+ "item/description": "@triggerBody()['message']"+ }+ },+ runAfter: {}+ },+ Return_Response: {+ type: "Response",+ kind: "Http",+ inputs: {+ statusCode: 200,+ headers: { "Content-Type": "application/json" },+ body: {+ success: true,+ recordId: "@body('Create_Dataverse_Record')?['_record_id']",+ message: "Submission received for @{triggerBody()['name']}"+ }+ },+ runAfter: { Create_Dataverse_Record: ["Succeeded"] }+ }+ }+ }+ },+ "background-app-flow": {+ id: "background-app-flow",+ name: "Background App Flow (Scheduled Dataverse Digest)",+ description: "Daily recurrence \u2192 List Dataverse records with filter \u2192 Compose summary \u2192 Send digest email. Designed for manual association to a Power App.",+ connectors: ["shared_commondataserviceforapps", "shared_office365"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ Recurrence: {+ type: "Recurrence",+ recurrence: {+ frequency: "Day",+ interval: 1,+ schedule: { hours: ["7"], minutes: ["0"] }+ }+ }+ },+ actions: {+ List_Records: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",+ operationId: "ListRecords",+ connectionName: "shared_commondataserviceforapps"+ },+ parameters: {+ entityName: "REPLACE_WITH_TABLE_NAME",+ "$filter": "createdon ge @{addDays(utcNow(), -1)}",+ "$top": 100+ }+ },+ runAfter: {}+ },+ Compose_Summary: {+ type: "Compose",+ inputs: "Daily report: @{length(body('List_Records')?['value'])} records found since @{addDays(utcNow(), -1)}",+ runAfter: { List_Records: ["Succeeded"] }+ },+ Send_Digest_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "Daily App Digest \u2014 @{utcNow('yyyy-MM-dd')}",+ "emailMessage/Body": "<p><strong>Background App Digest</strong></p><p>@{outputs('Compose_Summary')}</p><p><em>This flow can be manually associated to a Power App for in-context billing.</em></p>"+ }+ },+ runAfter: { Compose_Summary: ["Succeeded"] }+ }+ }+ }+ },+ "sharepoint-item-flow": {+ id: "sharepoint-item-flow",+ name: "SharePoint Item Created (Polling Trigger)",+ description: "SharePoint polling trigger with splitOn \u2192 get item details \u2192 condition \u2192 send notification email. Standard event-driven pattern.",+ connectors: ["shared_sharepointonline", "shared_office365"],+ definition: {+ $schema: SCHEMA,+ contentVersion: "1.0.0.0",+ parameters: BASE_PARAMS,+ outputs: {},+ triggers: {+ When_a_new_item_is_created: {+ type: "OpenApiConnection",+ recurrence: {+ frequency: "Minute",+ interval: 5+ },+ splitOn: "@triggerOutputs()?['body/value']",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",+ operationId: "GetOnNewItems",+ connectionName: "shared_sharepointonline"+ },+ parameters: {+ dataset: "REPLACE_WITH_SITE_URL",+ table: "REPLACE_WITH_LIST_NAME"+ }+ }+ }+ },+ actions: {+ Compose_Item_Summary: {+ type: "Compose",+ inputs: "New item: @{triggerOutputs()?['body/Title']} (ID: @{triggerOutputs()?['body/ID']})",+ runAfter: {}+ },+ Send_Notification_Email: {+ type: "OpenApiConnection",+ inputs: {+ host: {+ apiId: "/providers/Microsoft.PowerApps/apis/shared_office365",+ operationId: "SendEmailV2",+ connectionName: "shared_office365"+ },+ parameters: {+ "emailMessage/To": "REPLACE_WITH_RECIPIENT_EMAIL",+ "emailMessage/Subject": "New SharePoint Item: @{triggerOutputs()?['body/Title']}",+ "emailMessage/Body": `<p><strong>New item created in SharePoint list</strong></p><p>@{outputs('Compose_Item_Summary')}</p><p><a href="@{triggerOutputs()?['body/{Link}']}">View item</a></p>`+ }+ },+ runAfter: { Compose_Item_Summary: ["Succeeded"] }+ }+ }+ }+ }+};++// packages/core/dist/index.js+init_trigger_emulators();+init_flow_definition();++// packages/core/dist/mcp/server.js+import { AsyncLocalStorage } from "node:async_hooks";++// node_modules/zod/v3/external.js+var external_exports = {};+__export(external_exports, {+ BRAND: () => BRAND,+ DIRTY: () => DIRTY,+ EMPTY_PATH: () => EMPTY_PATH,+ INVALID: () => INVALID,+ NEVER: () => NEVER2,+ OK: () => OK,+ ParseStatus: () => ParseStatus,+ Schema: () => ZodType2,+ ZodAny: () => ZodAny,+ ZodArray: () => ZodArray2,+ ZodBigInt: () => ZodBigInt,+ ZodBoolean: () => ZodBoolean2,+ ZodBranded: () => ZodBranded,+ ZodCatch: () => ZodCatch2,+ ZodDate: () => ZodDate,+ ZodDefault: () => ZodDefault2,+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,+ ZodEffects: () => ZodEffects,+ ZodEnum: () => ZodEnum2,+ ZodError: () => ZodError2,+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,+ ZodFunction: () => ZodFunction,+ ZodIntersection: () => ZodIntersection2,+ ZodIssueCode: () => ZodIssueCode,+ ZodLazy: () => ZodLazy,+ ZodLiteral: () => ZodLiteral2,+ ZodMap: () => ZodMap,+ ZodNaN: () => ZodNaN,+ ZodNativeEnum: () => ZodNativeEnum,+ ZodNever: () => ZodNever2,+ ZodNull: () => ZodNull2,+ ZodNullable: () => ZodNullable2,+ ZodNumber: () => ZodNumber2,+ ZodObject: () => ZodObject2,+ ZodOptional: () => ZodOptional2,+ ZodParsedType: () => ZodParsedType,+ ZodPipeline: () => ZodPipeline,+ ZodPromise: () => ZodPromise,+ ZodReadonly: () => ZodReadonly2,+ ZodRecord: () => ZodRecord2,+ ZodSchema: () => ZodType2,+ ZodSet: () => ZodSet,+ ZodString: () => ZodString2,+ ZodSymbol: () => ZodSymbol,+ ZodTransformer: () => ZodEffects,+ ZodTuple: () => ZodTuple,+ ZodType: () => ZodType2,+ ZodUndefined: () => ZodUndefined,+ ZodUnion: () => ZodUnion2,+ ZodUnknown: () => ZodUnknown2,+ ZodVoid: () => ZodVoid,+ addIssueToContext: () => addIssueToContext,+ any: () => anyType,+ array: () => arrayType,+ bigint: () => bigIntType,+ boolean: () => booleanType,+ coerce: () => coerce,+ custom: () => custom2,+ date: () => dateType,+ datetimeRegex: () => datetimeRegex,+ defaultErrorMap: () => en_default2,+ discriminatedUnion: () => discriminatedUnionType,+ effect: () => effectsType,+ enum: () => enumType,+ function: () => functionType,+ getErrorMap: () => getErrorMap,+ getParsedType: () => getParsedType2,+ instanceof: () => instanceOfType,+ intersection: () => intersectionType,+ isAborted: () => isAborted,+ isAsync: () => isAsync,+ isDirty: () => isDirty,+ isValid: () => isValid,+ late: () => late,+ lazy: () => lazyType,+ literal: () => literalType,+ makeIssue: () => makeIssue,+ map: () => mapType,+ nan: () => nanType,+ nativeEnum: () => nativeEnumType,+ never: () => neverType,+ null: () => nullType,+ nullable: () => nullableType,+ number: () => numberType,+ object: () => objectType,+ objectUtil: () => objectUtil,+ oboolean: () => oboolean,+ onumber: () => onumber,+ optional: () => optionalType,+ ostring: () => ostring,+ pipeline: () => pipelineType,+ preprocess: () => preprocessType,+ promise: () => promiseType,+ quotelessJson: () => quotelessJson,+ record: () => recordType,+ set: () => setType,+ setErrorMap: () => setErrorMap,+ strictObject: () => strictObjectType,+ string: () => stringType,+ symbol: () => symbolType,+ transformer: () => effectsType,+ tuple: () => tupleType,+ undefined: () => undefinedType,+ union: () => unionType,+ unknown: () => unknownType,+ util: () => util,+ void: () => voidType+});++// node_modules/zod/v3/helpers/util.js+var util;+(function(util2) {+ util2.assertEqual = (_) => {+ };+ function assertIs2(_arg) {+ }+ util2.assertIs = assertIs2;+ function assertNever2(_x) {+ throw new Error();+ }+ util2.assertNever = assertNever2;+ util2.arrayToEnum = (items) => {+ const obj = {};+ for (const item of items) {+ obj[item] = item;+ }+ return obj;+ };+ util2.getValidEnumValues = (obj) => {+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");+ const filtered = {};+ for (const k of validKeys) {+ filtered[k] = obj[k];+ }+ return util2.objectValues(filtered);+ };+ util2.objectValues = (obj) => {+ return util2.objectKeys(obj).map(function(e) {+ return obj[e];+ });+ };+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {+ const keys = [];+ for (const key in object3) {+ if (Object.prototype.hasOwnProperty.call(object3, key)) {+ keys.push(key);+ }+ }+ return keys;+ };+ util2.find = (arr, checker) => {+ for (const item of arr) {+ if (checker(item))+ return item;+ }+ return void 0;+ };+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;+ function joinValues2(array2, separator = " | ") {+ return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);+ }+ util2.joinValues = joinValues2;+ util2.jsonStringifyReplacer = (_, value) => {+ if (typeof value === "bigint") {+ return value.toString();+ }+ return value;+ };+})(util || (util = {}));+var objectUtil;+(function(objectUtil2) {+ objectUtil2.mergeShapes = (first, second) => {+ return {+ ...first,+ ...second+ // second overwrites first+ };+ };+})(objectUtil || (objectUtil = {}));+var ZodParsedType = util.arrayToEnum([+ "string",+ "nan",+ "number",+ "integer",+ "float",+ "boolean",+ "date",+ "bigint",+ "symbol",+ "function",+ "undefined",+ "null",+ "array",+ "object",+ "unknown",+ "promise",+ "void",+ "never",+ "map",+ "set"+]);+var getParsedType2 = (data) => {+ const t = typeof data;+ switch (t) {+ case "undefined":+ return ZodParsedType.undefined;+ case "string":+ return ZodParsedType.string;+ case "number":+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;+ case "boolean":+ return ZodParsedType.boolean;+ case "function":+ return ZodParsedType.function;+ case "bigint":+ return ZodParsedType.bigint;+ case "symbol":+ return ZodParsedType.symbol;+ case "object":+ if (Array.isArray(data)) {+ return ZodParsedType.array;+ }+ if (data === null) {+ return ZodParsedType.null;+ }+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {+ return ZodParsedType.promise;+ }+ if (typeof Map !== "undefined" && data instanceof Map) {+ return ZodParsedType.map;+ }+ if (typeof Set !== "undefined" && data instanceof Set) {+ return ZodParsedType.set;+ }+ if (typeof Date !== "undefined" && data instanceof Date) {+ return ZodParsedType.date;+ }+ return ZodParsedType.object;+ default:+ return ZodParsedType.unknown;+ }+};++// node_modules/zod/v3/ZodError.js+var ZodIssueCode = util.arrayToEnum([+ "invalid_type",+ "invalid_literal",+ "custom",+ "invalid_union",+ "invalid_union_discriminator",+ "invalid_enum_value",+ "unrecognized_keys",+ "invalid_arguments",+ "invalid_return_type",+ "invalid_date",+ "invalid_string",+ "too_small",+ "too_big",+ "invalid_intersection_types",+ "not_multiple_of",+ "not_finite"+]);+var quotelessJson = (obj) => {+ const json = JSON.stringify(obj, null, 2);+ return json.replace(/"([^"]+)":/g, "$1:");+};+var ZodError2 = class _ZodError extends Error {+ get errors() {+ return this.issues;+ }+ constructor(issues) {+ super();+ this.issues = [];+ this.addIssue = (sub) => {+ this.issues = [...this.issues, sub];+ };+ this.addIssues = (subs = []) => {+ this.issues = [...this.issues, ...subs];+ };+ const actualProto = new.target.prototype;+ if (Object.setPrototypeOf) {+ Object.setPrototypeOf(this, actualProto);+ } else {+ this.__proto__ = actualProto;+ }+ this.name = "ZodError";+ this.issues = issues;+ }+ format(_mapper) {+ const mapper = _mapper || function(issue2) {+ return issue2.message;+ };+ const fieldErrors = { _errors: [] };+ const processError = (error2) => {+ for (const issue2 of error2.issues) {+ if (issue2.code === "invalid_union") {+ issue2.unionErrors.map(processError);+ } else if (issue2.code === "invalid_return_type") {+ processError(issue2.returnTypeError);+ } else if (issue2.code === "invalid_arguments") {+ processError(issue2.argumentsError);+ } else if (issue2.path.length === 0) {+ fieldErrors._errors.push(mapper(issue2));+ } else {+ let curr = fieldErrors;+ let i = 0;+ while (i < issue2.path.length) {+ const el = issue2.path[i];+ const terminal = i === issue2.path.length - 1;+ if (!terminal) {+ curr[el] = curr[el] || { _errors: [] };+ } else {+ curr[el] = curr[el] || { _errors: [] };+ curr[el]._errors.push(mapper(issue2));+ }+ curr = curr[el];+ i++;+ }+ }+ }+ };+ processError(this);+ return fieldErrors;+ }+ static assert(value) {+ if (!(value instanceof _ZodError)) {+ throw new Error(`Not a ZodError: ${value}`);+ }+ }+ toString() {+ return this.message;+ }+ get message() {+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);+ }+ get isEmpty() {+ return this.issues.length === 0;+ }+ flatten(mapper = (issue2) => issue2.message) {+ const fieldErrors = {};+ const formErrors = [];+ for (const sub of this.issues) {+ if (sub.path.length > 0) {+ const firstEl = sub.path[0];+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];+ fieldErrors[firstEl].push(mapper(sub));+ } else {+ formErrors.push(mapper(sub));+ }+ }+ return { formErrors, fieldErrors };+ }+ get formErrors() {+ return this.flatten();+ }+};+ZodError2.create = (issues) => {+ const error2 = new ZodError2(issues);+ return error2;+};++// node_modules/zod/v3/locales/en.js+var errorMap = (issue2, _ctx) => {+ let message;+ switch (issue2.code) {+ case ZodIssueCode.invalid_type:+ if (issue2.received === ZodParsedType.undefined) {+ message = "Required";+ } else {+ message = `Expected ${issue2.expected}, received ${issue2.received}`;+ }+ break;+ case ZodIssueCode.invalid_literal:+ message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;+ break;+ case ZodIssueCode.unrecognized_keys:+ message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;+ break;+ case ZodIssueCode.invalid_union:+ message = `Invalid input`;+ break;+ case ZodIssueCode.invalid_union_discriminator:+ message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;+ break;+ case ZodIssueCode.invalid_enum_value:+ message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;+ break;+ case ZodIssueCode.invalid_arguments:+ message = `Invalid function arguments`;+ break;+ case ZodIssueCode.invalid_return_type:+ message = `Invalid function return type`;+ break;+ case ZodIssueCode.invalid_date:+ message = `Invalid date`;+ break;+ case ZodIssueCode.invalid_string:+ if (typeof issue2.validation === "object") {+ if ("includes" in issue2.validation) {+ message = `Invalid input: must include "${issue2.validation.includes}"`;+ if (typeof issue2.validation.position === "number") {+ message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;+ }+ } else if ("startsWith" in issue2.validation) {+ message = `Invalid input: must start with "${issue2.validation.startsWith}"`;+ } else if ("endsWith" in issue2.validation) {+ message = `Invalid input: must end with "${issue2.validation.endsWith}"`;+ } else {+ util.assertNever(issue2.validation);+ }+ } else if (issue2.validation !== "regex") {+ message = `Invalid ${issue2.validation}`;+ } else {+ message = "Invalid";+ }+ break;+ case ZodIssueCode.too_small:+ if (issue2.type === "array")+ message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;+ else if (issue2.type === "string")+ message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;+ else if (issue2.type === "number")+ message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;+ else if (issue2.type === "bigint")+ message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;+ else if (issue2.type === "date")+ message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;+ else+ message = "Invalid input";+ break;+ case ZodIssueCode.too_big:+ if (issue2.type === "array")+ message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;+ else if (issue2.type === "string")+ message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;+ else if (issue2.type === "number")+ message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;+ else if (issue2.type === "bigint")+ message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;+ else if (issue2.type === "date")+ message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;+ else+ message = "Invalid input";+ break;+ case ZodIssueCode.custom:+ message = `Invalid input`;+ break;+ case ZodIssueCode.invalid_intersection_types:+ message = `Intersection results could not be merged`;+ break;+ case ZodIssueCode.not_multiple_of:+ message = `Number must be a multiple of ${issue2.multipleOf}`;+ break;+ case ZodIssueCode.not_finite:+ message = "Number must be finite";+ break;+ default:+ message = _ctx.defaultError;+ util.assertNever(issue2);+ }+ return { message };+};+var en_default2 = errorMap;++// node_modules/zod/v3/errors.js+var overrideErrorMap = en_default2;+function setErrorMap(map) {+ overrideErrorMap = map;+}+function getErrorMap() {+ return overrideErrorMap;+}++// node_modules/zod/v3/helpers/parseUtil.js+var makeIssue = (params) => {+ const { data, path: path3, errorMaps, issueData } = params;+ const fullPath = [...path3, ...issueData.path || []];+ const fullIssue = {+ ...issueData,+ path: fullPath+ };+ if (issueData.message !== void 0) {+ return {+ ...issueData,+ path: fullPath,+ message: issueData.message+ };+ }+ let errorMessage = "";+ const maps = errorMaps.filter((m) => !!m).slice().reverse();+ for (const map of maps) {+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;+ }+ return {+ ...issueData,+ path: fullPath,+ message: errorMessage+ };+};+var EMPTY_PATH = [];+function addIssueToContext(ctx, issueData) {+ const overrideMap = getErrorMap();+ const issue2 = makeIssue({+ issueData,+ data: ctx.data,+ path: ctx.path,+ errorMaps: [+ ctx.common.contextualErrorMap,+ // contextual error map is first priority+ ctx.schemaErrorMap,+ // then schema-bound map if available+ overrideMap,+ // then global override map+ overrideMap === en_default2 ? void 0 : en_default2+ // then global default map+ ].filter((x) => !!x)+ });+ ctx.common.issues.push(issue2);+}+var ParseStatus = class _ParseStatus {+ constructor() {+ this.value = "valid";+ }+ dirty() {+ if (this.value === "valid")+ this.value = "dirty";+ }+ abort() {+ if (this.value !== "aborted")+ this.value = "aborted";+ }+ static mergeArray(status, results) {+ const arrayValue = [];+ for (const s of results) {+ if (s.status === "aborted")+ return INVALID;+ if (s.status === "dirty")+ status.dirty();+ arrayValue.push(s.value);+ }+ return { status: status.value, value: arrayValue };+ }+ static async mergeObjectAsync(status, pairs) {+ const syncPairs = [];+ for (const pair of pairs) {+ const key = await pair.key;+ const value = await pair.value;+ syncPairs.push({+ key,+ value+ });+ }+ return _ParseStatus.mergeObjectSync(status, syncPairs);+ }+ static mergeObjectSync(status, pairs) {+ const finalObject = {};+ for (const pair of pairs) {+ const { key, value } = pair;+ if (key.status === "aborted")+ return INVALID;+ if (value.status === "aborted")+ return INVALID;+ if (key.status === "dirty")+ status.dirty();+ if (value.status === "dirty")+ status.dirty();+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {+ finalObject[key.value] = value.value;+ }+ }+ return { status: status.value, value: finalObject };+ }+};+var INVALID = Object.freeze({+ status: "aborted"+});+var DIRTY = (value) => ({ status: "dirty", value });+var OK = (value) => ({ status: "valid", value });+var isAborted = (x) => x.status === "aborted";+var isDirty = (x) => x.status === "dirty";+var isValid = (x) => x.status === "valid";+var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;++// node_modules/zod/v3/helpers/errorUtil.js+var errorUtil;+(function(errorUtil2) {+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;+})(errorUtil || (errorUtil = {}));++// node_modules/zod/v3/types.js+var ParseInputLazyPath = class {+ constructor(parent, value, path3, key) {+ this._cachedPath = [];+ this.parent = parent;+ this.data = value;+ this._path = path3;+ this._key = key;+ }+ get path() {+ if (!this._cachedPath.length) {+ if (Array.isArray(this._key)) {+ this._cachedPath.push(...this._path, ...this._key);+ } else {+ this._cachedPath.push(...this._path, this._key);+ }+ }+ return this._cachedPath;+ }+};+var handleResult = (ctx, result) => {+ if (isValid(result)) {+ return { success: true, data: result.value };+ } else {+ if (!ctx.common.issues.length) {+ throw new Error("Validation failed but no issues detected.");+ }+ return {+ success: false,+ get error() {+ if (this._error)+ return this._error;+ const error2 = new ZodError2(ctx.common.issues);+ this._error = error2;+ return this._error;+ }+ };+ }+};+function processCreateParams(params) {+ if (!params)+ return {};+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;+ if (errorMap2 && (invalid_type_error || required_error)) {+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);+ }+ if (errorMap2)+ return { errorMap: errorMap2, description };+ const customMap = (iss, ctx) => {+ const { message } = params;+ if (iss.code === "invalid_enum_value") {+ return { message: message ?? ctx.defaultError };+ }+ if (typeof ctx.data === "undefined") {+ return { message: message ?? required_error ?? ctx.defaultError };+ }+ if (iss.code !== "invalid_type")+ return { message: ctx.defaultError };+ return { message: message ?? invalid_type_error ?? ctx.defaultError };+ };+ return { errorMap: customMap, description };+}+var ZodType2 = class {+ get description() {+ return this._def.description;+ }+ _getType(input) {+ return getParsedType2(input.data);+ }+ _getOrReturnCtx(input, ctx) {+ return ctx || {+ common: input.parent.common,+ data: input.data,+ parsedType: getParsedType2(input.data),+ schemaErrorMap: this._def.errorMap,+ path: input.path,+ parent: input.parent+ };+ }+ _processInputParams(input) {+ return {+ status: new ParseStatus(),+ ctx: {+ common: input.parent.common,+ data: input.data,+ parsedType: getParsedType2(input.data),+ schemaErrorMap: this._def.errorMap,+ path: input.path,+ parent: input.parent+ }+ };+ }+ _parseSync(input) {+ const result = this._parse(input);+ if (isAsync(result)) {+ throw new Error("Synchronous parse encountered promise.");+ }+ return result;+ }+ _parseAsync(input) {+ const result = this._parse(input);+ return Promise.resolve(result);+ }+ parse(data, params) {+ const result = this.safeParse(data, params);+ if (result.success)+ return result.data;+ throw result.error;+ }+ safeParse(data, params) {+ const ctx = {+ common: {+ issues: [],+ async: params?.async ?? false,+ contextualErrorMap: params?.errorMap+ },+ path: params?.path || [],+ schemaErrorMap: this._def.errorMap,+ parent: null,+ data,+ parsedType: getParsedType2(data)+ };+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });+ return handleResult(ctx, result);+ }+ "~validate"(data) {+ const ctx = {+ common: {+ issues: [],+ async: !!this["~standard"].async+ },+ path: [],+ schemaErrorMap: this._def.errorMap,+ parent: null,+ data,+ parsedType: getParsedType2(data)+ };+ if (!this["~standard"].async) {+ try {+ const result = this._parseSync({ data, path: [], parent: ctx });+ return isValid(result) ? {+ value: result.value+ } : {+ issues: ctx.common.issues+ };+ } catch (err) {+ if (err?.message?.toLowerCase()?.includes("encountered")) {+ this["~standard"].async = true;+ }+ ctx.common = {+ issues: [],+ async: true+ };+ }+ }+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {+ value: result.value+ } : {+ issues: ctx.common.issues+ });+ }+ async parseAsync(data, params) {+ const result = await this.safeParseAsync(data, params);+ if (result.success)+ return result.data;+ throw result.error;+ }+ async safeParseAsync(data, params) {+ const ctx = {+ common: {+ issues: [],+ contextualErrorMap: params?.errorMap,+ async: true+ },+ path: params?.path || [],+ schemaErrorMap: this._def.errorMap,+ parent: null,+ data,+ parsedType: getParsedType2(data)+ };+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));+ return handleResult(ctx, result);+ }+ refine(check2, message) {+ const getIssueProperties = (val) => {+ if (typeof message === "string" || typeof message === "undefined") {+ return { message };+ } else if (typeof message === "function") {+ return message(val);+ } else {+ return message;+ }+ };+ return this._refinement((val, ctx) => {+ const result = check2(val);+ const setError = () => ctx.addIssue({+ code: ZodIssueCode.custom,+ ...getIssueProperties(val)+ });+ if (typeof Promise !== "undefined" && result instanceof Promise) {+ return result.then((data) => {+ if (!data) {+ setError();+ return false;+ } else {+ return true;+ }+ });+ }+ if (!result) {+ setError();+ return false;+ } else {+ return true;+ }+ });+ }+ refinement(check2, refinementData) {+ return this._refinement((val, ctx) => {+ if (!check2(val)) {+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);+ return false;+ } else {+ return true;+ }+ });+ }+ _refinement(refinement) {+ return new ZodEffects({+ schema: this,+ typeName: ZodFirstPartyTypeKind.ZodEffects,+ effect: { type: "refinement", refinement }+ });+ }+ superRefine(refinement) {+ return this._refinement(refinement);+ }+ constructor(def) {+ this.spa = this.safeParseAsync;+ this._def = def;+ this.parse = this.parse.bind(this);+ this.safeParse = this.safeParse.bind(this);+ this.parseAsync = this.parseAsync.bind(this);+ this.safeParseAsync = this.safeParseAsync.bind(this);+ this.spa = this.spa.bind(this);+ this.refine = this.refine.bind(this);+ this.refinement = this.refinement.bind(this);+ this.superRefine = this.superRefine.bind(this);+ this.optional = this.optional.bind(this);+ this.nullable = this.nullable.bind(this);+ this.nullish = this.nullish.bind(this);+ this.array = this.array.bind(this);+ this.promise = this.promise.bind(this);+ this.or = this.or.bind(this);+ this.and = this.and.bind(this);+ this.transform = this.transform.bind(this);+ this.brand = this.brand.bind(this);+ this.default = this.default.bind(this);+ this.catch = this.catch.bind(this);+ this.describe = this.describe.bind(this);+ this.pipe = this.pipe.bind(this);+ this.readonly = this.readonly.bind(this);+ this.isNullable = this.isNullable.bind(this);+ this.isOptional = this.isOptional.bind(this);+ this["~standard"] = {+ version: 1,+ vendor: "zod",+ validate: (data) => this["~validate"](data)+ };+ }+ optional() {+ return ZodOptional2.create(this, this._def);+ }+ nullable() {+ return ZodNullable2.create(this, this._def);+ }+ nullish() {+ return this.nullable().optional();+ }+ array() {+ return ZodArray2.create(this);+ }+ promise() {+ return ZodPromise.create(this, this._def);+ }+ or(option) {+ return ZodUnion2.create([this, option], this._def);+ }+ and(incoming) {+ return ZodIntersection2.create(this, incoming, this._def);+ }+ transform(transform2) {+ return new ZodEffects({+ ...processCreateParams(this._def),+ schema: this,+ typeName: ZodFirstPartyTypeKind.ZodEffects,+ effect: { type: "transform", transform: transform2 }+ });+ }+ default(def) {+ const defaultValueFunc = typeof def === "function" ? def : () => def;+ return new ZodDefault2({+ ...processCreateParams(this._def),+ innerType: this,+ defaultValue: defaultValueFunc,+ typeName: ZodFirstPartyTypeKind.ZodDefault+ });+ }+ brand() {+ return new ZodBranded({+ typeName: ZodFirstPartyTypeKind.ZodBranded,+ type: this,+ ...processCreateParams(this._def)+ });+ }+ catch(def) {+ const catchValueFunc = typeof def === "function" ? def : () => def;+ return new ZodCatch2({+ ...processCreateParams(this._def),+ innerType: this,+ catchValue: catchValueFunc,+ typeName: ZodFirstPartyTypeKind.ZodCatch+ });+ }+ describe(description) {+ const This = this.constructor;+ return new This({+ ...this._def,+ description+ });+ }+ pipe(target) {+ return ZodPipeline.create(this, target);+ }+ readonly() {+ return ZodReadonly2.create(this);+ }+ isOptional() {+ return this.safeParse(void 0).success;+ }+ isNullable() {+ return this.safeParse(null).success;+ }+};+var cuidRegex = /^c[^\s-]{8,}$/i;+var cuid2Regex = /^[0-9a-z]+$/;+var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;+var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;+var nanoidRegex = /^[a-z0-9_-]{21}$/i;+var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;+var durationRegex = /^[-+]?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)?)??$/;+var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;+var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;+var emojiRegex;+var ipv4Regex = /^(?:(?: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])$/;+var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/;+var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;+var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;+var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;+var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;+var dateRegexSource = `((\\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])))`;+var dateRegex = new RegExp(`^${dateRegexSource}$`);+function timeRegexSource(args) {+ let secondsRegexSource = `[0-5]\\d`;+ if (args.precision) {+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;+ } else if (args.precision == null) {+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;+ }+ const secondsQuantifier = args.precision ? "+" : "?";+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;+}+function timeRegex(args) {+ return new RegExp(`^${timeRegexSource(args)}$`);+}+function datetimeRegex(args) {+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;+ const opts = [];+ opts.push(args.local ? `Z?` : `Z`);+ if (args.offset)+ opts.push(`([+-]\\d{2}:?\\d{2})`);+ regex = `${regex}(${opts.join("|")})`;+ return new RegExp(`^${regex}$`);+}+function isValidIP(ip, version4) {+ if ((version4 === "v4" || !version4) && ipv4Regex.test(ip)) {+ return true;+ }+ if ((version4 === "v6" || !version4) && ipv6Regex.test(ip)) {+ return true;+ }+ return false;+}+function isValidJWT2(jwt2, alg) {+ if (!jwtRegex.test(jwt2))+ return false;+ try {+ const [header] = jwt2.split(".");+ if (!header)+ return false;+ const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");+ const decoded = JSON.parse(atob(base642));+ if (typeof decoded !== "object" || decoded === null)+ return false;+ if ("typ" in decoded && decoded?.typ !== "JWT")+ return false;+ if (!decoded.alg)+ return false;+ if (alg && decoded.alg !== alg)+ return false;+ return true;+ } catch {+ return false;+ }+}+function isValidCidr(ip, version4) {+ if ((version4 === "v4" || !version4) && ipv4CidrRegex.test(ip)) {+ return true;+ }+ if ((version4 === "v6" || !version4) && ipv6CidrRegex.test(ip)) {+ return true;+ }+ return false;+}+var ZodString2 = class _ZodString2 extends ZodType2 {+ _parse(input) {+ if (this._def.coerce) {+ input.data = String(input.data);+ }+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.string) {+ const ctx2 = this._getOrReturnCtx(input);+ addIssueToContext(ctx2, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.string,+ received: ctx2.parsedType+ });+ return INVALID;+ }+ const status = new ParseStatus();+ let ctx = void 0;+ for (const check2 of this._def.checks) {+ if (check2.kind === "min") {+ if (input.data.length < check2.value) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: check2.value,+ type: "string",+ inclusive: true,+ exact: false,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "max") {+ if (input.data.length > check2.value) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: check2.value,+ type: "string",+ inclusive: true,+ exact: false,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "length") {+ const tooBig = input.data.length > check2.value;+ const tooSmall = input.data.length < check2.value;+ if (tooBig || tooSmall) {+ ctx = this._getOrReturnCtx(input, ctx);+ if (tooBig) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: check2.value,+ type: "string",+ inclusive: true,+ exact: true,+ message: check2.message+ });+ } else if (tooSmall) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: check2.value,+ type: "string",+ inclusive: true,+ exact: true,+ message: check2.message+ });+ }+ status.dirty();+ }+ } else if (check2.kind === "email") {+ if (!emailRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "email",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "emoji") {+ if (!emojiRegex) {+ emojiRegex = new RegExp(_emojiRegex, "u");+ }+ if (!emojiRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "emoji",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "uuid") {+ if (!uuidRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "uuid",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "nanoid") {+ if (!nanoidRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "nanoid",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "cuid") {+ if (!cuidRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "cuid",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "cuid2") {+ if (!cuid2Regex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "cuid2",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "ulid") {+ if (!ulidRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "ulid",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "url") {+ try {+ new URL(input.data);+ } catch {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "url",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "regex") {+ check2.regex.lastIndex = 0;+ const testResult = check2.regex.test(input.data);+ if (!testResult) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "regex",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "trim") {+ input.data = input.data.trim();+ } else if (check2.kind === "includes") {+ if (!input.data.includes(check2.value, check2.position)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: { includes: check2.value, position: check2.position },+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "toLowerCase") {+ input.data = input.data.toLowerCase();+ } else if (check2.kind === "toUpperCase") {+ input.data = input.data.toUpperCase();+ } else if (check2.kind === "startsWith") {+ if (!input.data.startsWith(check2.value)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: { startsWith: check2.value },+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "endsWith") {+ if (!input.data.endsWith(check2.value)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: { endsWith: check2.value },+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "datetime") {+ const regex = datetimeRegex(check2);+ if (!regex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: "datetime",+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "date") {+ const regex = dateRegex;+ if (!regex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: "date",+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "time") {+ const regex = timeRegex(check2);+ if (!regex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_string,+ validation: "time",+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "duration") {+ if (!durationRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "duration",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "ip") {+ if (!isValidIP(input.data, check2.version)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "ip",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "jwt") {+ if (!isValidJWT2(input.data, check2.alg)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "jwt",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "cidr") {+ if (!isValidCidr(input.data, check2.version)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "cidr",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "base64") {+ if (!base64Regex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "base64",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "base64url") {+ if (!base64urlRegex.test(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ validation: "base64url",+ code: ZodIssueCode.invalid_string,+ message: check2.message+ });+ status.dirty();+ }+ } else {+ util.assertNever(check2);+ }+ }+ return { status: status.value, value: input.data };+ }+ _regex(regex, validation, message) {+ return this.refinement((data) => regex.test(data), {+ validation,+ code: ZodIssueCode.invalid_string,+ ...errorUtil.errToObj(message)+ });+ }+ _addCheck(check2) {+ return new _ZodString2({+ ...this._def,+ checks: [...this._def.checks, check2]+ });+ }+ email(message) {+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });+ }+ url(message) {+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });+ }+ emoji(message) {+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });+ }+ uuid(message) {+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });+ }+ nanoid(message) {+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });+ }+ cuid(message) {+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });+ }+ cuid2(message) {+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });+ }+ ulid(message) {+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });+ }+ base64(message) {+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });+ }+ base64url(message) {+ return this._addCheck({+ kind: "base64url",+ ...errorUtil.errToObj(message)+ });+ }+ jwt(options) {+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });+ }+ ip(options) {+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });+ }+ cidr(options) {+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });+ }+ datetime(options) {+ if (typeof options === "string") {+ return this._addCheck({+ kind: "datetime",+ precision: null,+ offset: false,+ local: false,+ message: options+ });+ }+ return this._addCheck({+ kind: "datetime",+ precision: typeof options?.precision === "undefined" ? null : options?.precision,+ offset: options?.offset ?? false,+ local: options?.local ?? false,+ ...errorUtil.errToObj(options?.message)+ });+ }+ date(message) {+ return this._addCheck({ kind: "date", message });+ }+ time(options) {+ if (typeof options === "string") {+ return this._addCheck({+ kind: "time",+ precision: null,+ message: options+ });+ }+ return this._addCheck({+ kind: "time",+ precision: typeof options?.precision === "undefined" ? null : options?.precision,+ ...errorUtil.errToObj(options?.message)+ });+ }+ duration(message) {+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });+ }+ regex(regex, message) {+ return this._addCheck({+ kind: "regex",+ regex,+ ...errorUtil.errToObj(message)+ });+ }+ includes(value, options) {+ return this._addCheck({+ kind: "includes",+ value,+ position: options?.position,+ ...errorUtil.errToObj(options?.message)+ });+ }+ startsWith(value, message) {+ return this._addCheck({+ kind: "startsWith",+ value,+ ...errorUtil.errToObj(message)+ });+ }+ endsWith(value, message) {+ return this._addCheck({+ kind: "endsWith",+ value,+ ...errorUtil.errToObj(message)+ });+ }+ min(minLength, message) {+ return this._addCheck({+ kind: "min",+ value: minLength,+ ...errorUtil.errToObj(message)+ });+ }+ max(maxLength, message) {+ return this._addCheck({+ kind: "max",+ value: maxLength,+ ...errorUtil.errToObj(message)+ });+ }+ length(len, message) {+ return this._addCheck({+ kind: "length",+ value: len,+ ...errorUtil.errToObj(message)+ });+ }+ /**+ * Equivalent to `.min(1)`+ */+ nonempty(message) {+ return this.min(1, errorUtil.errToObj(message));+ }+ trim() {+ return new _ZodString2({+ ...this._def,+ checks: [...this._def.checks, { kind: "trim" }]+ });+ }+ toLowerCase() {+ return new _ZodString2({+ ...this._def,+ checks: [...this._def.checks, { kind: "toLowerCase" }]+ });+ }+ toUpperCase() {+ return new _ZodString2({+ ...this._def,+ checks: [...this._def.checks, { kind: "toUpperCase" }]+ });+ }+ get isDatetime() {+ return !!this._def.checks.find((ch) => ch.kind === "datetime");+ }+ get isDate() {+ return !!this._def.checks.find((ch) => ch.kind === "date");+ }+ get isTime() {+ return !!this._def.checks.find((ch) => ch.kind === "time");+ }+ get isDuration() {+ return !!this._def.checks.find((ch) => ch.kind === "duration");+ }+ get isEmail() {+ return !!this._def.checks.find((ch) => ch.kind === "email");+ }+ get isURL() {+ return !!this._def.checks.find((ch) => ch.kind === "url");+ }+ get isEmoji() {+ return !!this._def.checks.find((ch) => ch.kind === "emoji");+ }+ get isUUID() {+ return !!this._def.checks.find((ch) => ch.kind === "uuid");+ }+ get isNANOID() {+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");+ }+ get isCUID() {+ return !!this._def.checks.find((ch) => ch.kind === "cuid");+ }+ get isCUID2() {+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");+ }+ get isULID() {+ return !!this._def.checks.find((ch) => ch.kind === "ulid");+ }+ get isIP() {+ return !!this._def.checks.find((ch) => ch.kind === "ip");+ }+ get isCIDR() {+ return !!this._def.checks.find((ch) => ch.kind === "cidr");+ }+ get isBase64() {+ return !!this._def.checks.find((ch) => ch.kind === "base64");+ }+ get isBase64url() {+ return !!this._def.checks.find((ch) => ch.kind === "base64url");+ }+ get minLength() {+ let min = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "min") {+ if (min === null || ch.value > min)+ min = ch.value;+ }+ }+ return min;+ }+ get maxLength() {+ let max = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "max") {+ if (max === null || ch.value < max)+ max = ch.value;+ }+ }+ return max;+ }+};+ZodString2.create = (params) => {+ return new ZodString2({+ checks: [],+ typeName: ZodFirstPartyTypeKind.ZodString,+ coerce: params?.coerce ?? false,+ ...processCreateParams(params)+ });+};+function floatSafeRemainder2(val, step) {+ const valDecCount = (val.toString().split(".")[1] || "").length;+ const stepDecCount = (step.toString().split(".")[1] || "").length;+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));+ return valInt % stepInt / 10 ** decCount;+}+var ZodNumber2 = class _ZodNumber extends ZodType2 {+ constructor() {+ super(...arguments);+ this.min = this.gte;+ this.max = this.lte;+ this.step = this.multipleOf;+ }+ _parse(input) {+ if (this._def.coerce) {+ input.data = Number(input.data);+ }+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.number) {+ const ctx2 = this._getOrReturnCtx(input);+ addIssueToContext(ctx2, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.number,+ received: ctx2.parsedType+ });+ return INVALID;+ }+ let ctx = void 0;+ const status = new ParseStatus();+ for (const check2 of this._def.checks) {+ if (check2.kind === "int") {+ if (!util.isInteger(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: "integer",+ received: "float",+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "min") {+ const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;+ if (tooSmall) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: check2.value,+ type: "number",+ inclusive: check2.inclusive,+ exact: false,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "max") {+ const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;+ if (tooBig) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: check2.value,+ type: "number",+ inclusive: check2.inclusive,+ exact: false,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "multipleOf") {+ if (floatSafeRemainder2(input.data, check2.value) !== 0) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.not_multiple_of,+ multipleOf: check2.value,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "finite") {+ if (!Number.isFinite(input.data)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.not_finite,+ message: check2.message+ });+ status.dirty();+ }+ } else {+ util.assertNever(check2);+ }+ }+ return { status: status.value, value: input.data };+ }+ gte(value, message) {+ return this.setLimit("min", value, true, errorUtil.toString(message));+ }+ gt(value, message) {+ return this.setLimit("min", value, false, errorUtil.toString(message));+ }+ lte(value, message) {+ return this.setLimit("max", value, true, errorUtil.toString(message));+ }+ lt(value, message) {+ return this.setLimit("max", value, false, errorUtil.toString(message));+ }+ setLimit(kind, value, inclusive, message) {+ return new _ZodNumber({+ ...this._def,+ checks: [+ ...this._def.checks,+ {+ kind,+ value,+ inclusive,+ message: errorUtil.toString(message)+ }+ ]+ });+ }+ _addCheck(check2) {+ return new _ZodNumber({+ ...this._def,+ checks: [...this._def.checks, check2]+ });+ }+ int(message) {+ return this._addCheck({+ kind: "int",+ message: errorUtil.toString(message)+ });+ }+ positive(message) {+ return this._addCheck({+ kind: "min",+ value: 0,+ inclusive: false,+ message: errorUtil.toString(message)+ });+ }+ negative(message) {+ return this._addCheck({+ kind: "max",+ value: 0,+ inclusive: false,+ message: errorUtil.toString(message)+ });+ }+ nonpositive(message) {+ return this._addCheck({+ kind: "max",+ value: 0,+ inclusive: true,+ message: errorUtil.toString(message)+ });+ }+ nonnegative(message) {+ return this._addCheck({+ kind: "min",+ value: 0,+ inclusive: true,+ message: errorUtil.toString(message)+ });+ }+ multipleOf(value, message) {+ return this._addCheck({+ kind: "multipleOf",+ value,+ message: errorUtil.toString(message)+ });+ }+ finite(message) {+ return this._addCheck({+ kind: "finite",+ message: errorUtil.toString(message)+ });+ }+ safe(message) {+ return this._addCheck({+ kind: "min",+ inclusive: true,+ value: Number.MIN_SAFE_INTEGER,+ message: errorUtil.toString(message)+ })._addCheck({+ kind: "max",+ inclusive: true,+ value: Number.MAX_SAFE_INTEGER,+ message: errorUtil.toString(message)+ });+ }+ get minValue() {+ let min = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "min") {+ if (min === null || ch.value > min)+ min = ch.value;+ }+ }+ return min;+ }+ get maxValue() {+ let max = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "max") {+ if (max === null || ch.value < max)+ max = ch.value;+ }+ }+ return max;+ }+ get isInt() {+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));+ }+ get isFinite() {+ let max = null;+ let min = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {+ return true;+ } else if (ch.kind === "min") {+ if (min === null || ch.value > min)+ min = ch.value;+ } else if (ch.kind === "max") {+ if (max === null || ch.value < max)+ max = ch.value;+ }+ }+ return Number.isFinite(min) && Number.isFinite(max);+ }+};+ZodNumber2.create = (params) => {+ return new ZodNumber2({+ checks: [],+ typeName: ZodFirstPartyTypeKind.ZodNumber,+ coerce: params?.coerce || false,+ ...processCreateParams(params)+ });+};+var ZodBigInt = class _ZodBigInt extends ZodType2 {+ constructor() {+ super(...arguments);+ this.min = this.gte;+ this.max = this.lte;+ }+ _parse(input) {+ if (this._def.coerce) {+ try {+ input.data = BigInt(input.data);+ } catch {+ return this._getInvalidInput(input);+ }+ }+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.bigint) {+ return this._getInvalidInput(input);+ }+ let ctx = void 0;+ const status = new ParseStatus();+ for (const check2 of this._def.checks) {+ if (check2.kind === "min") {+ const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;+ if (tooSmall) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ type: "bigint",+ minimum: check2.value,+ inclusive: check2.inclusive,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "max") {+ const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;+ if (tooBig) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ type: "bigint",+ maximum: check2.value,+ inclusive: check2.inclusive,+ message: check2.message+ });+ status.dirty();+ }+ } else if (check2.kind === "multipleOf") {+ if (input.data % check2.value !== BigInt(0)) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.not_multiple_of,+ multipleOf: check2.value,+ message: check2.message+ });+ status.dirty();+ }+ } else {+ util.assertNever(check2);+ }+ }+ return { status: status.value, value: input.data };+ }+ _getInvalidInput(input) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.bigint,+ received: ctx.parsedType+ });+ return INVALID;+ }+ gte(value, message) {+ return this.setLimit("min", value, true, errorUtil.toString(message));+ }+ gt(value, message) {+ return this.setLimit("min", value, false, errorUtil.toString(message));+ }+ lte(value, message) {+ return this.setLimit("max", value, true, errorUtil.toString(message));+ }+ lt(value, message) {+ return this.setLimit("max", value, false, errorUtil.toString(message));+ }+ setLimit(kind, value, inclusive, message) {+ return new _ZodBigInt({+ ...this._def,+ checks: [+ ...this._def.checks,+ {+ kind,+ value,+ inclusive,+ message: errorUtil.toString(message)+ }+ ]+ });+ }+ _addCheck(check2) {+ return new _ZodBigInt({+ ...this._def,+ checks: [...this._def.checks, check2]+ });+ }+ positive(message) {+ return this._addCheck({+ kind: "min",+ value: BigInt(0),+ inclusive: false,+ message: errorUtil.toString(message)+ });+ }+ negative(message) {+ return this._addCheck({+ kind: "max",+ value: BigInt(0),+ inclusive: false,+ message: errorUtil.toString(message)+ });+ }+ nonpositive(message) {+ return this._addCheck({+ kind: "max",+ value: BigInt(0),+ inclusive: true,+ message: errorUtil.toString(message)+ });+ }+ nonnegative(message) {+ return this._addCheck({+ kind: "min",+ value: BigInt(0),+ inclusive: true,+ message: errorUtil.toString(message)+ });+ }+ multipleOf(value, message) {+ return this._addCheck({+ kind: "multipleOf",+ value,+ message: errorUtil.toString(message)+ });+ }+ get minValue() {+ let min = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "min") {+ if (min === null || ch.value > min)+ min = ch.value;+ }+ }+ return min;+ }+ get maxValue() {+ let max = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "max") {+ if (max === null || ch.value < max)+ max = ch.value;+ }+ }+ return max;+ }+};+ZodBigInt.create = (params) => {+ return new ZodBigInt({+ checks: [],+ typeName: ZodFirstPartyTypeKind.ZodBigInt,+ coerce: params?.coerce ?? false,+ ...processCreateParams(params)+ });+};+var ZodBoolean2 = class extends ZodType2 {+ _parse(input) {+ if (this._def.coerce) {+ input.data = Boolean(input.data);+ }+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.boolean) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.boolean,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return OK(input.data);+ }+};+ZodBoolean2.create = (params) => {+ return new ZodBoolean2({+ typeName: ZodFirstPartyTypeKind.ZodBoolean,+ coerce: params?.coerce || false,+ ...processCreateParams(params)+ });+};+var ZodDate = class _ZodDate extends ZodType2 {+ _parse(input) {+ if (this._def.coerce) {+ input.data = new Date(input.data);+ }+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.date) {+ const ctx2 = this._getOrReturnCtx(input);+ addIssueToContext(ctx2, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.date,+ received: ctx2.parsedType+ });+ return INVALID;+ }+ if (Number.isNaN(input.data.getTime())) {+ const ctx2 = this._getOrReturnCtx(input);+ addIssueToContext(ctx2, {+ code: ZodIssueCode.invalid_date+ });+ return INVALID;+ }+ const status = new ParseStatus();+ let ctx = void 0;+ for (const check2 of this._def.checks) {+ if (check2.kind === "min") {+ if (input.data.getTime() < check2.value) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ message: check2.message,+ inclusive: true,+ exact: false,+ minimum: check2.value,+ type: "date"+ });+ status.dirty();+ }+ } else if (check2.kind === "max") {+ if (input.data.getTime() > check2.value) {+ ctx = this._getOrReturnCtx(input, ctx);+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ message: check2.message,+ inclusive: true,+ exact: false,+ maximum: check2.value,+ type: "date"+ });+ status.dirty();+ }+ } else {+ util.assertNever(check2);+ }+ }+ return {+ status: status.value,+ value: new Date(input.data.getTime())+ };+ }+ _addCheck(check2) {+ return new _ZodDate({+ ...this._def,+ checks: [...this._def.checks, check2]+ });+ }+ min(minDate, message) {+ return this._addCheck({+ kind: "min",+ value: minDate.getTime(),+ message: errorUtil.toString(message)+ });+ }+ max(maxDate, message) {+ return this._addCheck({+ kind: "max",+ value: maxDate.getTime(),+ message: errorUtil.toString(message)+ });+ }+ get minDate() {+ let min = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "min") {+ if (min === null || ch.value > min)+ min = ch.value;+ }+ }+ return min != null ? new Date(min) : null;+ }+ get maxDate() {+ let max = null;+ for (const ch of this._def.checks) {+ if (ch.kind === "max") {+ if (max === null || ch.value < max)+ max = ch.value;+ }+ }+ return max != null ? new Date(max) : null;+ }+};+ZodDate.create = (params) => {+ return new ZodDate({+ checks: [],+ coerce: params?.coerce || false,+ typeName: ZodFirstPartyTypeKind.ZodDate,+ ...processCreateParams(params)+ });+};+var ZodSymbol = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.symbol) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.symbol,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return OK(input.data);+ }+};+ZodSymbol.create = (params) => {+ return new ZodSymbol({+ typeName: ZodFirstPartyTypeKind.ZodSymbol,+ ...processCreateParams(params)+ });+};+var ZodUndefined = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.undefined) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.undefined,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return OK(input.data);+ }+};+ZodUndefined.create = (params) => {+ return new ZodUndefined({+ typeName: ZodFirstPartyTypeKind.ZodUndefined,+ ...processCreateParams(params)+ });+};+var ZodNull2 = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.null) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.null,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return OK(input.data);+ }+};+ZodNull2.create = (params) => {+ return new ZodNull2({+ typeName: ZodFirstPartyTypeKind.ZodNull,+ ...processCreateParams(params)+ });+};+var ZodAny = class extends ZodType2 {+ constructor() {+ super(...arguments);+ this._any = true;+ }+ _parse(input) {+ return OK(input.data);+ }+};+ZodAny.create = (params) => {+ return new ZodAny({+ typeName: ZodFirstPartyTypeKind.ZodAny,+ ...processCreateParams(params)+ });+};+var ZodUnknown2 = class extends ZodType2 {+ constructor() {+ super(...arguments);+ this._unknown = true;+ }+ _parse(input) {+ return OK(input.data);+ }+};+ZodUnknown2.create = (params) => {+ return new ZodUnknown2({+ typeName: ZodFirstPartyTypeKind.ZodUnknown,+ ...processCreateParams(params)+ });+};+var ZodNever2 = class extends ZodType2 {+ _parse(input) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.never,+ received: ctx.parsedType+ });+ return INVALID;+ }+};+ZodNever2.create = (params) => {+ return new ZodNever2({+ typeName: ZodFirstPartyTypeKind.ZodNever,+ ...processCreateParams(params)+ });+};+var ZodVoid = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.undefined) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.void,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return OK(input.data);+ }+};+ZodVoid.create = (params) => {+ return new ZodVoid({+ typeName: ZodFirstPartyTypeKind.ZodVoid,+ ...processCreateParams(params)+ });+};+var ZodArray2 = class _ZodArray extends ZodType2 {+ _parse(input) {+ const { ctx, status } = this._processInputParams(input);+ const def = this._def;+ if (ctx.parsedType !== ZodParsedType.array) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.array,+ received: ctx.parsedType+ });+ return INVALID;+ }+ if (def.exactLength !== null) {+ const tooBig = ctx.data.length > def.exactLength.value;+ const tooSmall = ctx.data.length < def.exactLength.value;+ if (tooBig || tooSmall) {+ addIssueToContext(ctx, {+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,+ minimum: tooSmall ? def.exactLength.value : void 0,+ maximum: tooBig ? def.exactLength.value : void 0,+ type: "array",+ inclusive: true,+ exact: true,+ message: def.exactLength.message+ });+ status.dirty();+ }+ }+ if (def.minLength !== null) {+ if (ctx.data.length < def.minLength.value) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: def.minLength.value,+ type: "array",+ inclusive: true,+ exact: false,+ message: def.minLength.message+ });+ status.dirty();+ }+ }+ if (def.maxLength !== null) {+ if (ctx.data.length > def.maxLength.value) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: def.maxLength.value,+ type: "array",+ inclusive: true,+ exact: false,+ message: def.maxLength.message+ });+ status.dirty();+ }+ }+ if (ctx.common.async) {+ return Promise.all([...ctx.data].map((item, i) => {+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));+ })).then((result2) => {+ return ParseStatus.mergeArray(status, result2);+ });+ }+ const result = [...ctx.data].map((item, i) => {+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));+ });+ return ParseStatus.mergeArray(status, result);+ }+ get element() {+ return this._def.type;+ }+ min(minLength, message) {+ return new _ZodArray({+ ...this._def,+ minLength: { value: minLength, message: errorUtil.toString(message) }+ });+ }+ max(maxLength, message) {+ return new _ZodArray({+ ...this._def,+ maxLength: { value: maxLength, message: errorUtil.toString(message) }+ });+ }+ length(len, message) {+ return new _ZodArray({+ ...this._def,+ exactLength: { value: len, message: errorUtil.toString(message) }+ });+ }+ nonempty(message) {+ return this.min(1, message);+ }+};+ZodArray2.create = (schema, params) => {+ return new ZodArray2({+ type: schema,+ minLength: null,+ maxLength: null,+ exactLength: null,+ typeName: ZodFirstPartyTypeKind.ZodArray,+ ...processCreateParams(params)+ });+};+function deepPartialify(schema) {+ if (schema instanceof ZodObject2) {+ const newShape = {};+ for (const key in schema.shape) {+ const fieldSchema = schema.shape[key];+ newShape[key] = ZodOptional2.create(deepPartialify(fieldSchema));+ }+ return new ZodObject2({+ ...schema._def,+ shape: () => newShape+ });+ } else if (schema instanceof ZodArray2) {+ return new ZodArray2({+ ...schema._def,+ type: deepPartialify(schema.element)+ });+ } else if (schema instanceof ZodOptional2) {+ return ZodOptional2.create(deepPartialify(schema.unwrap()));+ } else if (schema instanceof ZodNullable2) {+ return ZodNullable2.create(deepPartialify(schema.unwrap()));+ } else if (schema instanceof ZodTuple) {+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));+ } else {+ return schema;+ }+}+var ZodObject2 = class _ZodObject extends ZodType2 {+ constructor() {+ super(...arguments);+ this._cached = null;+ this.nonstrict = this.passthrough;+ this.augment = this.extend;+ }+ _getCached() {+ if (this._cached !== null)+ return this._cached;+ const shape = this._def.shape();+ const keys = util.objectKeys(shape);+ this._cached = { shape, keys };+ return this._cached;+ }+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.object) {+ const ctx2 = this._getOrReturnCtx(input);+ addIssueToContext(ctx2, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.object,+ received: ctx2.parsedType+ });+ return INVALID;+ }+ const { status, ctx } = this._processInputParams(input);+ const { shape, keys: shapeKeys } = this._getCached();+ const extraKeys = [];+ if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) {+ for (const key in ctx.data) {+ if (!shapeKeys.includes(key)) {+ extraKeys.push(key);+ }+ }+ }+ const pairs = [];+ for (const key of shapeKeys) {+ const keyValidator = shape[key];+ const value = ctx.data[key];+ pairs.push({+ key: { status: "valid", value: key },+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),+ alwaysSet: key in ctx.data+ });+ }+ if (this._def.catchall instanceof ZodNever2) {+ const unknownKeys = this._def.unknownKeys;+ if (unknownKeys === "passthrough") {+ for (const key of extraKeys) {+ pairs.push({+ key: { status: "valid", value: key },+ value: { status: "valid", value: ctx.data[key] }+ });+ }+ } else if (unknownKeys === "strict") {+ if (extraKeys.length > 0) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.unrecognized_keys,+ keys: extraKeys+ });+ status.dirty();+ }+ } else if (unknownKeys === "strip") {+ } else {+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);+ }+ } else {+ const catchall = this._def.catchall;+ for (const key of extraKeys) {+ const value = ctx.data[key];+ pairs.push({+ key: { status: "valid", value: key },+ value: catchall._parse(+ new ParseInputLazyPath(ctx, value, ctx.path, key)+ //, ctx.child(key), value, getParsedType(value)+ ),+ alwaysSet: key in ctx.data+ });+ }+ }+ if (ctx.common.async) {+ return Promise.resolve().then(async () => {+ const syncPairs = [];+ for (const pair of pairs) {+ const key = await pair.key;+ const value = await pair.value;+ syncPairs.push({+ key,+ value,+ alwaysSet: pair.alwaysSet+ });+ }+ return syncPairs;+ }).then((syncPairs) => {+ return ParseStatus.mergeObjectSync(status, syncPairs);+ });+ } else {+ return ParseStatus.mergeObjectSync(status, pairs);+ }+ }+ get shape() {+ return this._def.shape();+ }+ strict(message) {+ errorUtil.errToObj;+ return new _ZodObject({+ ...this._def,+ unknownKeys: "strict",+ ...message !== void 0 ? {+ errorMap: (issue2, ctx) => {+ const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError;+ if (issue2.code === "unrecognized_keys")+ return {+ message: errorUtil.errToObj(message).message ?? defaultError+ };+ return {+ message: defaultError+ };+ }+ } : {}+ });+ }+ strip() {+ return new _ZodObject({+ ...this._def,+ unknownKeys: "strip"+ });+ }+ passthrough() {+ return new _ZodObject({+ ...this._def,+ unknownKeys: "passthrough"+ });+ }+ // const AugmentFactory =+ // <Def extends ZodObjectDef>(def: Def) =>+ // <Augmentation extends ZodRawShape>(+ // augmentation: Augmentation+ // ): ZodObject<+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,+ // Def["unknownKeys"],+ // Def["catchall"]+ // > => {+ // return new ZodObject({+ // ...def,+ // shape: () => ({+ // ...def.shape(),+ // ...augmentation,+ // }),+ // }) as any;+ // };+ extend(augmentation) {+ return new _ZodObject({+ ...this._def,+ shape: () => ({+ ...this._def.shape(),+ ...augmentation+ })+ });+ }+ /**+ * Prior to [email protected] there was a bug in the+ * inferred type of merged objects. Please+ * upgrade if you are experiencing issues.+ */+ merge(merging) {+ const merged = new _ZodObject({+ unknownKeys: merging._def.unknownKeys,+ catchall: merging._def.catchall,+ shape: () => ({+ ...this._def.shape(),+ ...merging._def.shape()+ }),+ typeName: ZodFirstPartyTypeKind.ZodObject+ });+ return merged;+ }+ // merge<+ // Incoming extends AnyZodObject,+ // Augmentation extends Incoming["shape"],+ // NewOutput extends {+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation+ // ? Augmentation[k]["_output"]+ // : k extends keyof Output+ // ? Output[k]+ // : never;+ // },+ // NewInput extends {+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation+ // ? Augmentation[k]["_input"]+ // : k extends keyof Input+ // ? Input[k]+ // : never;+ // }+ // >(+ // merging: Incoming+ // ): ZodObject<+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,+ // Incoming["_def"]["unknownKeys"],+ // Incoming["_def"]["catchall"],+ // NewOutput,+ // NewInput+ // > {+ // const merged: any = new ZodObject({+ // unknownKeys: merging._def.unknownKeys,+ // catchall: merging._def.catchall,+ // shape: () =>+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),+ // typeName: ZodFirstPartyTypeKind.ZodObject,+ // }) as any;+ // return merged;+ // }+ setKey(key, schema) {+ return this.augment({ [key]: schema });+ }+ // merge<Incoming extends AnyZodObject>(+ // merging: Incoming+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {+ // ZodObject<+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,+ // Incoming["_def"]["unknownKeys"],+ // Incoming["_def"]["catchall"]+ // > {+ // // const mergedShape = objectUtil.mergeShapes(+ // // this._def.shape(),+ // // merging._def.shape()+ // // );+ // const merged: any = new ZodObject({+ // unknownKeys: merging._def.unknownKeys,+ // catchall: merging._def.catchall,+ // shape: () =>+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),+ // typeName: ZodFirstPartyTypeKind.ZodObject,+ // }) as any;+ // return merged;+ // }+ catchall(index) {+ return new _ZodObject({+ ...this._def,+ catchall: index+ });+ }+ pick(mask) {+ const shape = {};+ for (const key of util.objectKeys(mask)) {+ if (mask[key] && this.shape[key]) {+ shape[key] = this.shape[key];+ }+ }+ return new _ZodObject({+ ...this._def,+ shape: () => shape+ });+ }+ omit(mask) {+ const shape = {};+ for (const key of util.objectKeys(this.shape)) {+ if (!mask[key]) {+ shape[key] = this.shape[key];+ }+ }+ return new _ZodObject({+ ...this._def,+ shape: () => shape+ });+ }+ /**+ * @deprecated+ */+ deepPartial() {+ return deepPartialify(this);+ }+ partial(mask) {+ const newShape = {};+ for (const key of util.objectKeys(this.shape)) {+ const fieldSchema = this.shape[key];+ if (mask && !mask[key]) {+ newShape[key] = fieldSchema;+ } else {+ newShape[key] = fieldSchema.optional();+ }+ }+ return new _ZodObject({+ ...this._def,+ shape: () => newShape+ });+ }+ required(mask) {+ const newShape = {};+ for (const key of util.objectKeys(this.shape)) {+ if (mask && !mask[key]) {+ newShape[key] = this.shape[key];+ } else {+ const fieldSchema = this.shape[key];+ let newField = fieldSchema;+ while (newField instanceof ZodOptional2) {+ newField = newField._def.innerType;+ }+ newShape[key] = newField;+ }+ }+ return new _ZodObject({+ ...this._def,+ shape: () => newShape+ });+ }+ keyof() {+ return createZodEnum(util.objectKeys(this.shape));+ }+};+ZodObject2.create = (shape, params) => {+ return new ZodObject2({+ shape: () => shape,+ unknownKeys: "strip",+ catchall: ZodNever2.create(),+ typeName: ZodFirstPartyTypeKind.ZodObject,+ ...processCreateParams(params)+ });+};+ZodObject2.strictCreate = (shape, params) => {+ return new ZodObject2({+ shape: () => shape,+ unknownKeys: "strict",+ catchall: ZodNever2.create(),+ typeName: ZodFirstPartyTypeKind.ZodObject,+ ...processCreateParams(params)+ });+};+ZodObject2.lazycreate = (shape, params) => {+ return new ZodObject2({+ shape,+ unknownKeys: "strip",+ catchall: ZodNever2.create(),+ typeName: ZodFirstPartyTypeKind.ZodObject,+ ...processCreateParams(params)+ });+};+var ZodUnion2 = class extends ZodType2 {+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ const options = this._def.options;+ function handleResults(results) {+ for (const result of results) {+ if (result.result.status === "valid") {+ return result.result;+ }+ }+ for (const result of results) {+ if (result.result.status === "dirty") {+ ctx.common.issues.push(...result.ctx.common.issues);+ return result.result;+ }+ }+ const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues));+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_union,+ unionErrors+ });+ return INVALID;+ }+ if (ctx.common.async) {+ return Promise.all(options.map(async (option) => {+ const childCtx = {+ ...ctx,+ common: {+ ...ctx.common,+ issues: []+ },+ parent: null+ };+ return {+ result: await option._parseAsync({+ data: ctx.data,+ path: ctx.path,+ parent: childCtx+ }),+ ctx: childCtx+ };+ })).then(handleResults);+ } else {+ let dirty = void 0;+ const issues = [];+ for (const option of options) {+ const childCtx = {+ ...ctx,+ common: {+ ...ctx.common,+ issues: []+ },+ parent: null+ };+ const result = option._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: childCtx+ });+ if (result.status === "valid") {+ return result;+ } else if (result.status === "dirty" && !dirty) {+ dirty = { result, ctx: childCtx };+ }+ if (childCtx.common.issues.length) {+ issues.push(childCtx.common.issues);+ }+ }+ if (dirty) {+ ctx.common.issues.push(...dirty.ctx.common.issues);+ return dirty.result;+ }+ const unionErrors = issues.map((issues2) => new ZodError2(issues2));+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_union,+ unionErrors+ });+ return INVALID;+ }+ }+ get options() {+ return this._def.options;+ }+};+ZodUnion2.create = (types, params) => {+ return new ZodUnion2({+ options: types,+ typeName: ZodFirstPartyTypeKind.ZodUnion,+ ...processCreateParams(params)+ });+};+var getDiscriminator = (type) => {+ if (type instanceof ZodLazy) {+ return getDiscriminator(type.schema);+ } else if (type instanceof ZodEffects) {+ return getDiscriminator(type.innerType());+ } else if (type instanceof ZodLiteral2) {+ return [type.value];+ } else if (type instanceof ZodEnum2) {+ return type.options;+ } else if (type instanceof ZodNativeEnum) {+ return util.objectValues(type.enum);+ } else if (type instanceof ZodDefault2) {+ return getDiscriminator(type._def.innerType);+ } else if (type instanceof ZodUndefined) {+ return [void 0];+ } else if (type instanceof ZodNull2) {+ return [null];+ } else if (type instanceof ZodOptional2) {+ return [void 0, ...getDiscriminator(type.unwrap())];+ } else if (type instanceof ZodNullable2) {+ return [null, ...getDiscriminator(type.unwrap())];+ } else if (type instanceof ZodBranded) {+ return getDiscriminator(type.unwrap());+ } else if (type instanceof ZodReadonly2) {+ return getDiscriminator(type.unwrap());+ } else if (type instanceof ZodCatch2) {+ return getDiscriminator(type._def.innerType);+ } else {+ return [];+ }+};+var ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 {+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.object) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.object,+ received: ctx.parsedType+ });+ return INVALID;+ }+ const discriminator = this.discriminator;+ const discriminatorValue = ctx.data[discriminator];+ const option = this.optionsMap.get(discriminatorValue);+ if (!option) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_union_discriminator,+ options: Array.from(this.optionsMap.keys()),+ path: [discriminator]+ });+ return INVALID;+ }+ if (ctx.common.async) {+ return option._parseAsync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ } else {+ return option._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ }+ }+ get discriminator() {+ return this._def.discriminator;+ }+ get options() {+ return this._def.options;+ }+ get optionsMap() {+ return this._def.optionsMap;+ }+ /**+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must+ * have a different value for each object in the union.+ * @param discriminator the name of the discriminator property+ * @param types an array of object schemas+ * @param params+ */+ static create(discriminator, options, params) {+ const optionsMap = /* @__PURE__ */ new Map();+ for (const type of options) {+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);+ if (!discriminatorValues.length) {+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);+ }+ for (const value of discriminatorValues) {+ if (optionsMap.has(value)) {+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);+ }+ optionsMap.set(value, type);+ }+ }+ return new _ZodDiscriminatedUnion({+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,+ discriminator,+ options,+ optionsMap,+ ...processCreateParams(params)+ });+ }+};+function mergeValues2(a, b) {+ const aType = getParsedType2(a);+ const bType = getParsedType2(b);+ if (a === b) {+ return { valid: true, data: a };+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {+ const bKeys = util.objectKeys(b);+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);+ const newObj = { ...a, ...b };+ for (const key of sharedKeys) {+ const sharedValue = mergeValues2(a[key], b[key]);+ if (!sharedValue.valid) {+ return { valid: false };+ }+ newObj[key] = sharedValue.data;+ }+ return { valid: true, data: newObj };+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {+ if (a.length !== b.length) {+ return { valid: false };+ }+ const newArray = [];+ for (let index = 0; index < a.length; index++) {+ const itemA = a[index];+ const itemB = b[index];+ const sharedValue = mergeValues2(itemA, itemB);+ if (!sharedValue.valid) {+ return { valid: false };+ }+ newArray.push(sharedValue.data);+ }+ return { valid: true, data: newArray };+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {+ return { valid: true, data: a };+ } else {+ return { valid: false };+ }+}+var ZodIntersection2 = class extends ZodType2 {+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ const handleParsed = (parsedLeft, parsedRight) => {+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {+ return INVALID;+ }+ const merged = mergeValues2(parsedLeft.value, parsedRight.value);+ if (!merged.valid) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_intersection_types+ });+ return INVALID;+ }+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {+ status.dirty();+ }+ return { status: status.value, value: merged.data };+ };+ if (ctx.common.async) {+ return Promise.all([+ this._def.left._parseAsync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ }),+ this._def.right._parseAsync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ })+ ]).then(([left, right]) => handleParsed(left, right));+ } else {+ return handleParsed(this._def.left._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ }), this._def.right._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ }));+ }+ }+};+ZodIntersection2.create = (left, right, params) => {+ return new ZodIntersection2({+ left,+ right,+ typeName: ZodFirstPartyTypeKind.ZodIntersection,+ ...processCreateParams(params)+ });+};+var ZodTuple = class _ZodTuple extends ZodType2 {+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.array) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.array,+ received: ctx.parsedType+ });+ return INVALID;+ }+ if (ctx.data.length < this._def.items.length) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: this._def.items.length,+ inclusive: true,+ exact: false,+ type: "array"+ });+ return INVALID;+ }+ const rest = this._def.rest;+ if (!rest && ctx.data.length > this._def.items.length) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: this._def.items.length,+ inclusive: true,+ exact: false,+ type: "array"+ });+ status.dirty();+ }+ const items = [...ctx.data].map((item, itemIndex) => {+ const schema = this._def.items[itemIndex] || this._def.rest;+ if (!schema)+ return null;+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));+ }).filter((x) => !!x);+ if (ctx.common.async) {+ return Promise.all(items).then((results) => {+ return ParseStatus.mergeArray(status, results);+ });+ } else {+ return ParseStatus.mergeArray(status, items);+ }+ }+ get items() {+ return this._def.items;+ }+ rest(rest) {+ return new _ZodTuple({+ ...this._def,+ rest+ });+ }+};+ZodTuple.create = (schemas, params) => {+ if (!Array.isArray(schemas)) {+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");+ }+ return new ZodTuple({+ items: schemas,+ typeName: ZodFirstPartyTypeKind.ZodTuple,+ rest: null,+ ...processCreateParams(params)+ });+};+var ZodRecord2 = class _ZodRecord extends ZodType2 {+ get keySchema() {+ return this._def.keyType;+ }+ get valueSchema() {+ return this._def.valueType;+ }+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.object) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.object,+ received: ctx.parsedType+ });+ return INVALID;+ }+ const pairs = [];+ const keyType = this._def.keyType;+ const valueType = this._def.valueType;+ for (const key in ctx.data) {+ pairs.push({+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),+ alwaysSet: key in ctx.data+ });+ }+ if (ctx.common.async) {+ return ParseStatus.mergeObjectAsync(status, pairs);+ } else {+ return ParseStatus.mergeObjectSync(status, pairs);+ }+ }+ get element() {+ return this._def.valueType;+ }+ static create(first, second, third) {+ if (second instanceof ZodType2) {+ return new _ZodRecord({+ keyType: first,+ valueType: second,+ typeName: ZodFirstPartyTypeKind.ZodRecord,+ ...processCreateParams(third)+ });+ }+ return new _ZodRecord({+ keyType: ZodString2.create(),+ valueType: first,+ typeName: ZodFirstPartyTypeKind.ZodRecord,+ ...processCreateParams(second)+ });+ }+};+var ZodMap = class extends ZodType2 {+ get keySchema() {+ return this._def.keyType;+ }+ get valueSchema() {+ return this._def.valueType;+ }+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.map) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.map,+ received: ctx.parsedType+ });+ return INVALID;+ }+ const keyType = this._def.keyType;+ const valueType = this._def.valueType;+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {+ return {+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))+ };+ });+ if (ctx.common.async) {+ const finalMap = /* @__PURE__ */ new Map();+ return Promise.resolve().then(async () => {+ for (const pair of pairs) {+ const key = await pair.key;+ const value = await pair.value;+ if (key.status === "aborted" || value.status === "aborted") {+ return INVALID;+ }+ if (key.status === "dirty" || value.status === "dirty") {+ status.dirty();+ }+ finalMap.set(key.value, value.value);+ }+ return { status: status.value, value: finalMap };+ });+ } else {+ const finalMap = /* @__PURE__ */ new Map();+ for (const pair of pairs) {+ const key = pair.key;+ const value = pair.value;+ if (key.status === "aborted" || value.status === "aborted") {+ return INVALID;+ }+ if (key.status === "dirty" || value.status === "dirty") {+ status.dirty();+ }+ finalMap.set(key.value, value.value);+ }+ return { status: status.value, value: finalMap };+ }+ }+};+ZodMap.create = (keyType, valueType, params) => {+ return new ZodMap({+ valueType,+ keyType,+ typeName: ZodFirstPartyTypeKind.ZodMap,+ ...processCreateParams(params)+ });+};+var ZodSet = class _ZodSet extends ZodType2 {+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.set) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.set,+ received: ctx.parsedType+ });+ return INVALID;+ }+ const def = this._def;+ if (def.minSize !== null) {+ if (ctx.data.size < def.minSize.value) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_small,+ minimum: def.minSize.value,+ type: "set",+ inclusive: true,+ exact: false,+ message: def.minSize.message+ });+ status.dirty();+ }+ }+ if (def.maxSize !== null) {+ if (ctx.data.size > def.maxSize.value) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.too_big,+ maximum: def.maxSize.value,+ type: "set",+ inclusive: true,+ exact: false,+ message: def.maxSize.message+ });+ status.dirty();+ }+ }+ const valueType = this._def.valueType;+ function finalizeSet(elements2) {+ const parsedSet = /* @__PURE__ */ new Set();+ for (const element of elements2) {+ if (element.status === "aborted")+ return INVALID;+ if (element.status === "dirty")+ status.dirty();+ parsedSet.add(element.value);+ }+ return { status: status.value, value: parsedSet };+ }+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));+ if (ctx.common.async) {+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));+ } else {+ return finalizeSet(elements);+ }+ }+ min(minSize, message) {+ return new _ZodSet({+ ...this._def,+ minSize: { value: minSize, message: errorUtil.toString(message) }+ });+ }+ max(maxSize, message) {+ return new _ZodSet({+ ...this._def,+ maxSize: { value: maxSize, message: errorUtil.toString(message) }+ });+ }+ size(size, message) {+ return this.min(size, message).max(size, message);+ }+ nonempty(message) {+ return this.min(1, message);+ }+};+ZodSet.create = (valueType, params) => {+ return new ZodSet({+ valueType,+ minSize: null,+ maxSize: null,+ typeName: ZodFirstPartyTypeKind.ZodSet,+ ...processCreateParams(params)+ });+};+var ZodFunction = class _ZodFunction extends ZodType2 {+ constructor() {+ super(...arguments);+ this.validate = this.implement;+ }+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.function) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.function,+ received: ctx.parsedType+ });+ return INVALID;+ }+ function makeArgsIssue(args, error2) {+ return makeIssue({+ data: args,+ path: ctx.path,+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default2].filter((x) => !!x),+ issueData: {+ code: ZodIssueCode.invalid_arguments,+ argumentsError: error2+ }+ });+ }+ function makeReturnsIssue(returns, error2) {+ return makeIssue({+ data: returns,+ path: ctx.path,+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default2].filter((x) => !!x),+ issueData: {+ code: ZodIssueCode.invalid_return_type,+ returnTypeError: error2+ }+ });+ }+ const params = { errorMap: ctx.common.contextualErrorMap };+ const fn = ctx.data;+ if (this._def.returns instanceof ZodPromise) {+ const me = this;+ return OK(async function(...args) {+ const error2 = new ZodError2([]);+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {+ error2.addIssue(makeArgsIssue(args, e));+ throw error2;+ });+ const result = await Reflect.apply(fn, this, parsedArgs);+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {+ error2.addIssue(makeReturnsIssue(result, e));+ throw error2;+ });+ return parsedReturns;+ });+ } else {+ const me = this;+ return OK(function(...args) {+ const parsedArgs = me._def.args.safeParse(args, params);+ if (!parsedArgs.success) {+ throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]);+ }+ const result = Reflect.apply(fn, this, parsedArgs.data);+ const parsedReturns = me._def.returns.safeParse(result, params);+ if (!parsedReturns.success) {+ throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]);+ }+ return parsedReturns.data;+ });+ }+ }+ parameters() {+ return this._def.args;+ }+ returnType() {+ return this._def.returns;+ }+ args(...items) {+ return new _ZodFunction({+ ...this._def,+ args: ZodTuple.create(items).rest(ZodUnknown2.create())+ });+ }+ returns(returnType) {+ return new _ZodFunction({+ ...this._def,+ returns: returnType+ });+ }+ implement(func) {+ const validatedFunc = this.parse(func);+ return validatedFunc;+ }+ strictImplement(func) {+ const validatedFunc = this.parse(func);+ return validatedFunc;+ }+ static create(args, returns, params) {+ return new _ZodFunction({+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown2.create()),+ returns: returns || ZodUnknown2.create(),+ typeName: ZodFirstPartyTypeKind.ZodFunction,+ ...processCreateParams(params)+ });+ }+};+var ZodLazy = class extends ZodType2 {+ get schema() {+ return this._def.getter();+ }+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ const lazySchema = this._def.getter();+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });+ }+};+ZodLazy.create = (getter, params) => {+ return new ZodLazy({+ getter,+ typeName: ZodFirstPartyTypeKind.ZodLazy,+ ...processCreateParams(params)+ });+};+var ZodLiteral2 = class extends ZodType2 {+ _parse(input) {+ if (input.data !== this._def.value) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ received: ctx.data,+ code: ZodIssueCode.invalid_literal,+ expected: this._def.value+ });+ return INVALID;+ }+ return { status: "valid", value: input.data };+ }+ get value() {+ return this._def.value;+ }+};+ZodLiteral2.create = (value, params) => {+ return new ZodLiteral2({+ value,+ typeName: ZodFirstPartyTypeKind.ZodLiteral,+ ...processCreateParams(params)+ });+};+function createZodEnum(values, params) {+ return new ZodEnum2({+ values,+ typeName: ZodFirstPartyTypeKind.ZodEnum,+ ...processCreateParams(params)+ });+}+var ZodEnum2 = class _ZodEnum extends ZodType2 {+ _parse(input) {+ if (typeof input.data !== "string") {+ const ctx = this._getOrReturnCtx(input);+ const expectedValues = this._def.values;+ addIssueToContext(ctx, {+ expected: util.joinValues(expectedValues),+ received: ctx.parsedType,+ code: ZodIssueCode.invalid_type+ });+ return INVALID;+ }+ if (!this._cache) {+ this._cache = new Set(this._def.values);+ }+ if (!this._cache.has(input.data)) {+ const ctx = this._getOrReturnCtx(input);+ const expectedValues = this._def.values;+ addIssueToContext(ctx, {+ received: ctx.data,+ code: ZodIssueCode.invalid_enum_value,+ options: expectedValues+ });+ return INVALID;+ }+ return OK(input.data);+ }+ get options() {+ return this._def.values;+ }+ get enum() {+ const enumValues = {};+ for (const val of this._def.values) {+ enumValues[val] = val;+ }+ return enumValues;+ }+ get Values() {+ const enumValues = {};+ for (const val of this._def.values) {+ enumValues[val] = val;+ }+ return enumValues;+ }+ get Enum() {+ const enumValues = {};+ for (const val of this._def.values) {+ enumValues[val] = val;+ }+ return enumValues;+ }+ extract(values, newDef = this._def) {+ return _ZodEnum.create(values, {+ ...this._def,+ ...newDef+ });+ }+ exclude(values, newDef = this._def) {+ return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {+ ...this._def,+ ...newDef+ });+ }+};+ZodEnum2.create = createZodEnum;+var ZodNativeEnum = class extends ZodType2 {+ _parse(input) {+ const nativeEnumValues = util.getValidEnumValues(this._def.values);+ const ctx = this._getOrReturnCtx(input);+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {+ const expectedValues = util.objectValues(nativeEnumValues);+ addIssueToContext(ctx, {+ expected: util.joinValues(expectedValues),+ received: ctx.parsedType,+ code: ZodIssueCode.invalid_type+ });+ return INVALID;+ }+ if (!this._cache) {+ this._cache = new Set(util.getValidEnumValues(this._def.values));+ }+ if (!this._cache.has(input.data)) {+ const expectedValues = util.objectValues(nativeEnumValues);+ addIssueToContext(ctx, {+ received: ctx.data,+ code: ZodIssueCode.invalid_enum_value,+ options: expectedValues+ });+ return INVALID;+ }+ return OK(input.data);+ }+ get enum() {+ return this._def.values;+ }+};+ZodNativeEnum.create = (values, params) => {+ return new ZodNativeEnum({+ values,+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,+ ...processCreateParams(params)+ });+};+var ZodPromise = class extends ZodType2 {+ unwrap() {+ return this._def.type;+ }+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.promise,+ received: ctx.parsedType+ });+ return INVALID;+ }+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);+ return OK(promisified.then((data) => {+ return this._def.type.parseAsync(data, {+ path: ctx.path,+ errorMap: ctx.common.contextualErrorMap+ });+ }));+ }+};+ZodPromise.create = (schema, params) => {+ return new ZodPromise({+ type: schema,+ typeName: ZodFirstPartyTypeKind.ZodPromise,+ ...processCreateParams(params)+ });+};+var ZodEffects = class extends ZodType2 {+ innerType() {+ return this._def.schema;+ }+ sourceType() {+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;+ }+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ const effect = this._def.effect || null;+ const checkCtx = {+ addIssue: (arg) => {+ addIssueToContext(ctx, arg);+ if (arg.fatal) {+ status.abort();+ } else {+ status.dirty();+ }+ },+ get path() {+ return ctx.path;+ }+ };+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);+ if (effect.type === "preprocess") {+ const processed = effect.transform(ctx.data, checkCtx);+ if (ctx.common.async) {+ return Promise.resolve(processed).then(async (processed2) => {+ if (status.value === "aborted")+ return INVALID;+ const result = await this._def.schema._parseAsync({+ data: processed2,+ path: ctx.path,+ parent: ctx+ });+ if (result.status === "aborted")+ return INVALID;+ if (result.status === "dirty")+ return DIRTY(result.value);+ if (status.value === "dirty")+ return DIRTY(result.value);+ return result;+ });+ } else {+ if (status.value === "aborted")+ return INVALID;+ const result = this._def.schema._parseSync({+ data: processed,+ path: ctx.path,+ parent: ctx+ });+ if (result.status === "aborted")+ return INVALID;+ if (result.status === "dirty")+ return DIRTY(result.value);+ if (status.value === "dirty")+ return DIRTY(result.value);+ return result;+ }+ }+ if (effect.type === "refinement") {+ const executeRefinement = (acc) => {+ const result = effect.refinement(acc, checkCtx);+ if (ctx.common.async) {+ return Promise.resolve(result);+ }+ if (result instanceof Promise) {+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");+ }+ return acc;+ };+ if (ctx.common.async === false) {+ const inner = this._def.schema._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ if (inner.status === "aborted")+ return INVALID;+ if (inner.status === "dirty")+ status.dirty();+ executeRefinement(inner.value);+ return { status: status.value, value: inner.value };+ } else {+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {+ if (inner.status === "aborted")+ return INVALID;+ if (inner.status === "dirty")+ status.dirty();+ return executeRefinement(inner.value).then(() => {+ return { status: status.value, value: inner.value };+ });+ });+ }+ }+ if (effect.type === "transform") {+ if (ctx.common.async === false) {+ const base = this._def.schema._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ if (!isValid(base))+ return INVALID;+ const result = effect.transform(base.value, checkCtx);+ if (result instanceof Promise) {+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);+ }+ return { status: status.value, value: result };+ } else {+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {+ if (!isValid(base))+ return INVALID;+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({+ status: status.value,+ value: result+ }));+ });+ }+ }+ util.assertNever(effect);+ }+};+ZodEffects.create = (schema, effect, params) => {+ return new ZodEffects({+ schema,+ typeName: ZodFirstPartyTypeKind.ZodEffects,+ effect,+ ...processCreateParams(params)+ });+};+ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {+ return new ZodEffects({+ schema,+ effect: { type: "preprocess", transform: preprocess2 },+ typeName: ZodFirstPartyTypeKind.ZodEffects,+ ...processCreateParams(params)+ });+};+var ZodOptional2 = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 === ZodParsedType.undefined) {+ return OK(void 0);+ }+ return this._def.innerType._parse(input);+ }+ unwrap() {+ return this._def.innerType;+ }+};+ZodOptional2.create = (type, params) => {+ return new ZodOptional2({+ innerType: type,+ typeName: ZodFirstPartyTypeKind.ZodOptional,+ ...processCreateParams(params)+ });+};+var ZodNullable2 = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 === ZodParsedType.null) {+ return OK(null);+ }+ return this._def.innerType._parse(input);+ }+ unwrap() {+ return this._def.innerType;+ }+};+ZodNullable2.create = (type, params) => {+ return new ZodNullable2({+ innerType: type,+ typeName: ZodFirstPartyTypeKind.ZodNullable,+ ...processCreateParams(params)+ });+};+var ZodDefault2 = class extends ZodType2 {+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ let data = ctx.data;+ if (ctx.parsedType === ZodParsedType.undefined) {+ data = this._def.defaultValue();+ }+ return this._def.innerType._parse({+ data,+ path: ctx.path,+ parent: ctx+ });+ }+ removeDefault() {+ return this._def.innerType;+ }+};+ZodDefault2.create = (type, params) => {+ return new ZodDefault2({+ innerType: type,+ typeName: ZodFirstPartyTypeKind.ZodDefault,+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,+ ...processCreateParams(params)+ });+};+var ZodCatch2 = class extends ZodType2 {+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ const newCtx = {+ ...ctx,+ common: {+ ...ctx.common,+ issues: []+ }+ };+ const result = this._def.innerType._parse({+ data: newCtx.data,+ path: newCtx.path,+ parent: {+ ...newCtx+ }+ });+ if (isAsync(result)) {+ return result.then((result2) => {+ return {+ status: "valid",+ value: result2.status === "valid" ? result2.value : this._def.catchValue({+ get error() {+ return new ZodError2(newCtx.common.issues);+ },+ input: newCtx.data+ })+ };+ });+ } else {+ return {+ status: "valid",+ value: result.status === "valid" ? result.value : this._def.catchValue({+ get error() {+ return new ZodError2(newCtx.common.issues);+ },+ input: newCtx.data+ })+ };+ }+ }+ removeCatch() {+ return this._def.innerType;+ }+};+ZodCatch2.create = (type, params) => {+ return new ZodCatch2({+ innerType: type,+ typeName: ZodFirstPartyTypeKind.ZodCatch,+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,+ ...processCreateParams(params)+ });+};+var ZodNaN = class extends ZodType2 {+ _parse(input) {+ const parsedType2 = this._getType(input);+ if (parsedType2 !== ZodParsedType.nan) {+ const ctx = this._getOrReturnCtx(input);+ addIssueToContext(ctx, {+ code: ZodIssueCode.invalid_type,+ expected: ZodParsedType.nan,+ received: ctx.parsedType+ });+ return INVALID;+ }+ return { status: "valid", value: input.data };+ }+};+ZodNaN.create = (params) => {+ return new ZodNaN({+ typeName: ZodFirstPartyTypeKind.ZodNaN,+ ...processCreateParams(params)+ });+};+var BRAND = Symbol("zod_brand");+var ZodBranded = class extends ZodType2 {+ _parse(input) {+ const { ctx } = this._processInputParams(input);+ const data = ctx.data;+ return this._def.type._parse({+ data,+ path: ctx.path,+ parent: ctx+ });+ }+ unwrap() {+ return this._def.type;+ }+};+var ZodPipeline = class _ZodPipeline extends ZodType2 {+ _parse(input) {+ const { status, ctx } = this._processInputParams(input);+ if (ctx.common.async) {+ const handleAsync = async () => {+ const inResult = await this._def.in._parseAsync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ if (inResult.status === "aborted")+ return INVALID;+ if (inResult.status === "dirty") {+ status.dirty();+ return DIRTY(inResult.value);+ } else {+ return this._def.out._parseAsync({+ data: inResult.value,+ path: ctx.path,+ parent: ctx+ });+ }+ };+ return handleAsync();+ } else {+ const inResult = this._def.in._parseSync({+ data: ctx.data,+ path: ctx.path,+ parent: ctx+ });+ if (inResult.status === "aborted")+ return INVALID;+ if (inResult.status === "dirty") {+ status.dirty();+ return {+ status: "dirty",+ value: inResult.value+ };+ } else {+ return this._def.out._parseSync({+ data: inResult.value,+ path: ctx.path,+ parent: ctx+ });+ }+ }+ }+ static create(a, b) {+ return new _ZodPipeline({+ in: a,+ out: b,+ typeName: ZodFirstPartyTypeKind.ZodPipeline+ });+ }+};+var ZodReadonly2 = class extends ZodType2 {+ _parse(input) {+ const result = this._def.innerType._parse(input);+ const freeze = (data) => {+ if (isValid(data)) {+ data.value = Object.freeze(data.value);+ }+ return data;+ };+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);+ }+ unwrap() {+ return this._def.innerType;+ }+};+ZodReadonly2.create = (type, params) => {+ return new ZodReadonly2({+ innerType: type,+ typeName: ZodFirstPartyTypeKind.ZodReadonly,+ ...processCreateParams(params)+ });+};+function cleanParams(params, data) {+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;+ const p2 = typeof p === "string" ? { message: p } : p;+ return p2;+}+function custom2(check2, _params = {}, fatal) {+ if (check2)+ return ZodAny.create().superRefine((data, ctx) => {+ const r = check2(data);+ if (r instanceof Promise) {+ return r.then((r2) => {+ if (!r2) {+ const params = cleanParams(_params, data);+ const _fatal = params.fatal ?? fatal ?? true;+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });+ }+ });+ }+ if (!r) {+ const params = cleanParams(_params, data);+ const _fatal = params.fatal ?? fatal ?? true;+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });+ }+ return;+ });+ return ZodAny.create();+}+var late = {+ object: ZodObject2.lazycreate+};+var ZodFirstPartyTypeKind;+(function(ZodFirstPartyTypeKind2) {+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";+})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));+var instanceOfType = (cls, params = {+ message: `Input not instance of ${cls.name}`+}) => custom2((data) => data instanceof cls, params);+var stringType = ZodString2.create;+var numberType = ZodNumber2.create;+var nanType = ZodNaN.create;+var bigIntType = ZodBigInt.create;+var booleanType = ZodBoolean2.create;+var dateType = ZodDate.create;+var symbolType = ZodSymbol.create;+var undefinedType = ZodUndefined.create;+var nullType = ZodNull2.create;+var anyType = ZodAny.create;+var unknownType = ZodUnknown2.create;+var neverType = ZodNever2.create;+var voidType = ZodVoid.create;+var arrayType = ZodArray2.create;+var objectType = ZodObject2.create;+var strictObjectType = ZodObject2.strictCreate;+var unionType = ZodUnion2.create;+var discriminatedUnionType = ZodDiscriminatedUnion2.create;+var intersectionType = ZodIntersection2.create;+var tupleType = ZodTuple.create;+var recordType = ZodRecord2.create;+var mapType = ZodMap.create;+var setType = ZodSet.create;+var functionType = ZodFunction.create;+var lazyType = ZodLazy.create;+var literalType = ZodLiteral2.create;+var enumType = ZodEnum2.create;+var nativeEnumType = ZodNativeEnum.create;+var promiseType = ZodPromise.create;+var effectsType = ZodEffects.create;+var optionalType = ZodOptional2.create;+var nullableType = ZodNullable2.create;+var preprocessType = ZodEffects.createWithPreprocess;+var pipelineType = ZodPipeline.create;+var ostring = () => stringType().optional();+var onumber = () => numberType().optional();+var oboolean = () => booleanType().optional();+var coerce = {+ string: (arg) => ZodString2.create({ ...arg, coerce: true }),+ number: (arg) => ZodNumber2.create({ ...arg, coerce: true }),+ boolean: (arg) => ZodBoolean2.create({+ ...arg,+ coerce: true+ }),+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),+ date: (arg) => ZodDate.create({ ...arg, coerce: true })+};+var NEVER2 = INVALID;++// node_modules/zod/v4/mini/schemas.js+var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {+ if (!inst._zod)+ throw new Error("Uninitialized schema in ZodMiniType.");+ $ZodType.init(inst, def);+ inst.def = def;+ inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });+ inst.safeParse = (data, params) => safeParse(inst, data, params);+ inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });+ inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);+ inst.check = (...checks) => {+ return inst.clone(+ {+ ...def,+ checks: [+ ...def.checks ?? [],+ ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)+ ]+ }+ // { parent: true }+ );+ };+ inst.clone = (_def, params) => clone(inst, _def, params);+ inst.brand = () => inst;+ inst.register = (reg, meta) => {+ reg.add(inst, meta);+ return inst;+ };+});+var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {+ $ZodObject.init(inst, def);+ ZodMiniType.init(inst, def);+ util_exports.defineLazy(inst, "shape", () => def.shape);+});+function object2(shape, params) {+ const def = {+ type: "object",+ get shape() {+ util_exports.assignProp(this, "shape", { ...shape });+ return this.shape;+ },+ ...util_exports.normalizeParams(params)+ };+ return new ZodMiniObject(def);+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js+function isZ4Schema(s) {+ const schema = s;+ return !!schema._zod;+}+function objectFromShape(shape) {+ const values = Object.values(shape);+ if (values.length === 0)+ return object2({});+ const allV4 = values.every(isZ4Schema);+ const allV3 = values.every((s) => !isZ4Schema(s));+ if (allV4)+ return object2(shape);+ if (allV3)+ return objectType(shape);+ throw new Error("Mixed Zod versions detected in object shape.");+}+function safeParse3(schema, data) {+ if (isZ4Schema(schema)) {+ const result2 = safeParse(schema, data);+ return result2;+ }+ const v3Schema = schema;+ const result = v3Schema.safeParse(data);+ return result;+}+async function safeParseAsync3(schema, data) {+ if (isZ4Schema(schema)) {+ const result2 = await safeParseAsync(schema, data);+ return result2;+ }+ const v3Schema = schema;+ const result = await v3Schema.safeParseAsync(data);+ return result;+}+function getObjectShape(schema) {+ if (!schema)+ return void 0;+ let rawShape;+ if (isZ4Schema(schema)) {+ const v4Schema = schema;+ rawShape = v4Schema._zod?.def?.shape;+ } else {+ const v3Schema = schema;+ rawShape = v3Schema.shape;+ }+ if (!rawShape)+ return void 0;+ if (typeof rawShape === "function") {+ try {+ return rawShape();+ } catch {+ return void 0;+ }+ }+ return rawShape;+}+function normalizeObjectSchema(schema) {+ if (!schema)+ return void 0;+ if (typeof schema === "object") {+ const asV3 = schema;+ const asV4 = schema;+ if (!asV3._def && !asV4._zod) {+ const values = Object.values(schema);+ if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) {+ return objectFromShape(schema);+ }+ }+ }+ if (isZ4Schema(schema)) {+ const v4Schema = schema;+ const def = v4Schema._zod?.def;+ if (def && (def.type === "object" || def.shape !== void 0)) {+ return schema;+ }+ } else {+ const v3Schema = schema;+ if (v3Schema.shape !== void 0) {+ return schema;+ }+ }+ return void 0;+}+function getParseErrorMessage(error2) {+ if (error2 && typeof error2 === "object") {+ if ("message" in error2 && typeof error2.message === "string") {+ return error2.message;+ }+ if ("issues" in error2 && Array.isArray(error2.issues) && error2.issues.length > 0) {+ const firstIssue = error2.issues[0];+ if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {+ return String(firstIssue.message);+ }+ }+ try {+ return JSON.stringify(error2);+ } catch {+ return String(error2);+ }+ }+ return String(error2);+}+function getSchemaDescription(schema) {+ return schema.description;+}+function isSchemaOptional(schema) {+ if (isZ4Schema(schema)) {+ const v4Schema = schema;+ return v4Schema._zod?.def?.type === "optional";+ }+ const v3Schema = schema;+ if (typeof schema.isOptional === "function") {+ return schema.isOptional();+ }+ return v3Schema._def?.typeName === "ZodOptional";+}+function getLiteralValue(schema) {+ if (isZ4Schema(schema)) {+ const v4Schema = schema;+ const def2 = v4Schema._zod?.def;+ if (def2) {+ if (def2.value !== void 0)+ return def2.value;+ if (Array.isArray(def2.values) && def2.values.length > 0) {+ return def2.values[0];+ }+ }+ }+ const v3Schema = schema;+ const def = v3Schema._def;+ if (def) {+ if (def.value !== void 0)+ return def.value;+ if (Array.isArray(def.values) && def.values.length > 0) {+ return def.values[0];+ }+ }+ const directValue = schema.value;+ if (directValue !== void 0)+ return directValue;+ return void 0;+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js+function isTerminal(status) {+ return status === "completed" || status === "failed" || status === "cancelled";+}++// node_modules/zod-to-json-schema/dist/esm/Options.js+var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");+var defaultOptions = {+ name: void 0,+ $refStrategy: "root",+ basePath: ["#"],+ effectStrategy: "input",+ pipeStrategy: "all",+ dateStrategy: "format:date-time",+ mapStrategy: "entries",+ removeAdditionalStrategy: "passthrough",+ allowedAdditionalProperties: true,+ rejectedAdditionalProperties: false,+ definitionPath: "definitions",+ target: "jsonSchema7",+ strictUnions: false,+ definitions: {},+ errorMessages: false,+ markdownDescription: false,+ patternStrategy: "escape",+ applyRegexFlags: false,+ emailStrategy: "format:email",+ base64Strategy: "contentEncoding:base64",+ nameStrategy: "ref",+ openAiAnyTypeName: "OpenAiAnyType"+};+var getDefaultOptions = (options) => typeof options === "string" ? {+ ...defaultOptions,+ name: options+} : {+ ...defaultOptions,+ ...options+};++// node_modules/zod-to-json-schema/dist/esm/Refs.js+var getRefs = (options) => {+ const _options = getDefaultOptions(options);+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;+ return {+ ..._options,+ flags: { hasReferencedOpenAiAnyType: false },+ currentPath,+ propertyPath: void 0,+ seen: new Map(Object.entries(_options.definitions).map(([name3, def]) => [+ def._def,+ {+ def: def._def,+ path: [..._options.basePath, _options.definitionPath, name3],+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.+ jsonSchema: void 0+ }+ ]))+ };+};++// node_modules/zod-to-json-schema/dist/esm/errorMessages.js+function addErrorMessage(res, key, errorMessage, refs) {+ if (!refs?.errorMessages)+ return;+ if (errorMessage) {+ res.errorMessage = {+ ...res.errorMessage,+ [key]: errorMessage+ };+ }+}+function setResponseValueAndErrors(res, key, value, errorMessage, refs) {+ res[key] = value;+ addErrorMessage(res, key, errorMessage, refs);+}++// node_modules/zod-to-json-schema/dist/esm/getRelativePath.js+var getRelativePath = (pathA, pathB) => {+ let i = 0;+ for (; i < pathA.length && i < pathB.length; i++) {+ if (pathA[i] !== pathB[i])+ break;+ }+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");+};++// node_modules/zod-to-json-schema/dist/esm/parsers/any.js+function parseAnyDef(refs) {+ if (refs.target !== "openAi") {+ return {};+ }+ const anyDefinitionPath = [+ ...refs.basePath,+ refs.definitionPath,+ refs.openAiAnyTypeName+ ];+ refs.flags.hasReferencedOpenAiAnyType = true;+ return {+ $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/array.js+function parseArrayDef(def, refs) {+ const res = {+ type: "array"+ };+ if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {+ res.items = parseDef(def.type._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items"]+ });+ }+ if (def.minLength) {+ setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);+ }+ if (def.maxLength) {+ setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);+ }+ if (def.exactLength) {+ setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);+ setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);+ }+ return res;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js+function parseBigintDef(def, refs) {+ const res = {+ type: "integer",+ format: "int64"+ };+ if (!def.checks)+ return res;+ for (const check2 of def.checks) {+ switch (check2.kind) {+ case "min":+ if (refs.target === "jsonSchema7") {+ if (check2.inclusive) {+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);+ } else {+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);+ }+ } else {+ if (!check2.inclusive) {+ res.exclusiveMinimum = true;+ }+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);+ }+ break;+ case "max":+ if (refs.target === "jsonSchema7") {+ if (check2.inclusive) {+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);+ } else {+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);+ }+ } else {+ if (!check2.inclusive) {+ res.exclusiveMaximum = true;+ }+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);+ }+ break;+ case "multipleOf":+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);+ break;+ }+ }+ return res;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js+function parseBooleanDef() {+ return {+ type: "boolean"+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js+function parseBrandedDef(_def, refs) {+ return parseDef(_def.type._def, refs);+}++// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js+var parseCatchDef = (def, refs) => {+ return parseDef(def.innerType._def, refs);+};++// node_modules/zod-to-json-schema/dist/esm/parsers/date.js+function parseDateDef(def, refs, overrideDateStrategy) {+ const strategy = overrideDateStrategy ?? refs.dateStrategy;+ if (Array.isArray(strategy)) {+ return {+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))+ };+ }+ switch (strategy) {+ case "string":+ case "format:date-time":+ return {+ type: "string",+ format: "date-time"+ };+ case "format:date":+ return {+ type: "string",+ format: "date"+ };+ case "integer":+ return integerDateParser(def, refs);+ }+}+var integerDateParser = (def, refs) => {+ const res = {+ type: "integer",+ format: "unix-time"+ };+ if (refs.target === "openApi3") {+ return res;+ }+ for (const check2 of def.checks) {+ switch (check2.kind) {+ case "min":+ setResponseValueAndErrors(+ res,+ "minimum",+ check2.value,+ // This is in milliseconds+ check2.message,+ refs+ );+ break;+ case "max":+ setResponseValueAndErrors(+ res,+ "maximum",+ check2.value,+ // This is in milliseconds+ check2.message,+ refs+ );+ break;+ }+ }+ return res;+};++// node_modules/zod-to-json-schema/dist/esm/parsers/default.js+function parseDefaultDef(_def, refs) {+ return {+ ...parseDef(_def.innerType._def, refs),+ default: _def.defaultValue()+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js+function parseEffectsDef(_def, refs) {+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);+}++// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js+function parseEnumDef(def) {+ return {+ type: "string",+ enum: Array.from(def.values)+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js+var isJsonSchema7AllOfType = (type) => {+ if ("type" in type && type.type === "string")+ return false;+ return "allOf" in type;+};+function parseIntersectionDef(def, refs) {+ const allOf = [+ parseDef(def.left._def, {+ ...refs,+ currentPath: [...refs.currentPath, "allOf", "0"]+ }),+ parseDef(def.right._def, {+ ...refs,+ currentPath: [...refs.currentPath, "allOf", "1"]+ })+ ].filter((x) => !!x);+ let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;+ const mergedAllOf = [];+ allOf.forEach((schema) => {+ if (isJsonSchema7AllOfType(schema)) {+ mergedAllOf.push(...schema.allOf);+ if (schema.unevaluatedProperties === void 0) {+ unevaluatedProperties = void 0;+ }+ } else {+ let nestedSchema = schema;+ if ("additionalProperties" in schema && schema.additionalProperties === false) {+ const { additionalProperties, ...rest } = schema;+ nestedSchema = rest;+ } else {+ unevaluatedProperties = void 0;+ }+ mergedAllOf.push(nestedSchema);+ }+ });+ return mergedAllOf.length ? {+ allOf: mergedAllOf,+ ...unevaluatedProperties+ } : void 0;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js+function parseLiteralDef(def, refs) {+ const parsedType2 = typeof def.value;+ if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") {+ return {+ type: Array.isArray(def.value) ? "array" : "object"+ };+ }+ if (refs.target === "openApi3") {+ return {+ type: parsedType2 === "bigint" ? "integer" : parsedType2,+ enum: [def.value]+ };+ }+ return {+ type: parsedType2 === "bigint" ? "integer" : parsedType2,+ const: def.value+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/string.js+var emojiRegex2 = void 0;+var zodPatterns = {+ /**+ * `c` was changed to `[cC]` to replicate /i flag+ */+ cuid: /^[cC][^\s-]{8,}$/,+ cuid2: /^[0-9a-z]+$/,+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,+ /**+ * `a-z` was added to replicate /i flag+ */+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,+ /**+ * Constructed a valid Unicode RegExp+ *+ * Lazily instantiate since this type of regex isn't supported+ * in all envs (e.g. React Native).+ *+ * See:+ * https://github.com/colinhacks/zod/issues/2433+ * Fix in Zod:+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b+ */+ emoji: () => {+ if (emojiRegex2 === void 0) {+ emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");+ }+ return emojiRegex2;+ },+ /**+ * Unused+ */+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,+ /**+ * Unused+ */+ 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])$/,+ ipv4Cidr: /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,+ /**+ * Unused+ */+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,+ nanoid: /^[a-zA-Z0-9_-]{21}$/,+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/+};+function parseStringDef(def, refs) {+ const res = {+ type: "string"+ };+ if (def.checks) {+ for (const check2 of def.checks) {+ switch (check2.kind) {+ case "min":+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);+ break;+ case "max":+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);+ break;+ case "email":+ switch (refs.emailStrategy) {+ case "format:email":+ addFormat(res, "email", check2.message, refs);+ break;+ case "format:idn-email":+ addFormat(res, "idn-email", check2.message, refs);+ break;+ case "pattern:zod":+ addPattern(res, zodPatterns.email, check2.message, refs);+ break;+ }+ break;+ case "url":+ addFormat(res, "uri", check2.message, refs);+ break;+ case "uuid":+ addFormat(res, "uuid", check2.message, refs);+ break;+ case "regex":+ addPattern(res, check2.regex, check2.message, refs);+ break;+ case "cuid":+ addPattern(res, zodPatterns.cuid, check2.message, refs);+ break;+ case "cuid2":+ addPattern(res, zodPatterns.cuid2, check2.message, refs);+ break;+ case "startsWith":+ addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs);+ break;+ case "endsWith":+ addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs);+ break;+ case "datetime":+ addFormat(res, "date-time", check2.message, refs);+ break;+ case "date":+ addFormat(res, "date", check2.message, refs);+ break;+ case "time":+ addFormat(res, "time", check2.message, refs);+ break;+ case "duration":+ addFormat(res, "duration", check2.message, refs);+ break;+ case "length":+ setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs);+ setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs);+ break;+ case "includes": {+ addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs);+ break;+ }+ case "ip": {+ if (check2.version !== "v6") {+ addFormat(res, "ipv4", check2.message, refs);+ }+ if (check2.version !== "v4") {+ addFormat(res, "ipv6", check2.message, refs);+ }+ break;+ }+ case "base64url":+ addPattern(res, zodPatterns.base64url, check2.message, refs);+ break;+ case "jwt":+ addPattern(res, zodPatterns.jwt, check2.message, refs);+ break;+ case "cidr": {+ if (check2.version !== "v6") {+ addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs);+ }+ if (check2.version !== "v4") {+ addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs);+ }+ break;+ }+ case "emoji":+ addPattern(res, zodPatterns.emoji(), check2.message, refs);+ break;+ case "ulid": {+ addPattern(res, zodPatterns.ulid, check2.message, refs);+ break;+ }+ case "base64": {+ switch (refs.base64Strategy) {+ case "format:binary": {+ addFormat(res, "binary", check2.message, refs);+ break;+ }+ case "contentEncoding:base64": {+ setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs);+ break;+ }+ case "pattern:zod": {+ addPattern(res, zodPatterns.base64, check2.message, refs);+ break;+ }+ }+ break;+ }+ case "nanoid": {+ addPattern(res, zodPatterns.nanoid, check2.message, refs);+ }+ case "toLowerCase":+ case "toUpperCase":+ case "trim":+ break;+ default:+ /* @__PURE__ */ ((_) => {+ })(check2);+ }+ }+ }+ return res;+}+function escapeLiteralCheckValue(literal2, refs) {+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2;+}+var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");+function escapeNonAlphaNumeric(source) {+ let result = "";+ for (let i = 0; i < source.length; i++) {+ if (!ALPHA_NUMERIC.has(source[i])) {+ result += "\\";+ }+ result += source[i];+ }+ return result;+}+function addFormat(schema, value, message, refs) {+ if (schema.format || schema.anyOf?.some((x) => x.format)) {+ if (!schema.anyOf) {+ schema.anyOf = [];+ }+ if (schema.format) {+ schema.anyOf.push({+ format: schema.format,+ ...schema.errorMessage && refs.errorMessages && {+ errorMessage: { format: schema.errorMessage.format }+ }+ });+ delete schema.format;+ if (schema.errorMessage) {+ delete schema.errorMessage.format;+ if (Object.keys(schema.errorMessage).length === 0) {+ delete schema.errorMessage;+ }+ }+ }+ schema.anyOf.push({+ format: value,+ ...message && refs.errorMessages && { errorMessage: { format: message } }+ });+ } else {+ setResponseValueAndErrors(schema, "format", value, message, refs);+ }+}+function addPattern(schema, regex, message, refs) {+ if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {+ if (!schema.allOf) {+ schema.allOf = [];+ }+ if (schema.pattern) {+ schema.allOf.push({+ pattern: schema.pattern,+ ...schema.errorMessage && refs.errorMessages && {+ errorMessage: { pattern: schema.errorMessage.pattern }+ }+ });+ delete schema.pattern;+ if (schema.errorMessage) {+ delete schema.errorMessage.pattern;+ if (Object.keys(schema.errorMessage).length === 0) {+ delete schema.errorMessage;+ }+ }+ }+ schema.allOf.push({+ pattern: stringifyRegExpWithFlags(regex, refs),+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }+ });+ } else {+ setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);+ }+}+function stringifyRegExpWithFlags(regex, refs) {+ if (!refs.applyRegexFlags || !regex.flags) {+ return regex.source;+ }+ const flags = {+ i: regex.flags.includes("i"),+ m: regex.flags.includes("m"),+ s: regex.flags.includes("s")+ // `.` matches newlines+ };+ const source = flags.i ? regex.source.toLowerCase() : regex.source;+ let pattern = "";+ let isEscaped = false;+ let inCharGroup = false;+ let inCharRange = false;+ for (let i = 0; i < source.length; i++) {+ if (isEscaped) {+ pattern += source[i];+ isEscaped = false;+ continue;+ }+ if (flags.i) {+ if (inCharGroup) {+ if (source[i].match(/[a-z]/)) {+ if (inCharRange) {+ pattern += source[i];+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();+ inCharRange = false;+ } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {+ pattern += source[i];+ inCharRange = true;+ } else {+ pattern += `${source[i]}${source[i].toUpperCase()}`;+ }+ continue;+ }+ } else if (source[i].match(/[a-z]/)) {+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;+ continue;+ }+ }+ if (flags.m) {+ if (source[i] === "^") {+ pattern += `(^|(?<=[\r+]))`;+ continue;+ } else if (source[i] === "$") {+ pattern += `($|(?=[\r+]))`;+ continue;+ }+ }+ if (flags.s && source[i] === ".") {+ pattern += inCharGroup ? `${source[i]}\r+` : `[${source[i]}\r+]`;+ continue;+ }+ pattern += source[i];+ if (source[i] === "\\") {+ isEscaped = true;+ } else if (inCharGroup && source[i] === "]") {+ inCharGroup = false;+ } else if (!inCharGroup && source[i] === "[") {+ inCharGroup = true;+ }+ }+ try {+ new RegExp(pattern);+ } catch {+ console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);+ return regex.source;+ }+ return pattern;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/record.js+function parseRecordDef(def, refs) {+ if (refs.target === "openAi") {+ console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");+ }+ if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {+ return {+ type: "object",+ required: def.keyType._def.values,+ properties: def.keyType._def.values.reduce((acc, key) => ({+ ...acc,+ [key]: parseDef(def.valueType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "properties", key]+ }) ?? parseAnyDef(refs)+ }), {}),+ additionalProperties: refs.rejectedAdditionalProperties+ };+ }+ const schema = {+ type: "object",+ additionalProperties: parseDef(def.valueType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "additionalProperties"]+ }) ?? refs.allowedAdditionalProperties+ };+ if (refs.target === "openApi3") {+ return schema;+ }+ if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);+ return {+ ...schema,+ propertyNames: keyType+ };+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {+ return {+ ...schema,+ propertyNames: {+ enum: def.keyType._def.values+ }+ };+ } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {+ const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);+ return {+ ...schema,+ propertyNames: keyType+ };+ }+ return schema;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/map.js+function parseMapDef(def, refs) {+ if (refs.mapStrategy === "record") {+ return parseRecordDef(def, refs);+ }+ const keys = parseDef(def.keyType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items", "items", "0"]+ }) || parseAnyDef(refs);+ const values = parseDef(def.valueType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items", "items", "1"]+ }) || parseAnyDef(refs);+ return {+ type: "array",+ maxItems: 125,+ items: {+ type: "array",+ items: [keys, values],+ minItems: 2,+ maxItems: 2+ }+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js+function parseNativeEnumDef(def) {+ const object3 = def.values;+ const actualKeys = Object.keys(def.values).filter((key) => {+ return typeof object3[object3[key]] !== "number";+ });+ const actualValues = actualKeys.map((key) => object3[key]);+ const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));+ return {+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],+ enum: actualValues+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/never.js+function parseNeverDef(refs) {+ return refs.target === "openAi" ? void 0 : {+ not: parseAnyDef({+ ...refs,+ currentPath: [...refs.currentPath, "not"]+ })+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/null.js+function parseNullDef(refs) {+ return refs.target === "openApi3" ? {+ enum: ["null"],+ nullable: true+ } : {+ type: "null"+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/union.js+var primitiveMappings = {+ ZodString: "string",+ ZodNumber: "number",+ ZodBigInt: "integer",+ ZodBoolean: "boolean",+ ZodNull: "null"+};+function parseUnionDef(def, refs) {+ if (refs.target === "openApi3")+ return asAnyOf(def, refs);+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;+ if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {+ const types = options.reduce((types2, x) => {+ const type = primitiveMappings[x._def.typeName];+ return type && !types2.includes(type) ? [...types2, type] : types2;+ }, []);+ return {+ type: types.length > 1 ? types : types[0]+ };+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {+ const types = options.reduce((acc, x) => {+ const type = typeof x._def.value;+ switch (type) {+ case "string":+ case "number":+ case "boolean":+ return [...acc, type];+ case "bigint":+ return [...acc, "integer"];+ case "object":+ if (x._def.value === null)+ return [...acc, "null"];+ case "symbol":+ case "undefined":+ case "function":+ default:+ return acc;+ }+ }, []);+ if (types.length === options.length) {+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);+ return {+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],+ enum: options.reduce((acc, x) => {+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];+ }, [])+ };+ }+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {+ return {+ type: "string",+ enum: options.reduce((acc, x) => [+ ...acc,+ ...x._def.values.filter((x2) => !acc.includes(x2))+ ], [])+ };+ }+ return asAnyOf(def, refs);+}+var asAnyOf = (def, refs) => {+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {+ ...refs,+ currentPath: [...refs.currentPath, "anyOf", `${i}`]+ })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));+ return anyOf.length ? { anyOf } : void 0;+};++// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js+function parseNullableDef(def, refs) {+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {+ if (refs.target === "openApi3") {+ return {+ type: primitiveMappings[def.innerType._def.typeName],+ nullable: true+ };+ }+ return {+ type: [+ primitiveMappings[def.innerType._def.typeName],+ "null"+ ]+ };+ }+ if (refs.target === "openApi3") {+ const base2 = parseDef(def.innerType._def, {+ ...refs,+ currentPath: [...refs.currentPath]+ });+ if (base2 && "$ref" in base2)+ return { allOf: [base2], nullable: true };+ return base2 && { ...base2, nullable: true };+ }+ const base = parseDef(def.innerType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "anyOf", "0"]+ });+ return base && { anyOf: [base, { type: "null" }] };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/number.js+function parseNumberDef(def, refs) {+ const res = {+ type: "number"+ };+ if (!def.checks)+ return res;+ for (const check2 of def.checks) {+ switch (check2.kind) {+ case "int":+ res.type = "integer";+ addErrorMessage(res, "type", check2.message, refs);+ break;+ case "min":+ if (refs.target === "jsonSchema7") {+ if (check2.inclusive) {+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);+ } else {+ setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs);+ }+ } else {+ if (!check2.inclusive) {+ res.exclusiveMinimum = true;+ }+ setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs);+ }+ break;+ case "max":+ if (refs.target === "jsonSchema7") {+ if (check2.inclusive) {+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);+ } else {+ setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs);+ }+ } else {+ if (!check2.inclusive) {+ res.exclusiveMaximum = true;+ }+ setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs);+ }+ break;+ case "multipleOf":+ setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs);+ break;+ }+ }+ return res;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/object.js+function parseObjectDef(def, refs) {+ const forceOptionalIntoNullable = refs.target === "openAi";+ const result = {+ type: "object",+ properties: {}+ };+ const required2 = [];+ const shape = def.shape();+ for (const propName in shape) {+ let propDef = shape[propName];+ if (propDef === void 0 || propDef._def === void 0) {+ continue;+ }+ let propOptional = safeIsOptional(propDef);+ if (propOptional && forceOptionalIntoNullable) {+ if (propDef._def.typeName === "ZodOptional") {+ propDef = propDef._def.innerType;+ }+ if (!propDef.isNullable()) {+ propDef = propDef.nullable();+ }+ propOptional = false;+ }+ const parsedDef = parseDef(propDef._def, {+ ...refs,+ currentPath: [...refs.currentPath, "properties", propName],+ propertyPath: [...refs.currentPath, "properties", propName]+ });+ if (parsedDef === void 0) {+ continue;+ }+ result.properties[propName] = parsedDef;+ if (!propOptional) {+ required2.push(propName);+ }+ }+ if (required2.length) {+ result.required = required2;+ }+ const additionalProperties = decideAdditionalProperties(def, refs);+ if (additionalProperties !== void 0) {+ result.additionalProperties = additionalProperties;+ }+ return result;+}+function decideAdditionalProperties(def, refs) {+ if (def.catchall._def.typeName !== "ZodNever") {+ return parseDef(def.catchall._def, {+ ...refs,+ currentPath: [...refs.currentPath, "additionalProperties"]+ });+ }+ switch (def.unknownKeys) {+ case "passthrough":+ return refs.allowedAdditionalProperties;+ case "strict":+ return refs.rejectedAdditionalProperties;+ case "strip":+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;+ }+}+function safeIsOptional(schema) {+ try {+ return schema.isOptional();+ } catch {+ return true;+ }+}++// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js+var parseOptionalDef = (def, refs) => {+ if (refs.currentPath.toString() === refs.propertyPath?.toString()) {+ return parseDef(def.innerType._def, refs);+ }+ const innerSchema = parseDef(def.innerType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "anyOf", "1"]+ });+ return innerSchema ? {+ anyOf: [+ {+ not: parseAnyDef(refs)+ },+ innerSchema+ ]+ } : parseAnyDef(refs);+};++// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js+var parsePipelineDef = (def, refs) => {+ if (refs.pipeStrategy === "input") {+ return parseDef(def.in._def, refs);+ } else if (refs.pipeStrategy === "output") {+ return parseDef(def.out._def, refs);+ }+ const a = parseDef(def.in._def, {+ ...refs,+ currentPath: [...refs.currentPath, "allOf", "0"]+ });+ const b = parseDef(def.out._def, {+ ...refs,+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]+ });+ return {+ allOf: [a, b].filter((x) => x !== void 0)+ };+};++// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js+function parsePromiseDef(def, refs) {+ return parseDef(def.type._def, refs);+}++// node_modules/zod-to-json-schema/dist/esm/parsers/set.js+function parseSetDef(def, refs) {+ const items = parseDef(def.valueType._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items"]+ });+ const schema = {+ type: "array",+ uniqueItems: true,+ items+ };+ if (def.minSize) {+ setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);+ }+ if (def.maxSize) {+ setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);+ }+ return schema;+}++// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js+function parseTupleDef(def, refs) {+ if (def.rest) {+ return {+ type: "array",+ minItems: def.items.length,+ items: def.items.map((x, i) => parseDef(x._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items", `${i}`]+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),+ additionalItems: parseDef(def.rest._def, {+ ...refs,+ currentPath: [...refs.currentPath, "additionalItems"]+ })+ };+ } else {+ return {+ type: "array",+ minItems: def.items.length,+ maxItems: def.items.length,+ items: def.items.map((x, i) => parseDef(x._def, {+ ...refs,+ currentPath: [...refs.currentPath, "items", `${i}`]+ })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])+ };+ }+}++// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js+function parseUndefinedDef(refs) {+ return {+ not: parseAnyDef(refs)+ };+}++// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js+function parseUnknownDef(refs) {+ return parseAnyDef(refs);+}++// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js+var parseReadonlyDef = (def, refs) => {+ return parseDef(def.innerType._def, refs);+};++// node_modules/zod-to-json-schema/dist/esm/selectParser.js+var selectParser = (def, typeName, refs) => {+ switch (typeName) {+ case ZodFirstPartyTypeKind.ZodString:+ return parseStringDef(def, refs);+ case ZodFirstPartyTypeKind.ZodNumber:+ return parseNumberDef(def, refs);+ case ZodFirstPartyTypeKind.ZodObject:+ return parseObjectDef(def, refs);+ case ZodFirstPartyTypeKind.ZodBigInt:+ return parseBigintDef(def, refs);+ case ZodFirstPartyTypeKind.ZodBoolean:+ return parseBooleanDef();+ case ZodFirstPartyTypeKind.ZodDate:+ return parseDateDef(def, refs);+ case ZodFirstPartyTypeKind.ZodUndefined:+ return parseUndefinedDef(refs);+ case ZodFirstPartyTypeKind.ZodNull:+ return parseNullDef(refs);+ case ZodFirstPartyTypeKind.ZodArray:+ return parseArrayDef(def, refs);+ case ZodFirstPartyTypeKind.ZodUnion:+ case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:+ return parseUnionDef(def, refs);+ case ZodFirstPartyTypeKind.ZodIntersection:+ return parseIntersectionDef(def, refs);+ case ZodFirstPartyTypeKind.ZodTuple:+ return parseTupleDef(def, refs);+ case ZodFirstPartyTypeKind.ZodRecord:+ return parseRecordDef(def, refs);+ case ZodFirstPartyTypeKind.ZodLiteral:+ return parseLiteralDef(def, refs);+ case ZodFirstPartyTypeKind.ZodEnum:+ return parseEnumDef(def);+ case ZodFirstPartyTypeKind.ZodNativeEnum:+ return parseNativeEnumDef(def);+ case ZodFirstPartyTypeKind.ZodNullable:+ return parseNullableDef(def, refs);+ case ZodFirstPartyTypeKind.ZodOptional:+ return parseOptionalDef(def, refs);+ case ZodFirstPartyTypeKind.ZodMap:+ return parseMapDef(def, refs);+ case ZodFirstPartyTypeKind.ZodSet:+ return parseSetDef(def, refs);+ case ZodFirstPartyTypeKind.ZodLazy:+ return () => def.getter()._def;+ case ZodFirstPartyTypeKind.ZodPromise:+ return parsePromiseDef(def, refs);+ case ZodFirstPartyTypeKind.ZodNaN:+ case ZodFirstPartyTypeKind.ZodNever:+ return parseNeverDef(refs);+ case ZodFirstPartyTypeKind.ZodEffects:+ return parseEffectsDef(def, refs);+ case ZodFirstPartyTypeKind.ZodAny:+ return parseAnyDef(refs);+ case ZodFirstPartyTypeKind.ZodUnknown:+ return parseUnknownDef(refs);+ case ZodFirstPartyTypeKind.ZodDefault:+ return parseDefaultDef(def, refs);+ case ZodFirstPartyTypeKind.ZodBranded:+ return parseBrandedDef(def, refs);+ case ZodFirstPartyTypeKind.ZodReadonly:+ return parseReadonlyDef(def, refs);+ case ZodFirstPartyTypeKind.ZodCatch:+ return parseCatchDef(def, refs);+ case ZodFirstPartyTypeKind.ZodPipeline:+ return parsePipelineDef(def, refs);+ case ZodFirstPartyTypeKind.ZodFunction:+ case ZodFirstPartyTypeKind.ZodVoid:+ case ZodFirstPartyTypeKind.ZodSymbol:+ return void 0;+ default:+ return /* @__PURE__ */ ((_) => void 0)(typeName);+ }+};++// node_modules/zod-to-json-schema/dist/esm/parseDef.js+function parseDef(def, refs, forceResolution = false) {+ const seenItem = refs.seen.get(def);+ if (refs.override) {+ const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);+ if (overrideResult !== ignoreOverride) {+ return overrideResult;+ }+ }+ if (seenItem && !forceResolution) {+ const seenSchema = get$ref(seenItem, refs);+ if (seenSchema !== void 0) {+ return seenSchema;+ }+ }+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };+ refs.seen.set(def, newItem);+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);+ const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;+ if (jsonSchema) {+ addMeta(def, refs, jsonSchema);+ }+ if (refs.postProcess) {+ const postProcessResult = refs.postProcess(jsonSchema, def, refs);+ newItem.jsonSchema = jsonSchema;+ return postProcessResult;+ }+ newItem.jsonSchema = jsonSchema;+ return jsonSchema;+}+var get$ref = (item, refs) => {+ switch (refs.$refStrategy) {+ case "root":+ return { $ref: item.path.join("/") };+ case "relative":+ return { $ref: getRelativePath(refs.currentPath, item.path) };+ case "none":+ case "seen": {+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {+ console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);+ return parseAnyDef(refs);+ }+ return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0;+ }+ }+};+var addMeta = (def, refs, jsonSchema) => {+ if (def.description) {+ jsonSchema.description = def.description;+ if (refs.markdownDescription) {+ jsonSchema.markdownDescription = def.description;+ }+ }+ return jsonSchema;+};++// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js+var zodToJsonSchema = (schema, options) => {+ const refs = getRefs(options);+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name4, schema2]) => ({+ ...acc,+ [name4]: parseDef(schema2._def, {+ ...refs,+ currentPath: [...refs.basePath, refs.definitionPath, name4]+ }, true) ?? parseAnyDef(refs)+ }), {}) : void 0;+ const name3 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;+ const main = parseDef(schema._def, name3 === void 0 ? refs : {+ ...refs,+ currentPath: [...refs.basePath, refs.definitionPath, name3]+ }, false) ?? parseAnyDef(refs);+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;+ if (title !== void 0) {+ main.title = title;+ }+ if (refs.flags.hasReferencedOpenAiAnyType) {+ if (!definitions) {+ definitions = {};+ }+ if (!definitions[refs.openAiAnyTypeName]) {+ definitions[refs.openAiAnyTypeName] = {+ // Skipping "object" as no properties can be defined and additionalProperties must be "false"+ type: ["string", "number", "integer", "boolean", "array", "null"],+ items: {+ $ref: refs.$refStrategy === "relative" ? "1" : [+ ...refs.basePath,+ refs.definitionPath,+ refs.openAiAnyTypeName+ ].join("/")+ }+ };+ }+ }+ const combined = name3 === void 0 ? definitions ? {+ ...main,+ [refs.definitionPath]: definitions+ } : main : {+ $ref: [+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,+ refs.definitionPath,+ name3+ ].join("/"),+ [refs.definitionPath]: {+ ...definitions,+ [name3]: main+ }+ };+ if (refs.target === "jsonSchema7") {+ combined.$schema = "http://json-schema.org/draft-07/schema#";+ } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {+ combined.$schema = "https://json-schema.org/draft/2019-09/schema#";+ }+ if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {+ console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");+ }+ return combined;+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js+function mapMiniTarget(t) {+ if (!t)+ return "draft-7";+ if (t === "jsonSchema7" || t === "draft-7")+ return "draft-7";+ if (t === "jsonSchema2019-09" || t === "draft-2020-12")+ return "draft-2020-12";+ return "draft-7";+}+function toJsonSchemaCompat(schema, opts) {+ if (isZ4Schema(schema)) {+ return toJSONSchema(schema, {+ target: mapMiniTarget(opts?.target),+ io: opts?.pipeStrategy ?? "input"+ });+ }+ return zodToJsonSchema(schema, {+ strictUnions: opts?.strictUnions ?? true,+ pipeStrategy: opts?.pipeStrategy ?? "input"+ });+}+function getMethodLiteral(schema) {+ const shape = getObjectShape(schema);+ const methodSchema = shape?.method;+ if (!methodSchema) {+ throw new Error("Schema is missing a method literal");+ }+ const value = getLiteralValue(methodSchema);+ if (typeof value !== "string") {+ throw new Error("Schema method literal must be a string");+ }+ return value;+}+function parseWithCompat(schema, data) {+ const result = safeParse3(schema, data);+ if (!result.success) {+ throw result.error;+ }+ return result.data;+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js+var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;+var Protocol = class {+ constructor(_options) {+ this._options = _options;+ this._requestMessageId = 0;+ this._requestHandlers = /* @__PURE__ */ new Map();+ this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();+ this._notificationHandlers = /* @__PURE__ */ new Map();+ this._responseHandlers = /* @__PURE__ */ new Map();+ this._progressHandlers = /* @__PURE__ */ new Map();+ this._timeoutInfo = /* @__PURE__ */ new Map();+ this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();+ this._taskProgressTokens = /* @__PURE__ */ new Map();+ this._requestResolvers = /* @__PURE__ */ new Map();+ this.setNotificationHandler(CancelledNotificationSchema, (notification) => {+ this._oncancel(notification);+ });+ this.setNotificationHandler(ProgressNotificationSchema, (notification) => {+ this._onprogress(notification);+ });+ this.setRequestHandler(+ PingRequestSchema,+ // Automatic pong by default.+ (_request) => ({})+ );+ this._taskStore = _options?.taskStore;+ this._taskMessageQueue = _options?.taskMessageQueue;+ if (this._taskStore) {+ this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);+ if (!task) {+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");+ }+ return {+ ...task+ };+ });+ this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {+ const handleTaskResult = async () => {+ const taskId = request.params.taskId;+ if (this._taskMessageQueue) {+ let queuedMessage;+ while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {+ if (queuedMessage.type === "response" || queuedMessage.type === "error") {+ const message = queuedMessage.message;+ const requestId = message.id;+ const resolver = this._requestResolvers.get(requestId);+ if (resolver) {+ this._requestResolvers.delete(requestId);+ if (queuedMessage.type === "response") {+ resolver(message);+ } else {+ const errorMessage = message;+ const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);+ resolver(error2);+ }+ } else {+ const messageType = queuedMessage.type === "response" ? "Response" : "Error";+ this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));+ }+ continue;+ }+ await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });+ }+ }+ const task = await this._taskStore.getTask(taskId, extra.sessionId);+ if (!task) {+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);+ }+ if (!isTerminal(task.status)) {+ await this._waitForTaskUpdate(taskId, extra.signal);+ return await handleTaskResult();+ }+ if (isTerminal(task.status)) {+ const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);+ this._clearTaskQueue(taskId);+ return {+ ...result,+ _meta: {+ ...result._meta,+ [RELATED_TASK_META_KEY]: {+ taskId+ }+ }+ };+ }+ return await handleTaskResult();+ };+ return await handleTaskResult();+ });+ this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {+ try {+ const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);+ return {+ tasks,+ nextCursor,+ _meta: {}+ };+ } catch (error2) {+ throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);+ }+ });+ this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {+ try {+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);+ if (!task) {+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);+ }+ if (isTerminal(task.status)) {+ throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);+ }+ await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);+ this._clearTaskQueue(request.params.taskId);+ const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);+ if (!cancelledTask) {+ throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);+ }+ return {+ _meta: {},+ ...cancelledTask+ };+ } catch (error2) {+ if (error2 instanceof McpError) {+ throw error2;+ }+ throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);+ }+ });+ }+ }+ async _oncancel(notification) {+ if (!notification.params.requestId) {+ return;+ }+ const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);+ controller?.abort(notification.params.reason);+ }+ _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {+ this._timeoutInfo.set(messageId, {+ timeoutId: setTimeout(onTimeout, timeout),+ startTime: Date.now(),+ timeout,+ maxTotalTimeout,+ resetTimeoutOnProgress,+ onTimeout+ });+ }+ _resetTimeout(messageId) {+ const info = this._timeoutInfo.get(messageId);+ if (!info)+ return false;+ const totalElapsed = Date.now() - info.startTime;+ if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {+ this._timeoutInfo.delete(messageId);+ throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {+ maxTotalTimeout: info.maxTotalTimeout,+ totalElapsed+ });+ }+ clearTimeout(info.timeoutId);+ info.timeoutId = setTimeout(info.onTimeout, info.timeout);+ return true;+ }+ _cleanupTimeout(messageId) {+ const info = this._timeoutInfo.get(messageId);+ if (info) {+ clearTimeout(info.timeoutId);+ this._timeoutInfo.delete(messageId);+ }+ }+ /**+ * Attaches to the given transport, starts it, and starts listening for messages.+ *+ * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.+ */+ async connect(transport2) {+ if (this._transport) {+ throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");+ }+ this._transport = transport2;+ const _onclose = this.transport?.onclose;+ this._transport.onclose = () => {+ _onclose?.();+ this._onclose();+ };+ const _onerror = this.transport?.onerror;+ this._transport.onerror = (error2) => {+ _onerror?.(error2);+ this._onerror(error2);+ };+ const _onmessage = this._transport?.onmessage;+ this._transport.onmessage = (message, extra) => {+ _onmessage?.(message, extra);+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {+ this._onresponse(message);+ } else if (isJSONRPCRequest(message)) {+ this._onrequest(message, extra);+ } else if (isJSONRPCNotification(message)) {+ this._onnotification(message);+ } else {+ this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));+ }+ };+ await this._transport.start();+ }+ _onclose() {+ const responseHandlers = this._responseHandlers;+ this._responseHandlers = /* @__PURE__ */ new Map();+ this._progressHandlers.clear();+ this._taskProgressTokens.clear();+ this._pendingDebouncedNotifications.clear();+ for (const info of this._timeoutInfo.values()) {+ clearTimeout(info.timeoutId);+ }+ this._timeoutInfo.clear();+ for (const controller of this._requestHandlerAbortControllers.values()) {+ controller.abort();+ }+ this._requestHandlerAbortControllers.clear();+ const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");+ this._transport = void 0;+ this.onclose?.();+ for (const handler of responseHandlers.values()) {+ handler(error2);+ }+ }+ _onerror(error2) {+ this.onerror?.(error2);+ }+ _onnotification(notification) {+ const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;+ if (handler === void 0) {+ return;+ }+ Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));+ }+ _onrequest(request, extra) {+ const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;+ const capturedTransport = this._transport;+ const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;+ if (handler === void 0) {+ const errorResponse = {+ jsonrpc: "2.0",+ id: request.id,+ error: {+ code: ErrorCode.MethodNotFound,+ message: "Method not found"+ }+ };+ if (relatedTaskId && this._taskMessageQueue) {+ this._enqueueTaskMessage(relatedTaskId, {+ type: "error",+ message: errorResponse,+ timestamp: Date.now()+ }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));+ } else {+ capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));+ }+ return;+ }+ const abortController = new AbortController();+ this._requestHandlerAbortControllers.set(request.id, abortController);+ const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;+ const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;+ const fullExtra = {+ signal: abortController.signal,+ sessionId: capturedTransport?.sessionId,+ _meta: request.params?._meta,+ sendNotification: async (notification) => {+ if (abortController.signal.aborted)+ return;+ const notificationOptions = { relatedRequestId: request.id };+ if (relatedTaskId) {+ notificationOptions.relatedTask = { taskId: relatedTaskId };+ }+ await this.notification(notification, notificationOptions);+ },+ sendRequest: async (r, resultSchema, options) => {+ if (abortController.signal.aborted) {+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");+ }+ const requestOptions = { ...options, relatedRequestId: request.id };+ if (relatedTaskId && !requestOptions.relatedTask) {+ requestOptions.relatedTask = { taskId: relatedTaskId };+ }+ const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;+ if (effectiveTaskId && taskStore) {+ await taskStore.updateTaskStatus(effectiveTaskId, "input_required");+ }+ return await this.request(r, resultSchema, requestOptions);+ },+ authInfo: extra?.authInfo,+ requestId: request.id,+ requestInfo: extra?.requestInfo,+ taskId: relatedTaskId,+ taskStore,+ taskRequestedTtl: taskCreationParams?.ttl,+ closeSSEStream: extra?.closeSSEStream,+ closeStandaloneSSEStream: extra?.closeStandaloneSSEStream+ };+ Promise.resolve().then(() => {+ if (taskCreationParams) {+ this.assertTaskHandlerCapability(request.method);+ }+ }).then(() => handler(request, fullExtra)).then(async (result) => {+ if (abortController.signal.aborted) {+ return;+ }+ const response = {+ result,+ jsonrpc: "2.0",+ id: request.id+ };+ if (relatedTaskId && this._taskMessageQueue) {+ await this._enqueueTaskMessage(relatedTaskId, {+ type: "response",+ message: response,+ timestamp: Date.now()+ }, capturedTransport?.sessionId);+ } else {+ await capturedTransport?.send(response);+ }+ }, async (error2) => {+ if (abortController.signal.aborted) {+ return;+ }+ const errorResponse = {+ jsonrpc: "2.0",+ id: request.id,+ error: {+ code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,+ message: error2.message ?? "Internal error",+ ...error2["data"] !== void 0 && { data: error2["data"] }+ }+ };+ if (relatedTaskId && this._taskMessageQueue) {+ await this._enqueueTaskMessage(relatedTaskId, {+ type: "error",+ message: errorResponse,+ timestamp: Date.now()+ }, capturedTransport?.sessionId);+ } else {+ await capturedTransport?.send(errorResponse);+ }+ }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {+ if (this._requestHandlerAbortControllers.get(request.id) === abortController) {+ this._requestHandlerAbortControllers.delete(request.id);+ }+ });+ }+ _onprogress(notification) {+ const { progressToken, ...params } = notification.params;+ const messageId = Number(progressToken);+ const handler = this._progressHandlers.get(messageId);+ if (!handler) {+ this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));+ return;+ }+ const responseHandler = this._responseHandlers.get(messageId);+ const timeoutInfo = this._timeoutInfo.get(messageId);+ if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {+ try {+ this._resetTimeout(messageId);+ } catch (error2) {+ this._responseHandlers.delete(messageId);+ this._progressHandlers.delete(messageId);+ this._cleanupTimeout(messageId);+ responseHandler(error2);+ return;+ }+ }+ handler(params);+ }+ _onresponse(response) {+ const messageId = Number(response.id);+ const resolver = this._requestResolvers.get(messageId);+ if (resolver) {+ this._requestResolvers.delete(messageId);+ if (isJSONRPCResultResponse(response)) {+ resolver(response);+ } else {+ const error2 = new McpError(response.error.code, response.error.message, response.error.data);+ resolver(error2);+ }+ return;+ }+ const handler = this._responseHandlers.get(messageId);+ if (handler === void 0) {+ this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));+ return;+ }+ this._responseHandlers.delete(messageId);+ this._cleanupTimeout(messageId);+ let isTaskResponse = false;+ if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {+ const result = response.result;+ if (result.task && typeof result.task === "object") {+ const task = result.task;+ if (typeof task.taskId === "string") {+ isTaskResponse = true;+ this._taskProgressTokens.set(task.taskId, messageId);+ }+ }+ }+ if (!isTaskResponse) {+ this._progressHandlers.delete(messageId);+ }+ if (isJSONRPCResultResponse(response)) {+ handler(response);+ } else {+ const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);+ handler(error2);+ }+ }+ get transport() {+ return this._transport;+ }+ /**+ * Closes the connection.+ */+ async close() {+ await this._transport?.close();+ }+ /**+ * Sends a request and returns an AsyncGenerator that yields response messages.+ * The generator is guaranteed to end with either a 'result' or 'error' message.+ *+ * @example+ * ```typescript+ * const stream = protocol.requestStream(request, resultSchema, options);+ * for await (const message of stream) {+ * switch (message.type) {+ * case 'taskCreated':+ * console.log('Task created:', message.task.taskId);+ * break;+ * case 'taskStatus':+ * console.log('Task status:', message.task.status);+ * break;+ * case 'result':+ * console.log('Final result:', message.result);+ * break;+ * case 'error':+ * console.error('Error:', message.error);+ * break;+ * }+ * }+ * ```+ *+ * @experimental Use `client.experimental.tasks.requestStream()` to access this method.+ */+ async *requestStream(request, resultSchema, options) {+ const { task } = options ?? {};+ if (!task) {+ try {+ const result = await this.request(request, resultSchema, options);+ yield { type: "result", result };+ } catch (error2) {+ yield {+ type: "error",+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))+ };+ }+ return;+ }+ let taskId;+ try {+ const createResult = await this.request(request, CreateTaskResultSchema, options);+ if (createResult.task) {+ taskId = createResult.task.taskId;+ yield { type: "taskCreated", task: createResult.task };+ } else {+ throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");+ }+ while (true) {+ const task2 = await this.getTask({ taskId }, options);+ yield { type: "taskStatus", task: task2 };+ if (isTerminal(task2.status)) {+ if (task2.status === "completed") {+ const result = await this.getTaskResult({ taskId }, resultSchema, options);+ yield { type: "result", result };+ } else if (task2.status === "failed") {+ yield {+ type: "error",+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)+ };+ } else if (task2.status === "cancelled") {+ yield {+ type: "error",+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)+ };+ }+ return;+ }+ if (task2.status === "input_required") {+ const result = await this.getTaskResult({ taskId }, resultSchema, options);+ yield { type: "result", result };+ return;+ }+ const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));+ options?.signal?.throwIfAborted();+ }+ } catch (error2) {+ yield {+ type: "error",+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))+ };+ }+ }+ /**+ * Sends a request and waits for a response.+ *+ * Do not use this method to emit notifications! Use notification() instead.+ */+ request(request, resultSchema, options) {+ const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};+ return new Promise((resolve2, reject) => {+ const earlyReject = (error2) => {+ reject(error2);+ };+ if (!this._transport) {+ earlyReject(new Error("Not connected"));+ return;+ }+ if (this._options?.enforceStrictCapabilities === true) {+ try {+ this.assertCapabilityForMethod(request.method);+ if (task) {+ this.assertTaskCapability(request.method);+ }+ } catch (e) {+ earlyReject(e);+ return;+ }+ }+ options?.signal?.throwIfAborted();+ const messageId = this._requestMessageId++;+ const jsonrpcRequest = {+ ...request,+ jsonrpc: "2.0",+ id: messageId+ };+ if (options?.onprogress) {+ this._progressHandlers.set(messageId, options.onprogress);+ jsonrpcRequest.params = {+ ...request.params,+ _meta: {+ ...request.params?._meta || {},+ progressToken: messageId+ }+ };+ }+ if (task) {+ jsonrpcRequest.params = {+ ...jsonrpcRequest.params,+ task+ };+ }+ if (relatedTask) {+ jsonrpcRequest.params = {+ ...jsonrpcRequest.params,+ _meta: {+ ...jsonrpcRequest.params?._meta || {},+ [RELATED_TASK_META_KEY]: relatedTask+ }+ };+ }+ const cancel = (reason) => {+ this._responseHandlers.delete(messageId);+ this._progressHandlers.delete(messageId);+ this._cleanupTimeout(messageId);+ this._transport?.send({+ jsonrpc: "2.0",+ method: "notifications/cancelled",+ params: {+ requestId: messageId,+ reason: String(reason)+ }+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));+ const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));+ reject(error2);+ };+ this._responseHandlers.set(messageId, (response) => {+ if (options?.signal?.aborted) {+ return;+ }+ if (response instanceof Error) {+ return reject(response);+ }+ try {+ const parseResult = safeParse3(resultSchema, response.result);+ if (!parseResult.success) {+ reject(parseResult.error);+ } else {+ resolve2(parseResult.data);+ }+ } catch (error2) {+ reject(error2);+ }+ });+ options?.signal?.addEventListener("abort", () => {+ cancel(options?.signal?.reason);+ });+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;+ const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);+ const relatedTaskId = relatedTask?.taskId;+ if (relatedTaskId) {+ const responseResolver = (response) => {+ const handler = this._responseHandlers.get(messageId);+ if (handler) {+ handler(response);+ } else {+ this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));+ }+ };+ this._requestResolvers.set(messageId, responseResolver);+ this._enqueueTaskMessage(relatedTaskId, {+ type: "request",+ message: jsonrpcRequest,+ timestamp: Date.now()+ }).catch((error2) => {+ this._cleanupTimeout(messageId);+ reject(error2);+ });+ } else {+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {+ this._cleanupTimeout(messageId);+ reject(error2);+ });+ }+ });+ }+ /**+ * Gets the current status of a task.+ *+ * @experimental Use `client.experimental.tasks.getTask()` to access this method.+ */+ async getTask(params, options) {+ return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);+ }+ /**+ * Retrieves the result of a completed task.+ *+ * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.+ */+ async getTaskResult(params, resultSchema, options) {+ return this.request({ method: "tasks/result", params }, resultSchema, options);+ }+ /**+ * Lists tasks, optionally starting from a pagination cursor.+ *+ * @experimental Use `client.experimental.tasks.listTasks()` to access this method.+ */+ async listTasks(params, options) {+ return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);+ }+ /**+ * Cancels a specific task.+ *+ * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.+ */+ async cancelTask(params, options) {+ return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);+ }+ /**+ * Emits a notification, which is a one-way message that does not expect a response.+ */+ async notification(notification, options) {+ if (!this._transport) {+ throw new Error("Not connected");+ }+ this.assertNotificationCapability(notification.method);+ const relatedTaskId = options?.relatedTask?.taskId;+ if (relatedTaskId) {+ const jsonrpcNotification2 = {+ ...notification,+ jsonrpc: "2.0",+ params: {+ ...notification.params,+ _meta: {+ ...notification.params?._meta || {},+ [RELATED_TASK_META_KEY]: options.relatedTask+ }+ }+ };+ await this._enqueueTaskMessage(relatedTaskId, {+ type: "notification",+ message: jsonrpcNotification2,+ timestamp: Date.now()+ });+ return;+ }+ const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;+ if (canDebounce) {+ if (this._pendingDebouncedNotifications.has(notification.method)) {+ return;+ }+ this._pendingDebouncedNotifications.add(notification.method);+ Promise.resolve().then(() => {+ this._pendingDebouncedNotifications.delete(notification.method);+ if (!this._transport) {+ return;+ }+ let jsonrpcNotification2 = {+ ...notification,+ jsonrpc: "2.0"+ };+ if (options?.relatedTask) {+ jsonrpcNotification2 = {+ ...jsonrpcNotification2,+ params: {+ ...jsonrpcNotification2.params,+ _meta: {+ ...jsonrpcNotification2.params?._meta || {},+ [RELATED_TASK_META_KEY]: options.relatedTask+ }+ }+ };+ }+ this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));+ });+ return;+ }+ let jsonrpcNotification = {+ ...notification,+ jsonrpc: "2.0"+ };+ if (options?.relatedTask) {+ jsonrpcNotification = {+ ...jsonrpcNotification,+ params: {+ ...jsonrpcNotification.params,+ _meta: {+ ...jsonrpcNotification.params?._meta || {},+ [RELATED_TASK_META_KEY]: options.relatedTask+ }+ }+ };+ }+ await this._transport.send(jsonrpcNotification, options);+ }+ /**+ * Registers a handler to invoke when this protocol object receives a request with the given method.+ *+ * Note that this will replace any previous request handler for the same method.+ */+ setRequestHandler(requestSchema, handler) {+ const method = getMethodLiteral(requestSchema);+ this.assertRequestHandlerCapability(method);+ this._requestHandlers.set(method, (request, extra) => {+ const parsed = parseWithCompat(requestSchema, request);+ return Promise.resolve(handler(parsed, extra));+ });+ }+ /**+ * Removes the request handler for the given method.+ */+ removeRequestHandler(method) {+ this._requestHandlers.delete(method);+ }+ /**+ * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.+ */+ assertCanSetRequestHandler(method) {+ if (this._requestHandlers.has(method)) {+ throw new Error(`A request handler for ${method} already exists, which would be overridden`);+ }+ }+ /**+ * Registers a handler to invoke when this protocol object receives a notification with the given method.+ *+ * Note that this will replace any previous notification handler for the same method.+ */+ setNotificationHandler(notificationSchema, handler) {+ const method = getMethodLiteral(notificationSchema);+ this._notificationHandlers.set(method, (notification) => {+ const parsed = parseWithCompat(notificationSchema, notification);+ return Promise.resolve(handler(parsed));+ });+ }+ /**+ * Removes the notification handler for the given method.+ */+ removeNotificationHandler(method) {+ this._notificationHandlers.delete(method);+ }+ /**+ * Cleans up the progress handler associated with a task.+ * This should be called when a task reaches a terminal status.+ */+ _cleanupTaskProgressHandler(taskId) {+ const progressToken = this._taskProgressTokens.get(taskId);+ if (progressToken !== void 0) {+ this._progressHandlers.delete(progressToken);+ this._taskProgressTokens.delete(taskId);+ }+ }+ /**+ * Enqueues a task-related message for side-channel delivery via tasks/result.+ * @param taskId The task ID to associate the message with+ * @param message The message to enqueue+ * @param sessionId Optional session ID for binding the operation to a specific session+ * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)+ *+ * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle+ * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer+ * simply propagates the error.+ */+ async _enqueueTaskMessage(taskId, message, sessionId) {+ if (!this._taskStore || !this._taskMessageQueue) {+ throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");+ }+ const maxQueueSize = this._options?.maxTaskQueueSize;+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);+ }+ /**+ * Clears the message queue for a task and rejects any pending request resolvers.+ * @param taskId The task ID whose queue should be cleared+ * @param sessionId Optional session ID for binding the operation to a specific session+ */+ async _clearTaskQueue(taskId, sessionId) {+ if (this._taskMessageQueue) {+ const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);+ for (const message of messages) {+ if (message.type === "request" && isJSONRPCRequest(message.message)) {+ const requestId = message.message.id;+ const resolver = this._requestResolvers.get(requestId);+ if (resolver) {+ resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));+ this._requestResolvers.delete(requestId);+ } else {+ this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));+ }+ }+ }+ }+ }+ /**+ * Waits for a task update (new messages or status change) with abort signal support.+ * Uses polling to check for updates at the task's configured poll interval.+ * @param taskId The task ID to wait for+ * @param signal Abort signal to cancel the wait+ * @returns Promise that resolves when an update occurs or rejects if aborted+ */+ async _waitForTaskUpdate(taskId, signal) {+ let interval = this._options?.defaultTaskPollInterval ?? 1e3;+ try {+ const task = await this._taskStore?.getTask(taskId);+ if (task?.pollInterval) {+ interval = task.pollInterval;+ }+ } catch {+ }+ return new Promise((resolve2, reject) => {+ if (signal.aborted) {+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));+ return;+ }+ const timeoutId = setTimeout(resolve2, interval);+ signal.addEventListener("abort", () => {+ clearTimeout(timeoutId);+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));+ }, { once: true });+ });+ }+ requestTaskStore(request, sessionId) {+ const taskStore = this._taskStore;+ if (!taskStore) {+ throw new Error("No task store configured");+ }+ return {+ createTask: async (taskParams) => {+ if (!request) {+ throw new Error("No request provided");+ }+ return await taskStore.createTask(taskParams, request.id, {+ method: request.method,+ params: request.params+ }, sessionId);+ },+ getTask: async (taskId) => {+ const task = await taskStore.getTask(taskId, sessionId);+ if (!task) {+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");+ }+ return task;+ },+ storeTaskResult: async (taskId, status, result) => {+ await taskStore.storeTaskResult(taskId, status, result, sessionId);+ const task = await taskStore.getTask(taskId, sessionId);+ if (task) {+ const notification = TaskStatusNotificationSchema.parse({+ method: "notifications/tasks/status",+ params: task+ });+ await this.notification(notification);+ if (isTerminal(task.status)) {+ this._cleanupTaskProgressHandler(taskId);+ }+ }+ },+ getTaskResult: (taskId) => {+ return taskStore.getTaskResult(taskId, sessionId);+ },+ updateTaskStatus: async (taskId, status, statusMessage) => {+ const task = await taskStore.getTask(taskId, sessionId);+ if (!task) {+ throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);+ }+ if (isTerminal(task.status)) {+ throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);+ }+ await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);+ const updatedTask = await taskStore.getTask(taskId, sessionId);+ if (updatedTask) {+ const notification = TaskStatusNotificationSchema.parse({+ method: "notifications/tasks/status",+ params: updatedTask+ });+ await this.notification(notification);+ if (isTerminal(updatedTask.status)) {+ this._cleanupTaskProgressHandler(taskId);+ }+ }+ },+ listTasks: (cursor) => {+ return taskStore.listTasks(cursor, sessionId);+ }+ };+ }+};+function isPlainObject3(value) {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}+function mergeCapabilities(base, additional) {+ const result = { ...base };+ for (const key in additional) {+ const k = key;+ const addValue = additional[k];+ if (addValue === void 0)+ continue;+ const baseValue = result[k];+ if (isPlainObject3(baseValue) && isPlainObject3(addValue)) {+ result[k] = { ...baseValue, ...addValue };+ } else {+ result[k] = addValue;+ }+ }+ return result;+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js+var import_ajv = __toESM(require_ajv(), 1);+var import_ajv_formats = __toESM(require_dist(), 1);+function createDefaultAjvInstance() {+ const ajv = new import_ajv.default({+ strict: false,+ validateFormats: true,+ validateSchema: false,+ allErrors: true+ });+ const addFormats = import_ajv_formats.default;+ addFormats(ajv);+ return ajv;+}+var AjvJsonSchemaValidator = class {+ /**+ * Create an AJV validator+ *+ * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.+ *+ * @example+ * ```typescript+ * // Use default configuration (recommended for most cases)+ * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';+ * const validator = new AjvJsonSchemaValidator();+ *+ * // Or provide custom AJV instance for advanced configuration+ * import { Ajv } from 'ajv';+ * import addFormats from 'ajv-formats';+ *+ * const ajv = new Ajv({ validateFormats: true });+ * addFormats(ajv);+ * const validator = new AjvJsonSchemaValidator(ajv);+ * ```+ */+ constructor(ajv) {+ this._ajv = ajv ?? createDefaultAjvInstance();+ }+ /**+ * Create a validator for the given JSON Schema+ *+ * The validator is compiled once and can be reused multiple times.+ * If the schema has an $id, it will be cached by AJV automatically.+ *+ * @param schema - Standard JSON Schema object+ * @returns A validator function that validates input data+ */+ getValidator(schema) {+ const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);+ return (input) => {+ const valid = ajvValidator(input);+ if (valid) {+ return {+ valid: true,+ data: input,+ errorMessage: void 0+ };+ } else {+ return {+ valid: false,+ data: void 0,+ errorMessage: this._ajv.errorsText(ajvValidator.errors)+ };+ }+ };+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js+var ExperimentalServerTasks = class {+ constructor(_server) {+ this._server = _server;+ }+ /**+ * Sends a request and returns an AsyncGenerator that yields response messages.+ * The generator is guaranteed to end with either a 'result' or 'error' message.+ *+ * This method provides streaming access to request processing, allowing you to+ * observe intermediate task status updates for task-augmented requests.+ *+ * @param request - The request to send+ * @param resultSchema - Zod schema for validating the result+ * @param options - Optional request options (timeout, signal, task creation params, etc.)+ * @returns AsyncGenerator that yields ResponseMessage objects+ *+ * @experimental+ */+ requestStream(request, resultSchema, options) {+ return this._server.requestStream(request, resultSchema, options);+ }+ /**+ * Sends a sampling request and returns an AsyncGenerator that yields response messages.+ * The generator is guaranteed to end with either a 'result' or 'error' message.+ *+ * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages+ * before the final result.+ *+ * @example+ * ```typescript+ * const stream = server.experimental.tasks.createMessageStream({+ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],+ * maxTokens: 100+ * }, {+ * onprogress: (progress) => {+ * // Handle streaming tokens via progress notifications+ * console.log('Progress:', progress.message);+ * }+ * });+ *+ * for await (const message of stream) {+ * switch (message.type) {+ * case 'taskCreated':+ * console.log('Task created:', message.task.taskId);+ * break;+ * case 'taskStatus':+ * console.log('Task status:', message.task.status);+ * break;+ * case 'result':+ * console.log('Final result:', message.result);+ * break;+ * case 'error':+ * console.error('Error:', message.error);+ * break;+ * }+ * }+ * ```+ *+ * @param params - The sampling request parameters+ * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)+ * @returns AsyncGenerator that yields ResponseMessage objects+ *+ * @experimental+ */+ createMessageStream(params, options) {+ const clientCapabilities = this._server.getClientCapabilities();+ if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {+ throw new Error("Client does not support sampling tools capability.");+ }+ if (params.messages.length > 0) {+ const lastMessage = params.messages[params.messages.length - 1];+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");+ if (hasToolResults) {+ if (lastContent.some((c) => c.type !== "tool_result")) {+ throw new Error("The last message must contain only tool_result content if any is present");+ }+ if (!hasPreviousToolUse) {+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");+ }+ }+ if (hasPreviousToolUse) {+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");+ }+ }+ }+ return this.requestStream({+ method: "sampling/createMessage",+ params+ }, CreateMessageResultSchema, options);+ }+ /**+ * Sends an elicitation request and returns an AsyncGenerator that yields response messages.+ * The generator is guaranteed to end with either a 'result' or 'error' message.+ *+ * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'+ * and 'taskStatus' messages before the final result.+ *+ * @example+ * ```typescript+ * const stream = server.experimental.tasks.elicitInputStream({+ * mode: 'url',+ * message: 'Please authenticate',+ * elicitationId: 'auth-123',+ * url: 'https://example.com/auth'+ * }, {+ * task: { ttl: 300000 } // Task-augmented for long-running auth flow+ * });+ *+ * for await (const message of stream) {+ * switch (message.type) {+ * case 'taskCreated':+ * console.log('Task created:', message.task.taskId);+ * break;+ * case 'taskStatus':+ * console.log('Task status:', message.task.status);+ * break;+ * case 'result':+ * console.log('User action:', message.result.action);+ * break;+ * case 'error':+ * console.error('Error:', message.error);+ * break;+ * }+ * }+ * ```+ *+ * @param params - The elicitation request parameters+ * @param options - Optional request options (timeout, signal, task creation params, etc.)+ * @returns AsyncGenerator that yields ResponseMessage objects+ *+ * @experimental+ */+ elicitInputStream(params, options) {+ const clientCapabilities = this._server.getClientCapabilities();+ const mode = params.mode ?? "form";+ switch (mode) {+ case "url": {+ if (!clientCapabilities?.elicitation?.url) {+ throw new Error("Client does not support url elicitation.");+ }+ break;+ }+ case "form": {+ if (!clientCapabilities?.elicitation?.form) {+ throw new Error("Client does not support form elicitation.");+ }+ break;+ }+ }+ const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params;+ return this.requestStream({+ method: "elicitation/create",+ params: normalizedParams+ }, ElicitResultSchema, options);+ }+ /**+ * Gets the current status of a task.+ *+ * @param taskId - The task identifier+ * @param options - Optional request options+ * @returns The task status+ *+ * @experimental+ */+ async getTask(taskId, options) {+ return this._server.getTask({ taskId }, options);+ }+ /**+ * Retrieves the result of a completed task.+ *+ * @param taskId - The task identifier+ * @param resultSchema - Zod schema for validating the result+ * @param options - Optional request options+ * @returns The task result+ *+ * @experimental+ */+ async getTaskResult(taskId, resultSchema, options) {+ return this._server.getTaskResult({ taskId }, resultSchema, options);+ }+ /**+ * Lists tasks with optional pagination.+ *+ * @param cursor - Optional pagination cursor+ * @param options - Optional request options+ * @returns List of tasks with optional next cursor+ *+ * @experimental+ */+ async listTasks(cursor, options) {+ return this._server.listTasks(cursor ? { cursor } : void 0, options);+ }+ /**+ * Cancels a running task.+ *+ * @param taskId - The task identifier+ * @param options - Optional request options+ *+ * @experimental+ */+ async cancelTask(taskId, options) {+ return this._server.cancelTask({ taskId }, options);+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js+function assertToolsCallTaskCapability(requests, method, entityName) {+ if (!requests) {+ throw new Error(`${entityName} does not support task creation (required for ${method})`);+ }+ switch (method) {+ case "tools/call":+ if (!requests.tools?.call) {+ throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);+ }+ break;+ default:+ break;+ }+}+function assertClientRequestTaskCapability(requests, method, entityName) {+ if (!requests) {+ throw new Error(`${entityName} does not support task creation (required for ${method})`);+ }+ switch (method) {+ case "sampling/createMessage":+ if (!requests.sampling?.createMessage) {+ throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);+ }+ break;+ case "elicitation/create":+ if (!requests.elicitation?.create) {+ throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);+ }+ break;+ default:+ break;+ }+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js+var Server = class extends Protocol {+ /**+ * Initializes this server with the given name and version information.+ */+ constructor(_serverInfo, options) {+ super(options);+ this._serverInfo = _serverInfo;+ this._loggingLevels = /* @__PURE__ */ new Map();+ this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));+ this.isMessageIgnored = (level, sessionId) => {+ const currentLevel = this._loggingLevels.get(sessionId);+ return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;+ };+ this._capabilities = options?.capabilities ?? {};+ this._instructions = options?.instructions;+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();+ this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));+ this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());+ if (this._capabilities.logging) {+ this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;+ const { level } = request.params;+ const parseResult = LoggingLevelSchema.safeParse(level);+ if (parseResult.success) {+ this._loggingLevels.set(transportSessionId, parseResult.data);+ }+ return {};+ });+ }+ }+ /**+ * Access experimental features.+ *+ * WARNING: These APIs are experimental and may change without notice.+ *+ * @experimental+ */+ get experimental() {+ if (!this._experimental) {+ this._experimental = {+ tasks: new ExperimentalServerTasks(this)+ };+ }+ return this._experimental;+ }+ /**+ * Registers new capabilities. This can only be called before connecting to a transport.+ *+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).+ */+ registerCapabilities(capabilities) {+ if (this.transport) {+ throw new Error("Cannot register capabilities after connecting to transport");+ }+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);+ }+ /**+ * Override request handler registration to enforce server-side validation for tools/call.+ */+ setRequestHandler(requestSchema, handler) {+ const shape = getObjectShape(requestSchema);+ const methodSchema = shape?.method;+ if (!methodSchema) {+ throw new Error("Schema is missing a method literal");+ }+ let methodValue;+ if (isZ4Schema(methodSchema)) {+ const v4Schema = methodSchema;+ const v4Def = v4Schema._zod?.def;+ methodValue = v4Def?.value ?? v4Schema.value;+ } else {+ const v3Schema = methodSchema;+ const legacyDef = v3Schema._def;+ methodValue = legacyDef?.value ?? v3Schema.value;+ }+ if (typeof methodValue !== "string") {+ throw new Error("Schema method literal must be a string");+ }+ const method = methodValue;+ if (method === "tools/call") {+ const wrappedHandler = async (request, extra) => {+ const validatedRequest = safeParse3(CallToolRequestSchema, request);+ if (!validatedRequest.success) {+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);+ }+ const { params } = validatedRequest.data;+ const result = await Promise.resolve(handler(request, extra));+ if (params.task) {+ const taskValidationResult = safeParse3(CreateTaskResultSchema, result);+ if (!taskValidationResult.success) {+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);+ }+ return taskValidationResult.data;+ }+ const validationResult = safeParse3(CallToolResultSchema, result);+ if (!validationResult.success) {+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);+ }+ return validationResult.data;+ };+ return super.setRequestHandler(requestSchema, wrappedHandler);+ }+ return super.setRequestHandler(requestSchema, handler);+ }+ assertCapabilityForMethod(method) {+ switch (method) {+ case "sampling/createMessage":+ if (!this._clientCapabilities?.sampling) {+ throw new Error(`Client does not support sampling (required for ${method})`);+ }+ break;+ case "elicitation/create":+ if (!this._clientCapabilities?.elicitation) {+ throw new Error(`Client does not support elicitation (required for ${method})`);+ }+ break;+ case "roots/list":+ if (!this._clientCapabilities?.roots) {+ throw new Error(`Client does not support listing roots (required for ${method})`);+ }+ break;+ case "ping":+ break;+ }+ }+ assertNotificationCapability(method) {+ switch (method) {+ case "notifications/message":+ if (!this._capabilities.logging) {+ throw new Error(`Server does not support logging (required for ${method})`);+ }+ break;+ case "notifications/resources/updated":+ case "notifications/resources/list_changed":+ if (!this._capabilities.resources) {+ throw new Error(`Server does not support notifying about resources (required for ${method})`);+ }+ break;+ case "notifications/tools/list_changed":+ if (!this._capabilities.tools) {+ throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);+ }+ break;+ case "notifications/prompts/list_changed":+ if (!this._capabilities.prompts) {+ throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);+ }+ break;+ case "notifications/elicitation/complete":+ if (!this._clientCapabilities?.elicitation?.url) {+ throw new Error(`Client does not support URL elicitation (required for ${method})`);+ }+ break;+ case "notifications/cancelled":+ break;+ case "notifications/progress":+ break;+ }+ }+ assertRequestHandlerCapability(method) {+ if (!this._capabilities) {+ return;+ }+ switch (method) {+ case "completion/complete":+ if (!this._capabilities.completions) {+ throw new Error(`Server does not support completions (required for ${method})`);+ }+ break;+ case "logging/setLevel":+ if (!this._capabilities.logging) {+ throw new Error(`Server does not support logging (required for ${method})`);+ }+ break;+ case "prompts/get":+ case "prompts/list":+ if (!this._capabilities.prompts) {+ throw new Error(`Server does not support prompts (required for ${method})`);+ }+ break;+ case "resources/list":+ case "resources/templates/list":+ case "resources/read":+ if (!this._capabilities.resources) {+ throw new Error(`Server does not support resources (required for ${method})`);+ }+ break;+ case "tools/call":+ case "tools/list":+ if (!this._capabilities.tools) {+ throw new Error(`Server does not support tools (required for ${method})`);+ }+ break;+ case "tasks/get":+ case "tasks/list":+ case "tasks/result":+ case "tasks/cancel":+ if (!this._capabilities.tasks) {+ throw new Error(`Server does not support tasks capability (required for ${method})`);+ }+ break;+ case "ping":+ case "initialize":+ break;+ }+ }+ assertTaskCapability(method) {+ assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");+ }+ assertTaskHandlerCapability(method) {+ if (!this._capabilities) {+ return;+ }+ assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");+ }+ async _oninitialize(request) {+ const requestedVersion = request.params.protocolVersion;+ this._clientCapabilities = request.params.capabilities;+ this._clientVersion = request.params.clientInfo;+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;+ return {+ protocolVersion,+ capabilities: this.getCapabilities(),+ serverInfo: this._serverInfo,+ ...this._instructions && { instructions: this._instructions }+ };+ }+ /**+ * After initialization has completed, this will be populated with the client's reported capabilities.+ */+ getClientCapabilities() {+ return this._clientCapabilities;+ }+ /**+ * After initialization has completed, this will be populated with information about the client's name and version.+ */+ getClientVersion() {+ return this._clientVersion;+ }+ getCapabilities() {+ return this._capabilities;+ }+ async ping() {+ return this.request({ method: "ping" }, EmptyResultSchema);+ }+ // Implementation+ async createMessage(params, options) {+ if (params.tools || params.toolChoice) {+ if (!this._clientCapabilities?.sampling?.tools) {+ throw new Error("Client does not support sampling tools capability.");+ }+ }+ if (params.messages.length > 0) {+ const lastMessage = params.messages[params.messages.length - 1];+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");+ if (hasToolResults) {+ if (lastContent.some((c) => c.type !== "tool_result")) {+ throw new Error("The last message must contain only tool_result content if any is present");+ }+ if (!hasPreviousToolUse) {+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");+ }+ }+ if (hasPreviousToolUse) {+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");+ }+ }+ }+ if (params.tools) {+ return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);+ }+ return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);+ }+ /**+ * Creates an elicitation request for the given parameters.+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.+ * @param params The parameters for the elicitation request.+ * @param options Optional request options.+ * @returns The result of the elicitation request.+ */+ async elicitInput(params, options) {+ const mode = params.mode ?? "form";+ switch (mode) {+ case "url": {+ if (!this._clientCapabilities?.elicitation?.url) {+ throw new Error("Client does not support url elicitation.");+ }+ const urlParams = params;+ return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);+ }+ case "form": {+ if (!this._clientCapabilities?.elicitation?.form) {+ throw new Error("Client does not support form elicitation.");+ }+ const formParams = params.mode === "form" ? params : { ...params, mode: "form" };+ const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);+ if (result.action === "accept" && result.content && formParams.requestedSchema) {+ try {+ const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);+ const validationResult = validator(result.content);+ if (!validationResult.valid) {+ throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);+ }+ } catch (error2) {+ if (error2 instanceof McpError) {+ throw error2;+ }+ throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`);+ }+ }+ return result;+ }+ }+ }+ /**+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`+ * notification for the specified elicitation ID.+ *+ * @param elicitationId The ID of the elicitation to mark as complete.+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.+ * @returns A function that emits the completion notification when awaited.+ */+ createElicitationCompletionNotifier(elicitationId, options) {+ if (!this._clientCapabilities?.elicitation?.url) {+ throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");+ }+ return () => this.notification({+ method: "notifications/elicitation/complete",+ params: {+ elicitationId+ }+ }, options);+ }+ async listRoots(params, options) {+ return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);+ }+ /**+ * Sends a logging message to the client, if connected.+ * Note: You only need to send the parameters object, not the entire JSON RPC message+ * @see LoggingMessageNotification+ * @param params+ * @param sessionId optional for stateless and backward compatibility+ */+ async sendLoggingMessage(params, sessionId) {+ if (this._capabilities.logging) {+ if (!this.isMessageIgnored(params.level, sessionId)) {+ return this.notification({ method: "notifications/message", params });+ }+ }+ }+ async sendResourceUpdated(params) {+ return this.notification({+ method: "notifications/resources/updated",+ params+ });+ }+ async sendResourceListChanged() {+ return this.notification({+ method: "notifications/resources/list_changed"+ });+ }+ async sendToolListChanged() {+ return this.notification({ method: "notifications/tools/list_changed" });+ }+ async sendPromptListChanged() {+ return this.notification({ method: "notifications/prompts/list_changed" });+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js+var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");+function isCompletable(schema) {+ return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;+}+function getCompleter(schema) {+ const meta = schema[COMPLETABLE_SYMBOL];+ return meta?.complete;+}+var McpZodTypeKind;+(function(McpZodTypeKind2) {+ McpZodTypeKind2["Completable"] = "McpCompletable";+})(McpZodTypeKind || (McpZodTypeKind = {}));++// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/uriTemplate.js+var MAX_TEMPLATE_LENGTH = 1e6;+var MAX_VARIABLE_LENGTH = 1e6;+var MAX_TEMPLATE_EXPRESSIONS = 1e4;+var MAX_REGEX_LENGTH = 1e6;+var UriTemplate = class _UriTemplate {+ /**+ * Returns true if the given string contains any URI template expressions.+ * A template expression is a sequence of characters enclosed in curly braces,+ * like {foo} or {?bar}.+ */+ static isTemplate(str) {+ return /\{[^}\s]+\}/.test(str);+ }+ static validateLength(str, max, context) {+ if (str.length > max) {+ throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);+ }+ }+ get variableNames() {+ return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names);+ }+ constructor(template) {+ _UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template");+ this.template = template;+ this.parts = this.parse(template);+ }+ toString() {+ return this.template;+ }+ parse(template) {+ const parts = [];+ let currentText = "";+ let i = 0;+ let expressionCount = 0;+ while (i < template.length) {+ if (template[i] === "{") {+ if (currentText) {+ parts.push(currentText);+ currentText = "";+ }+ const end = template.indexOf("}", i);+ if (end === -1)+ throw new Error("Unclosed template expression");+ expressionCount++;+ if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {+ throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);+ }+ const expr = template.slice(i + 1, end);+ const operator = this.getOperator(expr);+ const exploded = expr.includes("*");+ const names = this.getNames(expr);+ const name3 = names[0];+ for (const name4 of names) {+ _UriTemplate.validateLength(name4, MAX_VARIABLE_LENGTH, "Variable name");+ }+ parts.push({ name: name3, operator, names, exploded });+ i = end + 1;+ } else {+ currentText += template[i];+ i++;+ }+ }+ if (currentText) {+ parts.push(currentText);+ }+ return parts;+ }+ getOperator(expr) {+ const operators = ["+", "#", ".", "/", "?", "&"];+ return operators.find((op) => expr.startsWith(op)) || "";+ }+ getNames(expr) {+ const operator = this.getOperator(expr);+ return expr.slice(operator.length).split(",").map((name3) => name3.replace("*", "").trim()).filter((name3) => name3.length > 0);+ }+ encodeValue(value, operator) {+ _UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value");+ if (operator === "+" || operator === "#") {+ return encodeURI(value);+ }+ return encodeURIComponent(value);+ }+ expandPart(part, variables) {+ if (part.operator === "?" || part.operator === "&") {+ const pairs = part.names.map((name3) => {+ const value2 = variables[name3];+ if (value2 === void 0)+ return "";+ const encoded2 = Array.isArray(value2) ? value2.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value2.toString(), part.operator);+ return `${name3}=${encoded2}`;+ }).filter((pair) => pair.length > 0);+ if (pairs.length === 0)+ return "";+ const separator = part.operator === "?" ? "?" : "&";+ return separator + pairs.join("&");+ }+ if (part.names.length > 1) {+ const values2 = part.names.map((name3) => variables[name3]).filter((v) => v !== void 0);+ if (values2.length === 0)+ return "";+ return values2.map((v) => Array.isArray(v) ? v[0] : v).join(",");+ }+ const value = variables[part.name];+ if (value === void 0)+ return "";+ const values = Array.isArray(value) ? value : [value];+ const encoded = values.map((v) => this.encodeValue(v, part.operator));+ switch (part.operator) {+ case "":+ return encoded.join(",");+ case "+":+ return encoded.join(",");+ case "#":+ return "#" + encoded.join(",");+ case ".":+ return "." + encoded.join(".");+ case "/":+ return "/" + encoded.join("/");+ default:+ return encoded.join(",");+ }+ }+ expand(variables) {+ let result = "";+ let hasQueryParam = false;+ for (const part of this.parts) {+ if (typeof part === "string") {+ result += part;+ continue;+ }+ const expanded = this.expandPart(part, variables);+ if (!expanded)+ continue;+ if ((part.operator === "?" || part.operator === "&") && hasQueryParam) {+ result += expanded.replace("?", "&");+ } else {+ result += expanded;+ }+ if (part.operator === "?" || part.operator === "&") {+ hasQueryParam = true;+ }+ }+ return result;+ }+ escapeRegExp(str) {+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ }+ partToRegExp(part) {+ const patterns = [];+ for (const name4 of part.names) {+ _UriTemplate.validateLength(name4, MAX_VARIABLE_LENGTH, "Variable name");+ }+ if (part.operator === "?" || part.operator === "&") {+ for (let i = 0; i < part.names.length; i++) {+ const name4 = part.names[i];+ const prefix = i === 0 ? "\\" + part.operator : "&";+ patterns.push({+ pattern: prefix + this.escapeRegExp(name4) + "=([^&]+)",+ name: name4+ });+ }+ return patterns;+ }+ let pattern;+ const name3 = part.name;+ switch (part.operator) {+ case "":+ pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)";+ break;+ case "+":+ case "#":+ pattern = "(.+)";+ break;+ case ".":+ pattern = "\\.([^/,]+)";+ break;+ case "/":+ pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)");+ break;+ default:+ pattern = "([^/]+)";+ }+ patterns.push({ pattern, name: name3 });+ return patterns;+ }+ match(uri) {+ _UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI");+ let pattern = "^";+ const names = [];+ for (const part of this.parts) {+ if (typeof part === "string") {+ pattern += this.escapeRegExp(part);+ } else {+ const patterns = this.partToRegExp(part);+ for (const { pattern: partPattern, name: name3 } of patterns) {+ pattern += partPattern;+ names.push({ name: name3, exploded: part.exploded });+ }+ }+ }+ pattern += "$";+ _UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern");+ const regex = new RegExp(pattern);+ const match = uri.match(regex);+ if (!match)+ return null;+ const result = {};+ for (let i = 0; i < names.length; i++) {+ const { name: name3, exploded } = names[i];+ const value = match[i + 1];+ const cleanName = name3.replace("*", "");+ if (exploded && value.includes(",")) {+ result[cleanName] = value.split(",");+ } else {+ result[cleanName] = value;+ }+ }+ return result;+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js+var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;+function validateToolName(name3) {+ const warnings = [];+ if (name3.length === 0) {+ return {+ isValid: false,+ warnings: ["Tool name cannot be empty"]+ };+ }+ if (name3.length > 128) {+ return {+ isValid: false,+ warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name3.length})`]+ };+ }+ if (name3.includes(" ")) {+ warnings.push("Tool name contains spaces, which may cause parsing issues");+ }+ if (name3.includes(",")) {+ warnings.push("Tool name contains commas, which may cause parsing issues");+ }+ if (name3.startsWith("-") || name3.endsWith("-")) {+ warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");+ }+ if (name3.startsWith(".") || name3.endsWith(".")) {+ warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");+ }+ if (!TOOL_NAME_REGEX.test(name3)) {+ const invalidChars = name3.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);+ warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)");+ return {+ isValid: false,+ warnings+ };+ }+ return {+ isValid: true,+ warnings+ };+}+function issueToolNameWarning(name3, warnings) {+ if (warnings.length > 0) {+ console.warn(`Tool name validation warning for "${name3}":`);+ for (const warning of warnings) {+ console.warn(` - ${warning}`);+ }+ console.warn("Tool registration will proceed, but this may cause compatibility issues.");+ console.warn("Consider updating the tool name to conform to the MCP tool naming standard.");+ console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.");+ }+}+function validateAndWarnToolName(name3) {+ const result = validateToolName(name3);+ issueToolNameWarning(name3, result.warnings);+ return result.isValid;+}++// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js+var ExperimentalMcpServerTasks = class {+ constructor(_mcpServer) {+ this._mcpServer = _mcpServer;+ }+ registerToolTask(name3, config2, handler) {+ const execution = { taskSupport: "required", ...config2.execution };+ if (execution.taskSupport === "forbidden") {+ throw new Error(`Cannot register task-based tool '${name3}' with taskSupport 'forbidden'. Use registerTool() instead.`);+ }+ const mcpServerInternal = this._mcpServer;+ return mcpServerInternal._createRegisteredTool(name3, config2.title, config2.description, config2.inputSchema, config2.outputSchema, config2.annotations, execution, config2._meta, handler);+ }+};++// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js+var McpServer = class {+ constructor(serverInfo, options) {+ this._registeredResources = {};+ this._registeredResourceTemplates = {};+ this._registeredTools = {};+ this._registeredPrompts = {};+ this._toolHandlersInitialized = false;+ this._completionHandlerInitialized = false;+ this._resourceHandlersInitialized = false;+ this._promptHandlersInitialized = false;+ this.server = new Server(serverInfo, options);+ }+ /**+ * Access experimental features.+ *+ * WARNING: These APIs are experimental and may change without notice.+ *+ * @experimental+ */+ get experimental() {+ if (!this._experimental) {+ this._experimental = {+ tasks: new ExperimentalMcpServerTasks(this)+ };+ }+ return this._experimental;+ }+ /**+ * Attaches to the given transport, starts it, and starts listening for messages.+ *+ * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.+ */+ async connect(transport2) {+ return await this.server.connect(transport2);+ }+ /**+ * Closes the connection.+ */+ async close() {+ await this.server.close();+ }+ setToolRequestHandlers() {+ if (this._toolHandlersInitialized) {+ return;+ }+ this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));+ this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));+ this.server.registerCapabilities({+ tools: {+ listChanged: true+ }+ });+ this.server.setRequestHandler(ListToolsRequestSchema, () => ({+ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name3, tool]) => {+ const toolDefinition = {+ name: name3,+ title: tool.title,+ description: tool.description,+ inputSchema: (() => {+ const obj = normalizeObjectSchema(tool.inputSchema);+ return obj ? toJsonSchemaCompat(obj, {+ strictUnions: true,+ pipeStrategy: "input"+ }) : EMPTY_OBJECT_JSON_SCHEMA;+ })(),+ annotations: tool.annotations,+ execution: tool.execution,+ _meta: tool._meta+ };+ if (tool.outputSchema) {+ const obj = normalizeObjectSchema(tool.outputSchema);+ if (obj) {+ toolDefinition.outputSchema = toJsonSchemaCompat(obj, {+ strictUnions: true,+ pipeStrategy: "output"+ });+ }+ }+ return toolDefinition;+ })+ }));+ this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {+ try {+ const tool = this._registeredTools[request.params.name];+ if (!tool) {+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);+ }+ if (!tool.enabled) {+ throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);+ }+ const isTaskRequest = !!request.params.task;+ const taskSupport = tool.execution?.taskSupport;+ const isTaskHandler = "createTask" in tool.handler;+ if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) {+ throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);+ }+ if (taskSupport === "required" && !isTaskRequest) {+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);+ }+ if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) {+ return await this.handleAutomaticTaskPolling(tool, request, extra);+ }+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);+ const result = await this.executeToolHandler(tool, args, extra);+ if (isTaskRequest) {+ return result;+ }+ await this.validateToolOutput(tool, result, request.params.name);+ return result;+ } catch (error2) {+ if (error2 instanceof McpError) {+ if (error2.code === ErrorCode.UrlElicitationRequired) {+ throw error2;+ }+ }+ return this.createToolError(error2 instanceof Error ? error2.message : String(error2));+ }+ });+ this._toolHandlersInitialized = true;+ }+ /**+ * Creates a tool error result.+ *+ * @param errorMessage - The error message.+ * @returns The tool error result.+ */+ createToolError(errorMessage) {+ return {+ content: [+ {+ type: "text",+ text: errorMessage+ }+ ],+ isError: true+ };+ }+ /**+ * Validates tool input arguments against the tool's input schema.+ */+ async validateToolInput(tool, args, toolName) {+ if (!tool.inputSchema) {+ return void 0;+ }+ const inputObj = normalizeObjectSchema(tool.inputSchema);+ const schemaToParse = inputObj ?? tool.inputSchema;+ const parseResult = await safeParseAsync3(schemaToParse, args);+ if (!parseResult.success) {+ const error2 = "error" in parseResult ? parseResult.error : "Unknown error";+ const errorMessage = getParseErrorMessage(error2);+ throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);+ }+ return parseResult.data;+ }+ /**+ * Validates tool output against the tool's output schema.+ */+ async validateToolOutput(tool, result, toolName) {+ if (!tool.outputSchema) {+ return;+ }+ if (!("content" in result)) {+ return;+ }+ if (result.isError) {+ return;+ }+ if (!result.structuredContent) {+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);+ }+ const outputObj = normalizeObjectSchema(tool.outputSchema);+ const parseResult = await safeParseAsync3(outputObj, result.structuredContent);+ if (!parseResult.success) {+ const error2 = "error" in parseResult ? parseResult.error : "Unknown error";+ const errorMessage = getParseErrorMessage(error2);+ throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);+ }+ }+ /**+ * Executes a tool handler (either regular or task-based).+ */+ async executeToolHandler(tool, args, extra) {+ const handler = tool.handler;+ const isTaskHandler = "createTask" in handler;+ if (isTaskHandler) {+ if (!extra.taskStore) {+ throw new Error("No task store provided.");+ }+ const taskExtra = { ...extra, taskStore: extra.taskStore };+ if (tool.inputSchema) {+ const typedHandler = handler;+ return await Promise.resolve(typedHandler.createTask(args, taskExtra));+ } else {+ const typedHandler = handler;+ return await Promise.resolve(typedHandler.createTask(taskExtra));+ }+ }+ if (tool.inputSchema) {+ const typedHandler = handler;+ return await Promise.resolve(typedHandler(args, extra));+ } else {+ const typedHandler = handler;+ return await Promise.resolve(typedHandler(extra));+ }+ }+ /**+ * Handles automatic task polling for tools with taskSupport 'optional'.+ */+ async handleAutomaticTaskPolling(tool, request, extra) {+ if (!extra.taskStore) {+ throw new Error("No task store provided for task-capable tool.");+ }+ const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);+ const handler = tool.handler;+ const taskExtra = { ...extra, taskStore: extra.taskStore };+ const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : (+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ await Promise.resolve(handler.createTask(taskExtra))+ );+ const taskId = createTaskResult.task.taskId;+ let task = createTaskResult.task;+ const pollInterval = task.pollInterval ?? 5e3;+ while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {+ await new Promise((resolve2) => setTimeout(resolve2, pollInterval));+ const updatedTask = await extra.taskStore.getTask(taskId);+ if (!updatedTask) {+ throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);+ }+ task = updatedTask;+ }+ return await extra.taskStore.getTaskResult(taskId);+ }+ setCompletionRequestHandler() {+ if (this._completionHandlerInitialized) {+ return;+ }+ this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));+ this.server.registerCapabilities({+ completions: {}+ });+ this.server.setRequestHandler(CompleteRequestSchema, async (request) => {+ switch (request.params.ref.type) {+ case "ref/prompt":+ assertCompleteRequestPrompt(request);+ return this.handlePromptCompletion(request, request.params.ref);+ case "ref/resource":+ assertCompleteRequestResourceTemplate(request);+ return this.handleResourceCompletion(request, request.params.ref);+ default:+ throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);+ }+ });+ this._completionHandlerInitialized = true;+ }+ async handlePromptCompletion(request, ref) {+ const prompt = this._registeredPrompts[ref.name];+ if (!prompt) {+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);+ }+ if (!prompt.enabled) {+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);+ }+ if (!prompt.argsSchema) {+ return EMPTY_COMPLETION_RESULT;+ }+ const promptShape = getObjectShape(prompt.argsSchema);+ const field = promptShape?.[request.params.argument.name];+ if (!isCompletable(field)) {+ return EMPTY_COMPLETION_RESULT;+ }+ const completer = getCompleter(field);+ if (!completer) {+ return EMPTY_COMPLETION_RESULT;+ }+ const suggestions = await completer(request.params.argument.value, request.params.context);+ return createCompletionResult(suggestions);+ }+ async handleResourceCompletion(request, ref) {+ const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri);+ if (!template) {+ if (this._registeredResources[ref.uri]) {+ return EMPTY_COMPLETION_RESULT;+ }+ throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);+ }+ const completer = template.resourceTemplate.completeCallback(request.params.argument.name);+ if (!completer) {+ return EMPTY_COMPLETION_RESULT;+ }+ const suggestions = await completer(request.params.argument.value, request.params.context);+ return createCompletionResult(suggestions);+ }+ setResourceRequestHandlers() {+ if (this._resourceHandlersInitialized) {+ return;+ }+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));+ this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));+ this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));+ this.server.registerCapabilities({+ resources: {+ listChanged: true+ }+ });+ this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {+ const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({+ uri,+ name: resource.name,+ ...resource.metadata+ }));+ const templateResources = [];+ for (const template of Object.values(this._registeredResourceTemplates)) {+ if (!template.resourceTemplate.listCallback) {+ continue;+ }+ const result = await template.resourceTemplate.listCallback(extra);+ for (const resource of result.resources) {+ templateResources.push({+ ...template.metadata,+ // the defined resource metadata should override the template metadata if present+ ...resource+ });+ }+ }+ return { resources: [...resources, ...templateResources] };+ });+ this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {+ const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name3, template]) => ({+ name: name3,+ uriTemplate: template.resourceTemplate.uriTemplate.toString(),+ ...template.metadata+ }));+ return { resourceTemplates };+ });+ this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {+ const uri = new URL(request.params.uri);+ const resource = this._registeredResources[uri.toString()];+ if (resource) {+ if (!resource.enabled) {+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);+ }+ return resource.readCallback(uri, extra);+ }+ for (const template of Object.values(this._registeredResourceTemplates)) {+ const variables = template.resourceTemplate.uriTemplate.match(uri.toString());+ if (variables) {+ return template.readCallback(uri, variables, extra);+ }+ }+ throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);+ });+ this._resourceHandlersInitialized = true;+ }+ setPromptRequestHandlers() {+ if (this._promptHandlersInitialized) {+ return;+ }+ this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));+ this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));+ this.server.registerCapabilities({+ prompts: {+ listChanged: true+ }+ });+ this.server.setRequestHandler(ListPromptsRequestSchema, () => ({+ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name3, prompt]) => {+ return {+ name: name3,+ title: prompt.title,+ description: prompt.description,+ arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0+ };+ })+ }));+ this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {+ const prompt = this._registeredPrompts[request.params.name];+ if (!prompt) {+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);+ }+ if (!prompt.enabled) {+ throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);+ }+ if (prompt.argsSchema) {+ const argsObj = normalizeObjectSchema(prompt.argsSchema);+ const parseResult = await safeParseAsync3(argsObj, request.params.arguments);+ if (!parseResult.success) {+ const error2 = "error" in parseResult ? parseResult.error : "Unknown error";+ const errorMessage = getParseErrorMessage(error2);+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);+ }+ const args = parseResult.data;+ const cb = prompt.callback;+ return await Promise.resolve(cb(args, extra));+ } else {+ const cb = prompt.callback;+ return await Promise.resolve(cb(extra));+ }+ });+ this._promptHandlersInitialized = true;+ }+ resource(name3, uriOrTemplate, ...rest) {+ let metadata;+ if (typeof rest[0] === "object") {+ metadata = rest.shift();+ }+ const readCallback = rest[0];+ if (typeof uriOrTemplate === "string") {+ if (this._registeredResources[uriOrTemplate]) {+ throw new Error(`Resource ${uriOrTemplate} is already registered`);+ }+ const registeredResource = this._createRegisteredResource(name3, void 0, uriOrTemplate, metadata, readCallback);+ this.setResourceRequestHandlers();+ this.sendResourceListChanged();+ return registeredResource;+ } else {+ if (this._registeredResourceTemplates[name3]) {+ throw new Error(`Resource template ${name3} is already registered`);+ }+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name3, void 0, uriOrTemplate, metadata, readCallback);+ this.setResourceRequestHandlers();+ this.sendResourceListChanged();+ return registeredResourceTemplate;+ }+ }+ registerResource(name3, uriOrTemplate, config2, readCallback) {+ if (typeof uriOrTemplate === "string") {+ if (this._registeredResources[uriOrTemplate]) {+ throw new Error(`Resource ${uriOrTemplate} is already registered`);+ }+ const registeredResource = this._createRegisteredResource(name3, config2.title, uriOrTemplate, config2, readCallback);+ this.setResourceRequestHandlers();+ this.sendResourceListChanged();+ return registeredResource;+ } else {+ if (this._registeredResourceTemplates[name3]) {+ throw new Error(`Resource template ${name3} is already registered`);+ }+ const registeredResourceTemplate = this._createRegisteredResourceTemplate(name3, config2.title, uriOrTemplate, config2, readCallback);+ this.setResourceRequestHandlers();+ this.sendResourceListChanged();+ return registeredResourceTemplate;+ }+ }+ _createRegisteredResource(name3, title, uri, metadata, readCallback) {+ const registeredResource = {+ name: name3,+ title,+ metadata,+ readCallback,+ enabled: true,+ disable: () => registeredResource.update({ enabled: false }),+ enable: () => registeredResource.update({ enabled: true }),+ remove: () => registeredResource.update({ uri: null }),+ update: (updates) => {+ if (typeof updates.uri !== "undefined" && updates.uri !== uri) {+ delete this._registeredResources[uri];+ if (updates.uri)+ this._registeredResources[updates.uri] = registeredResource;+ }+ if (typeof updates.name !== "undefined")+ registeredResource.name = updates.name;+ if (typeof updates.title !== "undefined")+ registeredResource.title = updates.title;+ if (typeof updates.metadata !== "undefined")+ registeredResource.metadata = updates.metadata;+ if (typeof updates.callback !== "undefined")+ registeredResource.readCallback = updates.callback;+ if (typeof updates.enabled !== "undefined")+ registeredResource.enabled = updates.enabled;+ this.sendResourceListChanged();+ }+ };+ this._registeredResources[uri] = registeredResource;+ return registeredResource;+ }+ _createRegisteredResourceTemplate(name3, title, template, metadata, readCallback) {+ const registeredResourceTemplate = {+ resourceTemplate: template,+ title,+ metadata,+ readCallback,+ enabled: true,+ disable: () => registeredResourceTemplate.update({ enabled: false }),+ enable: () => registeredResourceTemplate.update({ enabled: true }),+ remove: () => registeredResourceTemplate.update({ name: null }),+ update: (updates) => {+ if (typeof updates.name !== "undefined" && updates.name !== name3) {+ delete this._registeredResourceTemplates[name3];+ if (updates.name)+ this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;+ }+ if (typeof updates.title !== "undefined")+ registeredResourceTemplate.title = updates.title;+ if (typeof updates.template !== "undefined")+ registeredResourceTemplate.resourceTemplate = updates.template;+ if (typeof updates.metadata !== "undefined")+ registeredResourceTemplate.metadata = updates.metadata;+ if (typeof updates.callback !== "undefined")+ registeredResourceTemplate.readCallback = updates.callback;+ if (typeof updates.enabled !== "undefined")+ registeredResourceTemplate.enabled = updates.enabled;+ this.sendResourceListChanged();+ }+ };+ this._registeredResourceTemplates[name3] = registeredResourceTemplate;+ const variableNames = template.uriTemplate.variableNames;+ const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));+ if (hasCompleter) {+ this.setCompletionRequestHandler();+ }+ return registeredResourceTemplate;+ }+ _createRegisteredPrompt(name3, title, description, argsSchema, callback) {+ const registeredPrompt = {+ title,+ description,+ argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema),+ callback,+ enabled: true,+ disable: () => registeredPrompt.update({ enabled: false }),+ enable: () => registeredPrompt.update({ enabled: true }),+ remove: () => registeredPrompt.update({ name: null }),+ update: (updates) => {+ if (typeof updates.name !== "undefined" && updates.name !== name3) {+ delete this._registeredPrompts[name3];+ if (updates.name)+ this._registeredPrompts[updates.name] = registeredPrompt;+ }+ if (typeof updates.title !== "undefined")+ registeredPrompt.title = updates.title;+ if (typeof updates.description !== "undefined")+ registeredPrompt.description = updates.description;+ if (typeof updates.argsSchema !== "undefined")+ registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);+ if (typeof updates.callback !== "undefined")+ registeredPrompt.callback = updates.callback;+ if (typeof updates.enabled !== "undefined")+ registeredPrompt.enabled = updates.enabled;+ this.sendPromptListChanged();+ }+ };+ this._registeredPrompts[name3] = registeredPrompt;+ if (argsSchema) {+ const hasCompletable = Object.values(argsSchema).some((field) => {+ const inner = field instanceof ZodOptional2 ? field._def?.innerType : field;+ return isCompletable(inner);+ });+ if (hasCompletable) {+ this.setCompletionRequestHandler();+ }+ }+ return registeredPrompt;+ }+ _createRegisteredTool(name3, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {+ validateAndWarnToolName(name3);+ const registeredTool = {+ title,+ description,+ inputSchema: getZodSchemaObject(inputSchema),+ outputSchema: getZodSchemaObject(outputSchema),+ annotations,+ execution,+ _meta,+ handler,+ enabled: true,+ disable: () => registeredTool.update({ enabled: false }),+ enable: () => registeredTool.update({ enabled: true }),+ remove: () => registeredTool.update({ name: null }),+ update: (updates) => {+ if (typeof updates.name !== "undefined" && updates.name !== name3) {+ if (typeof updates.name === "string") {+ validateAndWarnToolName(updates.name);+ }+ delete this._registeredTools[name3];+ if (updates.name)+ this._registeredTools[updates.name] = registeredTool;+ }+ if (typeof updates.title !== "undefined")+ registeredTool.title = updates.title;+ if (typeof updates.description !== "undefined")+ registeredTool.description = updates.description;+ if (typeof updates.paramsSchema !== "undefined")+ registeredTool.inputSchema = objectFromShape(updates.paramsSchema);+ if (typeof updates.outputSchema !== "undefined")+ registeredTool.outputSchema = objectFromShape(updates.outputSchema);+ if (typeof updates.callback !== "undefined")+ registeredTool.handler = updates.callback;+ if (typeof updates.annotations !== "undefined")+ registeredTool.annotations = updates.annotations;+ if (typeof updates._meta !== "undefined")+ registeredTool._meta = updates._meta;+ if (typeof updates.enabled !== "undefined")+ registeredTool.enabled = updates.enabled;+ this.sendToolListChanged();+ }+ };+ this._registeredTools[name3] = registeredTool;+ this.setToolRequestHandlers();+ this.sendToolListChanged();+ return registeredTool;+ }+ /**+ * tool() implementation. Parses arguments passed to overrides defined above.+ */+ tool(name3, ...rest) {+ if (this._registeredTools[name3]) {+ throw new Error(`Tool ${name3} is already registered`);+ }+ let description;+ let inputSchema;+ let outputSchema;+ let annotations;+ if (typeof rest[0] === "string") {+ description = rest.shift();+ }+ if (rest.length > 1) {+ const firstArg = rest[0];+ if (isZodRawShapeCompat(firstArg)) {+ inputSchema = rest.shift();+ if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {+ annotations = rest.shift();+ }+ } else if (typeof firstArg === "object" && firstArg !== null) {+ if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) {+ throw new Error(`Tool ${name3} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);+ }+ annotations = rest.shift();+ }+ }+ const callback = rest[0];+ return this._createRegisteredTool(name3, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback);+ }+ /**+ * Registers a tool with a config object and callback.+ */+ registerTool(name3, config2, cb) {+ if (this._registeredTools[name3]) {+ throw new Error(`Tool ${name3} is already registered`);+ }+ const { title, description, inputSchema, outputSchema, annotations, _meta } = config2;+ return this._createRegisteredTool(name3, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);+ }+ prompt(name3, ...rest) {+ if (this._registeredPrompts[name3]) {+ throw new Error(`Prompt ${name3} is already registered`);+ }+ let description;+ if (typeof rest[0] === "string") {+ description = rest.shift();+ }+ let argsSchema;+ if (rest.length > 1) {+ argsSchema = rest.shift();+ }+ const cb = rest[0];+ const registeredPrompt = this._createRegisteredPrompt(name3, void 0, description, argsSchema, cb);+ this.setPromptRequestHandlers();+ this.sendPromptListChanged();+ return registeredPrompt;+ }+ /**+ * Registers a prompt with a config object and callback.+ */+ registerPrompt(name3, config2, cb) {+ if (this._registeredPrompts[name3]) {+ throw new Error(`Prompt ${name3} is already registered`);+ }+ const { title, description, argsSchema } = config2;+ const registeredPrompt = this._createRegisteredPrompt(name3, title, description, argsSchema, cb);+ this.setPromptRequestHandlers();+ this.sendPromptListChanged();+ return registeredPrompt;+ }+ /**+ * Checks if the server is connected to a transport.+ * @returns True if the server is connected+ */+ isConnected() {+ return this.server.transport !== void 0;+ }+ /**+ * Sends a logging message to the client, if connected.+ * Note: You only need to send the parameters object, not the entire JSON RPC message+ * @see LoggingMessageNotification+ * @param params+ * @param sessionId optional for stateless and backward compatibility+ */+ async sendLoggingMessage(params, sessionId) {+ return this.server.sendLoggingMessage(params, sessionId);+ }+ /**+ * Sends a resource list changed event to the client, if connected.+ */+ sendResourceListChanged() {+ if (this.isConnected()) {+ this.server.sendResourceListChanged();+ }+ }+ /**+ * Sends a tool list changed event to the client, if connected.+ */+ sendToolListChanged() {+ if (this.isConnected()) {+ this.server.sendToolListChanged();+ }+ }+ /**+ * Sends a prompt list changed event to the client, if connected.+ */+ sendPromptListChanged() {+ if (this.isConnected()) {+ this.server.sendPromptListChanged();+ }+ }+};+var ResourceTemplate = class {+ constructor(uriTemplate, _callbacks) {+ this._callbacks = _callbacks;+ this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate;+ }+ /**+ * Gets the URI template pattern.+ */+ get uriTemplate() {+ return this._uriTemplate;+ }+ /**+ * Gets the list callback, if one was provided.+ */+ get listCallback() {+ return this._callbacks.list;+ }+ /**+ * Gets the callback for completing a specific URI template variable, if one was provided.+ */+ completeCallback(variable) {+ return this._callbacks.complete?.[variable];+ }+};+var EMPTY_OBJECT_JSON_SCHEMA = {+ type: "object",+ properties: {}+};+function isZodTypeLike(value) {+ return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";+}+function isZodSchemaInstance(obj) {+ return "_def" in obj || "_zod" in obj || isZodTypeLike(obj);+}+function isZodRawShapeCompat(obj) {+ if (typeof obj !== "object" || obj === null) {+ return false;+ }+ if (isZodSchemaInstance(obj)) {+ return false;+ }+ if (Object.keys(obj).length === 0) {+ return true;+ }+ return Object.values(obj).some(isZodTypeLike);+}+function getZodSchemaObject(schema) {+ if (!schema) {+ return void 0;+ }+ if (isZodRawShapeCompat(schema)) {+ return objectFromShape(schema);+ }+ if (!isZodSchemaInstance(schema)) {+ throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");+ }+ return schema;+}+function promptArgumentsFromSchema(schema) {+ const shape = getObjectShape(schema);+ if (!shape)+ return [];+ return Object.entries(shape).map(([name3, field]) => {+ const description = getSchemaDescription(field);+ const isOptional = isSchemaOptional(field);+ return {+ name: name3,+ description,+ required: !isOptional+ };+ });+}+function getMethodValue(schema) {+ const shape = getObjectShape(schema);+ const methodSchema = shape?.method;+ if (!methodSchema) {+ throw new Error("Schema is missing a method literal");+ }+ const value = getLiteralValue(methodSchema);+ if (typeof value === "string") {+ return value;+ }+ throw new Error("Schema method literal must be a string");+}+function createCompletionResult(suggestions) {+ return {+ completion: {+ values: suggestions.slice(0, 100),+ total: suggestions.length,+ hasMore: suggestions.length > 100+ }+ };+}+var EMPTY_COMPLETION_RESULT = {+ completion: {+ values: [],+ hasMore: false+ }+};++// packages/core/dist/mcp/server.js+init_flow_definition();++// packages/core/dist/mcp/response.js+var MAX_RESPONSE_CHARS = 5e4;+var TRUNCATION_NOTICE = "\n\n[Response truncated. Use more specific filters or get individual items for full details.]";+function safeResult(data) {+ let text;+ try {+ if (data == null) {+ text = JSON.stringify({ ok: true });+ } else {+ text = JSON.stringify(data, null, 2);+ }+ } catch {+ text = JSON.stringify({ error: "Failed to serialize response" });+ }+ if (text.length > MAX_RESPONSE_CHARS) {+ text = text.slice(0, MAX_RESPONSE_CHARS - TRUNCATION_NOTICE.length) + TRUNCATION_NOTICE;+ }+ return { content: [{ type: "text", text }] };+}+function safeError(err, enhance) {+ let payload;+ if (err && typeof err === "object" && "code" in err && typeof err.code === "string") {+ const e = err;+ payload = {+ code: e.code,+ message: e.message ?? String(err),+ remediation: e.remediation,+ operation: e.operation,+ flowId: e.flowId,+ solutionUniqueName: e.solutionUniqueName,+ solutionFriendlyName: e.solutionFriendlyName+ };+ } else {+ let message;+ if (enhance) {+ try {+ message = enhance(err);+ } catch {+ message = err instanceof Error ? err.message : String(err);+ }+ } else {+ message = err instanceof Error ? err.message : String(err);+ }+ payload = {+ code: "tool-error",+ message,+ ...err instanceof Error && err.name && err.name !== "Error" ? { errorName: err.name } : {}+ };+ }+ let text;+ try {+ text = JSON.stringify(payload, null, 2);+ } catch {+ text = JSON.stringify({ code: "tool-error", message: "Failed to serialize error" });+ }+ return { content: [{ type: "text", text }], isError: true };+}+function summarizeList(items, fields, rename) {+ return items.map((item) => {+ const summary = {};+ for (const field of fields) {+ const key = rename?.[field] ?? field.split(".").pop();+ const value = getNestedValue(item, field);+ if (value !== void 0) {+ summary[key] = value;+ }+ }+ return summary;+ });+}+function getNestedValue(obj, path3) {+ let current = obj;+ for (const segment of path3.split(".")) {+ if (current == null)+ return void 0;+ current = current[segment];+ }+ return current;+}++// packages/core/dist/mcp/progress.js+function progress(extra) {+ const token = extra?._meta?.progressToken;+ const sendNotification = extra?.sendNotification;+ if (token === void 0 || token === null || !sendNotification) {+ return {+ send: async () => {+ },+ enabled: false,+ signal: extra?.signal+ };+ }+ return {+ enabled: true,+ signal: extra?.signal,+ send: async (current, total, message) => {+ try {+ await sendNotification({+ method: "notifications/progress",+ params: {+ progressToken: token,+ progress: current,+ total,+ message+ }+ });+ } catch {+ }+ }+ };+}++// packages/core/dist/mcp/server.js+init_backups();+function buildToolContext(mcpCtx, config2, clientFactory) {+ let client = null;+ function getClient() {+ if (!client)+ client = clientFactory(mcpCtx.auth, config2);+ return client;+ }+ function resolveEnv(env) {+ const fromStore = mcpCtx.currentEnv.get().envId ?? void 0;+ const r = env || fromStore || config2.defaultEnvironmentId;+ if (!r)+ throw new Error("No environment specified and no default set. Call list_environments first, set one with set_current_env, or set PA_DEFAULT_ENVIRONMENT.");+ return r;+ }+ function rememberEnv(env) {+ if (mcpCtx.currentEnv.get().envId !== env)+ mcpCtx.currentEnv.set(env, { source: "auto-remember" });+ }+ function resolveFlow(flow) {+ const fromStore = mcpCtx.currentFlow.get().flowId ?? void 0;+ const r = flow || fromStore;+ if (!r)+ throw new Error("No flow specified and no current flow pinned. Pass flow, or pin one with set_current_flow.");+ return r;+ }+ function rememberFlow(flow, opts) {+ if (mcpCtx.currentFlow.get().flowId !== flow)+ mcpCtx.currentFlow.set(flow, { ...opts, source: "auto-remember" });+ }+ return { getClient, resolveEnv, rememberEnv, resolveFlow, rememberFlow };+}+function enhanceFlowApiError(err) {+ const msg = err?.message ?? String(err);+ const detail = err?.detail ?? "";+ const combined = `${msg} ${detail}`;+ const hints = [];+ if (combined.includes("WorkflowOperationParametersExtraParameter")) {+ hints.push("A parameter name is wrong. Call get_operation_details to see available parameter names.");+ }+ if (combined.includes("InvalidOpenApiConnectionOperationType")) {+ hints.push('This operation requires "OpenApiConnectionWebhook" type, not "OpenApiConnection".');+ }+ if (combined.includes("OpenApiOperationParameterValidationFailed")) {+ const m = detail.match(/enum values '\[([^\]]+)\]'/);+ if (m)+ hints.push(`Allowed values: ${m[1]}.`);+ }+ if (combined.includes("WorkflowOperationParametersRuntimeMissingValue")) {+ hints.push("A required parameter resolved to empty. Add: @if(empty(...), 'default', ...)");+ }+ if (combined.includes("InvalidApprovalType")) {+ hints.push('Valid approval types: Basic, BasicAwaitAll, CustomResponse, CustomResponseAwaitAll, Sequential. "BasicApproveReject" is NOT valid.');+ }+ if (combined.includes("is no longer present in the operation schema")) {+ hints.push("For StartAndWaitForAnApproval, body params must use 'WebhookApprovalCreationInput/' prefix (e.g. WebhookApprovalCreationInput/title). NOT 'ApprovalCreationInput/' (deprecated op) or bare names.");+ }+ return hints.length ? `${msg}++Fix: ${hints.join("\n")}` : msg;+}+function inferActionType(opProps) {+ if (!opProps)+ return "OpenApiConnection";+ const ann = opProps.annotation ?? opProps.properties?.annotation;+ if (ann?.family === "OpenApiConnectionWebhook")+ return "OpenApiConnectionWebhook";+ if (ann?.family === "OpenApiConnectionNotification")+ return "OpenApiConnectionNotification";+ const opId = opProps.operationId ?? opProps.name ?? "";+ if (/^(StartAndWait|WaitFor|Subscribe)/i.test(opId))+ return "OpenApiConnectionWebhook";+ return "OpenApiConnection";+}+async function createMcpServer(authProvider, deps = {}) {+ const config2 = deps.config ?? loadConfig();+ const clientFactory = deps.clientFactory ?? ((auth2, cfg) => new FlowClient(auth2, cfg));+ const sessionScope = new AsyncLocalStorage();+ const toolContexts = /* @__PURE__ */ new WeakMap();+ const legacyContext = {+ sessionId: "legacy-stdio",+ auth: authProvider,+ currentEnv: legacyCurrentEnvStore,+ currentFlow: legacyCurrentFlowStore,+ createdAt: /* @__PURE__ */ new Date(),+ lastActivityAt: /* @__PURE__ */ new Date()+ };+ function getActiveMcpContext(sessionId = sessionScope.getStore()) {+ if (deps.getContext) {+ const resolved = deps.getContext(sessionId);+ if (!resolved)+ throw new Error(`No MCP context found for session ${sessionId ?? "(none)"}`);+ resolved.lastActivityAt = /* @__PURE__ */ new Date();+ return resolved;+ }+ legacyContext.lastActivityAt = /* @__PURE__ */ new Date();+ return legacyContext;+ }+ function getActiveToolContext() {+ const mcpCtx = getActiveMcpContext();+ let toolCtx = toolContexts.get(mcpCtx);+ if (!toolCtx) {+ toolCtx = buildToolContext(mcpCtx, config2, clientFactory);+ toolContexts.set(mcpCtx, toolCtx);+ }+ return toolCtx;+ }+ const ctx = {+ getClient: () => getActiveToolContext().getClient(),+ resolveEnv: (env) => getActiveToolContext().resolveEnv(env),+ rememberEnv: (env) => getActiveToolContext().rememberEnv(env),+ resolveFlow: (flow) => getActiveToolContext().resolveFlow(flow),+ rememberFlow: (flow, opts) => getActiveToolContext().rememberFlow(flow, opts)+ };+ const server2 = new McpServer({+ name: deps.serverInfo?.name ?? "flowagent-mcp",+ version: deps.serverInfo?.version ?? "2.0.0"+ });+ if (deps.getContext || deps.onToolStart || deps.onToolEnd) {+ const origTool = server2.tool.bind(server2);+ server2.tool = (...regArgs) => {+ const handlerIdx = regArgs.findIndex((a) => typeof a === "function");+ if (handlerIdx < 0)+ return origTool(...regArgs);+ const handler = regArgs[handlerIdx];+ const toolName = regArgs[0];+ const wrappedHandler = async (...handlerArgs) => {+ const extra = handlerArgs[1];+ return sessionScope.run(extra?.sessionId, async () => {+ const correlationId = Math.random().toString(36).slice(2, 10);+ const args = handlerArgs[0] ?? {};+ const t0 = Date.now();+ try {+ getActiveMcpContext(extra?.sessionId);+ deps.onToolStart?.({ tool: toolName, args, correlationId });+ } catch {+ }+ try {+ const result = await handler(...handlerArgs);+ const isError = result?.isError === true;+ let errorCode;+ if (isError) {+ try {+ const text = result.content?.[0]?.text;+ if (typeof text === "string") {+ const parsed = JSON.parse(text);+ errorCode = parsed?.code;+ }+ } catch {+ }+ }+ try {+ deps.onToolEnd?.({+ tool: toolName,+ args,+ correlationId,+ durationMs: Date.now() - t0,+ isError,+ errorCode,+ result+ });+ } catch {+ }+ return result;+ } catch (err) {+ try {+ deps.onToolEnd?.({+ tool: toolName,+ args,+ correlationId,+ durationMs: Date.now() - t0,+ isError: true,+ errorCode: err?.code+ });+ } catch {+ }+ throw err;+ }+ });+ };+ const newArgs = [...regArgs];+ newArgs[handlerIdx] = wrappedHandler;+ return origTool(...newArgs);+ };+ }+ server2.tool("list_environments", "List all Power Automate environments. Use query to filter by name.", { query: external_exports.string().optional().describe("Filter by display name (case-insensitive)") }, { readOnlyHint: true, title: "List Environments" }, async ({ query }) => {+ try {+ const envs = await ctx.getClient().listEnvironments();+ let s = summarizeList(envs, ["name", "properties.displayName", "properties.isDefault", "properties.environmentSku", "location"], { "properties.displayName": "displayName", "properties.isDefault": "isDefault", "properties.environmentSku": "environmentSku" });+ if (query) {+ const q = query.toLowerCase();+ s = s.filter((e) => e.displayName?.toLowerCase().includes(q) || e.name?.includes(q));+ }+ return safeResult(s);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("resolve_environment", "Check which environment the current user resolves to via environment routing", { env: external_exports.string().optional().describe("Environment ID or omit for default") }, { readOnlyHint: true, title: "Resolve Environment" }, async ({ env }) => {+ try {+ return safeResult(await ctx.getClient().resolveEnvironment(env ? void 0 : void 0));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_current_env", "Show the current working environment that env-less tool calls (and the dashboard) target. Source is one of: env-var, set_tool, auto-remember, dashboard, none.", {}, { readOnlyHint: true, title: "Get Current Environment" }, async () => {+ try {+ const cur = getActiveMcpContext().currentEnv.get();+ if (!cur.envId)+ return safeResult({ envId: null, source: cur.source, message: "No current env set. Call list_environments and set_current_env, or set PA_DEFAULT_ENVIRONMENT." });+ let displayName = cur.displayName;+ if (!displayName) {+ try {+ const envs = await ctx.getClient().listEnvironments();+ displayName = envs.find((e) => e.name === cur.envId)?.properties?.displayName ?? null;+ } catch {+ }+ }+ return safeResult({ envId: cur.envId, displayName, updatedAt: cur.updatedAt, source: cur.source });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("set_current_env", "Set the current working environment that env-less tool calls (and the dashboard) target. Pass an env GUID OR a display-name substring; the latter is resolved against list_environments. Validates the env exists before saving.", {+ env: external_exports.string().describe("Environment ID (GUID) or a unique display-name substring")+ }, { title: "Set Current Environment" }, async ({ env }) => {+ try {+ const envs = await ctx.getClient().listEnvironments();+ let match = envs.find((e) => e.name === env);+ if (!match) {+ const q = env.toLowerCase();+ const candidates = envs.filter((e) => (e.properties?.displayName ?? "").toLowerCase().includes(q) || (e.name ?? "").toLowerCase().includes(q));+ if (candidates.length === 1)+ match = candidates[0];+ else if (candidates.length > 1) {+ return safeError(new Error(`Ambiguous: ${candidates.length} environments match "${env}". Pass the GUID. Matches: ${candidates.map((c) => `${c.properties?.displayName} (${c.name})`).join(", ")}`));+ }+ }+ if (!match)+ return safeError(new Error(`No environment matches "${env}". Call list_environments to see options.`));+ const next = getActiveMcpContext().currentEnv.set(match.name, { displayName: match.properties?.displayName ?? null, source: "set_tool" });+ return safeResult({ envId: next.envId, displayName: next.displayName, source: next.source, updatedAt: next.updatedAt });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_flows", "List cloud flows. Supports name search.", { env: external_exports.string().optional().describe("Environment ID (session default if omitted)"), name: external_exports.string().optional().describe("Filter by display name"), top: external_exports.number().optional().describe("Max results (default 50)"), filter: external_exports.string().optional().describe("OData filter (advanced)") }, { readOnlyHint: true, title: "List Flows" }, async ({ env, name: name3, top, filter }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ const opts = {};+ if (top)+ opts.top = top;+ if (filter)+ opts.filter = filter;+ const flows = await ctx.getClient().listFlows(envId, opts);+ let s = summarizeList(flows, ["name", "properties.displayName", "properties.state", "properties.lastModifiedTime"], { "properties.displayName": "displayName", "properties.state": "state", "properties.lastModifiedTime": "lastModifiedTime" });+ for (let i = 0; i < flows.length && i < s.length; i++) {+ const t = flows[i]?.properties?.definitionSummary?.triggers;+ if (t?.[0]) {+ s[i].triggerType = t[0].type;+ s[i].triggerKind = t[0].kind;+ }+ s[i].actionCount = flows[i]?.properties?.definitionSummary?.actions?.length;+ }+ if (name3) {+ const q = name3.toLowerCase();+ s = s.filter((f) => f.displayName?.toLowerCase().includes(q));+ }+ return safeResult(s);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_flow", "Get a flow's full definition + connection refs + metadata. Use this when you need to inspect or modify a specific flow. For metadata across many flows, prefer list_flows (4\xD7 faster \u2014 doesn't fetch the full definition per row).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID") }, { readOnlyHint: true, title: "Get Flow" }, async ({ env, flow }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ return safeResult(await ctx.getClient().getFlow(envId, flow));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_flow_context", "Resolve a flow's solution-membership: workflowId (Dataverse), workflowIdUnique (pre-publish), inSolution, solutionUniqueName, isManaged, isCustomizable, ownerId, category, and connectionReferenceLogicalNames. Use this BEFORE mutating a flow: refuse changes if isManaged=true, route name/description/owner changes through Dataverse for solution flows. `warning` is non-null if the lookup couldn't complete (no-dataverse-instance / workflow-not-found / dataverse-error) \u2014 treat that as 'no solution context, fall through to PPAPI behavior'.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID (PPAPI flow id)") }, { readOnlyHint: true, title: "Get Flow Context" }, async ({ env, flow }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ return safeResult(await ctx.getClient().getFlowContext(envId, flow));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("create_flow", "Create a new cloud flow from a JSON definition. **Auto-injects** $authentication + $connections parameters if missing (most agent-built definitions forget these \u2014 wave 8 fix). Refuses by default if a flow with the same displayName already exists (returns the existing flow ID + a hint to use update_flow). Pass allowDuplicate: true only when you really want a second flow with the same name. **Best practice**: call preflight_flow first to catch missing connection refs + solution-wrap risk before creating. **Use this for**: standing up a brand-new flow. **Do NOT use for**: editing an existing flow \u2014 use update_flow instead.", { env: external_exports.string().optional().describe("Environment ID"), name: external_exports.string().describe("Flow display name"), definition: external_exports.record(external_exports.unknown()).describe("Flow definition JSON"), connectionRefs: external_exports.record(external_exports.unknown()).optional().describe("Connection references JSON"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("Initial state (default Stopped)"), allowDuplicate: external_exports.boolean().optional().describe("Bypass the no-duplicate-name guard. Default false.") }, { readOnlyHint: false, title: "Create Flow" }, async ({ env, name: name3, definition, connectionRefs, state, allowDuplicate }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ let enrichedRefs = connectionRefs;+ if (enrichedRefs) {+ try {+ enrichedRefs = await enrichRefsWithLogicalNames(ctx.getClient(), envId, enrichedRefs);+ } catch {+ }+ }+ const stampedDefinition = injectTemplateMetadata(definition);+ const r = await ctx.getClient().createFlow(envId, { properties: { displayName: name3, definition: stampedDefinition, state: state || "Stopped", ...enrichedRefs ? { connectionReferences: enrichedRefs } : {} } }, { allowDuplicate });+ return safeResult({ name: r.name, displayName: r.properties?.displayName, state: r.properties?.state, createdTime: r.properties?.createdTime });+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("update_flow", "Update an existing flow's definition or properties. **Refuses by default if the flow lives in a managed Dataverse solution** (returns ManagedSolutionReadOnly). Pass forceManaged: true only if you understand the change will be overwritten on the next solution import \u2014 see docs/recipes/upgrade-managed-flow.md for the right pattern. **Recommended two-phase update**: call preview_update first to obtain a previewToken bound to the exact change, then pass that token back here. update_flow will only apply if the proposal still matches what was previewed (prevents lost writes from concurrent edits). Auto-captures a backup snapshot before applying (last 10 retained per flow, accessible via list_backups). **Use this for**: any change to an existing flow. **Do NOT use for**: creating a new flow (use create_flow) or starting/stopping a flow (use publish_flow / disable_flow).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: external_exports.record(external_exports.unknown()).optional().describe("Updated definition JSON"), connectionRefs: external_exports.record(external_exports.unknown()).optional().describe("Connection references JSON"), name: external_exports.string().optional().describe("New name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("State"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false."), previewToken: external_exports.string().optional().describe("Token issued by preview_update for this exact (env, flow, body) tuple. When supplied, the update only applies if the proposed change still matches what was previewed; mismatched tokens throw PreviewTokenMismatch.") }, { readOnlyHint: false, title: "Update Flow" }, async ({ env, flow, definition, connectionRefs, name: name3, state, forceManaged, previewToken }) => {+ try {+ const envId = ctx.resolveEnv(env);+ let enrichedRefs = connectionRefs;+ if (enrichedRefs) {+ try {+ enrichedRefs = await enrichRefsWithLogicalNames(ctx.getClient(), envId, enrichedRefs);+ } catch {+ }+ }+ const props = {};+ if (definition)+ props.definition = definition;+ if (enrichedRefs)+ props.connectionReferences = enrichedRefs;+ if (name3)+ props.displayName = name3;+ if (state)+ props.state = state;+ const r = await ctx.getClient().updateFlow(envId, flow, { properties: props }, { forceManaged, previewToken });+ return safeResult({ name: r.name, displayName: r.properties?.displayName, state: r.properties?.state, lastModifiedTime: r.properties?.lastModifiedTime });+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("preview_update", "Read-only: compute a diff between the live flow and the proposed update body, and return a short-lived single-use token. Use the token with update_flow to apply the change only if the proposal still matches what you reviewed. No mutation is performed by this tool.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: external_exports.record(external_exports.unknown()).optional().describe("Proposed updated definition JSON"), connectionRefs: external_exports.record(external_exports.unknown()).optional().describe("Proposed connection references JSON"), name: external_exports.string().optional().describe("Proposed new name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("Proposed state") }, { readOnlyHint: true, title: "Preview Update" }, async ({ env, flow, definition, connectionRefs, name: name3, state }) => {+ try {+ const envId = ctx.resolveEnv(env);+ let enrichedRefs = connectionRefs;+ if (enrichedRefs) {+ try {+ enrichedRefs = await enrichRefsWithLogicalNames(ctx.getClient(), envId, enrichedRefs);+ } catch {+ }+ }+ const props = {};+ if (definition)+ props.definition = definition;+ if (enrichedRefs)+ props.connectionReferences = enrichedRefs;+ if (name3)+ props.displayName = name3;+ if (state)+ props.state = state;+ const result = await ctx.getClient().previewUpdate(envId, flow, { properties: props });+ return safeResult(result);+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("edit_flow", "Apply targeted ('surgical') edits to an existing flow's definition without resending the whole thing \u2014 ideal for changing one action, parameter, or expression on a large flow. Each operation has an `op` and a slash-delimited `path` into the definition (e.g. `actions/Send_Email/inputs/parameters/subject`):\n \u2022 set \u2014 set (create or overwrite) the value at path\n \u2022 add \u2014 insert a new key at path (fails if it already exists)\n \u2022 remove \u2014 delete the key at path\n \u2022 merge \u2014 deep-merge an object value into the existing object at path (sibling keys preserved)\nRoutes through the same safety path as update_flow: auto-backup, managed-solution guard (pass forceManaged to override), and optional preview token. Works on non-solution and unmanaged-solution flows, with or without connection references. Set dryRun: true to get a diff + single-use previewToken without writing; re-call with the SAME operations plus that previewToken to apply. **Use this for**: small, precise changes to an existing flow. **Use update_flow** when replacing the whole definition.", {+ env: external_exports.string().optional().describe("Environment ID"),+ flow: external_exports.string().describe("Flow ID"),+ operations: external_exports.array(external_exports.object({+ op: external_exports.enum(["set", "add", "remove", "merge"]).describe("Edit verb"),+ path: external_exports.string().describe("Slash-delimited path into the definition, e.g. actions/Compose/inputs"),+ value: external_exports.unknown().optional().describe("New value (required for set/add/merge; merge requires an object)")+ })).describe("Ordered list of edit operations"),+ dryRun: external_exports.boolean().optional().describe("If true, return a diff + previewToken without writing."),+ previewToken: external_exports.string().optional().describe("Token from a prior dryRun for these exact operations; applies only if the flow still matches."),+ forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.")+ }, { readOnlyHint: false, title: "Edit Flow (surgical)" }, async ({ env, flow, operations, dryRun, previewToken, forceManaged }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ const result = await ctx.getClient().editFlow(envId, flow, operations, { dryRun, previewToken, forceManaged });+ if (result.mode === "preview") {+ return safeResult({ mode: "preview", applied: result.applied, diff: result.diff, previewToken: result.token, expiresAt: result.expiresAt, note: result.note });+ }+ return safeResult({ mode: "applied", applied: result.applied, name: result.flow.name, displayName: result.flow.properties?.displayName, lastModifiedTime: result.flow.properties?.lastModifiedTime });+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("copy_flow", "Copy a flow within the same environment or to another environment. Reads the source definition and re-creates it as a new, standalone flow (created Stopped by default). Same-env copies reuse the source connection references verbatim. Cross-env copies re-resolve each connector in the target environment (Dataverse-first, PPAPI fallback); connectors with no usable connection there are returned in `unresolvedConnectors` and the flow is left Stopped so it can't run half-wired. Flows with no connection references (built-in actions only) copy cleanly. Solution-bound sources (managed or unmanaged) are copied as plain standalone flows \u2014 solution membership is dropped (noted in the response). **Use this for**: duplicating a flow or promoting it across environments. **Do NOT use for**: a true managed-solution clone \u2014 use solution export/import.", {+ env: external_exports.string().optional().describe("Source environment ID"),+ flow: external_exports.string().describe("Source flow ID"),+ targetEnv: external_exports.string().optional().describe("Target environment ID (defaults to source env = same-env duplicate)"),+ name: external_exports.string().optional().describe("New flow name (default: '<source> (Copy)')"),+ state: external_exports.enum(["Started", "Stopped"]).optional().describe("Initial state of the copy (default Stopped)"),+ autoResolveConnections: external_exports.boolean().optional().describe("For cross-env copies, auto-resolve connections in the target. Default true.")+ }, { readOnlyHint: false, title: "Copy Flow" }, async ({ env, flow, targetEnv, name: name3, state, autoResolveConnections }) => {+ try {+ const envId = ctx.resolveEnv(env);+ ctx.rememberEnv(envId);+ const result = await ctx.getClient().copyFlow(envId, flow, { targetEnv, name: name3, state, autoResolveConnections });+ return safeResult(result);+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("publish_flow", "Enable (start) a flow. Refuses by default for managed-solution flows; pass forceManaged: true to override.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.") }, { readOnlyHint: false, title: "Enable Flow" }, async ({ env, flow, forceManaged }) => {+ try {+ await ctx.getClient().publishFlow(ctx.resolveEnv(env), flow, { forceManaged });+ return safeResult({ success: true });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("disable_flow", "Disable (stop) a flow. Refuses by default for managed-solution flows; pass forceManaged: true to override.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.") }, { readOnlyHint: false, title: "Disable Flow" }, async ({ env, flow, forceManaged }) => {+ try {+ await ctx.getClient().disableFlow(ctx.resolveEnv(env), flow, { forceManaged });+ return safeResult({ success: true });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("delete_flow", "Permanently delete a flow. **Refuses by default for managed-solution flows** (deletion is irreversible AND will be undone on next solution import). Pass forceManaged: true to override. **Use this when**: the flow is no longer needed AND you've confirmed no other flow / connection / app depends on it. **Do NOT use when**: you just want to stop the flow temporarily \u2014 use disable_flow (reversible). Auto-captures a backup snapshot before deletion, accessible via restore_backup for ~10 retentions.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.") }, { destructiveHint: true, title: "Delete Flow" }, async ({ env, flow, forceManaged }) => {+ try {+ await ctx.getClient().deleteFlow(ctx.resolveEnv(env), flow, { forceManaged });+ return safeResult({ success: true });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("run_flow", "Trigger a manual flow run. Set wait=true to poll until completion.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), body: external_exports.record(external_exports.unknown()).optional().describe("Trigger body JSON"), wait: external_exports.boolean().optional().describe("Wait for completion (default false)"), timeout: external_exports.number().optional().describe("Wait timeout seconds (default 60)") }, { readOnlyHint: false, title: "Run Flow" }, async ({ env, flow, body, wait, timeout }, extra) => {+ try {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ if (wait) {+ const prog = progress(extra);+ await prog.send(0, 100, `Triggering flow ${flow}\u2026`);+ let elapsed = 0;+ const totalSec = timeout ?? 60;+ const hb = prog.enabled ? setInterval(() => {+ elapsed += 2;+ void prog.send(Math.min(99, Math.floor(elapsed / totalSec * 100)), 100, `Polling run status\u2026 (${elapsed}s / ${totalSec}s)`);+ }, 2e3) : null;+ try {+ const triggerWallClock = Date.now() - 5e3;+ let triggerResult;+ if (body) {+ try {+ triggerResult = await c.runFlowViaCallback(envId, flow, body);+ } catch (e) {+ if (String(e?.message ?? "").match(/CallbackUrl|ListCallbackUrl/i)) {+ triggerResult = await c.runFlow(envId, flow);+ } else+ throw e;+ }+ } else {+ triggerResult = await c.runFlow(envId, flow);+ }+ const deadline = Date.now() + (timeout ? timeout * 1e3 : 6e4);+ let finalRun = null;+ while (Date.now() < deadline) {+ await new Promise((r2) => setTimeout(r2, 2e3));+ try {+ const runs = await c.getRunHistory(envId, flow, { top: 3 });+ const recent = (runs ?? []).find((r2) => new Date(r2.properties?.startTime ?? 0).getTime() > triggerWallClock);+ if (recent && recent.properties?.status !== "Running") {+ finalRun = recent;+ break;+ }+ if (recent)+ finalRun = recent;+ } catch {+ }+ }+ let actions = [];+ if (finalRun?.name) {+ try {+ const acts = await c.getRunActionDetails(envId, flow, finalRun.name);+ actions = (acts ?? []).map((a) => ({+ name: a.name,+ status: a.properties?.status,+ durationMs: a.properties?.startTime && a.properties?.endTime ? new Date(a.properties.endTime).getTime() - new Date(a.properties.startTime).getTime() : null,+ errorCode: a.properties?.error?.code+ }));+ } catch {+ }+ }+ const result = {+ triggered: true,+ runId: finalRun?.name,+ status: finalRun?.properties?.status ?? "Unknown",+ startTime: finalRun?.properties?.startTime,+ endTime: finalRun?.properties?.endTime,+ errorCode: finalRun?.properties?.error?.code,+ errorMessage: finalRun?.properties?.error?.message,+ actions+ };+ await prog.send(100, 100, `Run completed: status=${result.status}`);+ return safeResult(result);+ } finally {+ if (hb)+ clearInterval(hb);+ }+ }+ let r;+ if (body) {+ try {+ r = await c.runFlowViaCallback(envId, flow, body);+ } catch (e) {+ if (e?.message?.includes("CallbackUrl") || e?.message?.includes("ListCallbackUrl")) {+ r = await c.runFlow(envId, flow);+ } else+ throw e;+ }+ } else {+ r = await c.runFlow(envId, flow);+ }+ return safeResult(r ?? { triggered: true });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_run_history", "Get recent run history for a flow", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), top: external_exports.number().optional().describe("Max results (default 10)") }, { readOnlyHint: true, title: "Run History" }, async ({ env, flow, top }) => {+ try {+ const runs = await ctx.getClient().getRunHistory(ctx.resolveEnv(env), flow, top ? { top } : {});+ return safeResult(summarizeList(runs, ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.error.code", "properties.error.message"], { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" }));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_run_details", "Get details for a specific flow run", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), run: external_exports.string().describe("Run ID") }, { readOnlyHint: true, title: "Run Details" }, async ({ env, flow, run }) => {+ try {+ return safeResult(await ctx.getClient().getRunDetails(ctx.resolveEnv(env), flow, run));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_run_actions", "Get action-level execution details for a specific flow run", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), run: external_exports.string().describe("Run ID") }, { readOnlyHint: true, title: "Run Actions" }, async ({ env, flow, run }) => {+ try {+ const actions = await ctx.getClient().getRunActionDetails(ctx.resolveEnv(env), flow, run);+ return safeResult(summarizeList(actions, ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.code", "properties.error.code", "properties.error.message"], { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.code": "code", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" }));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_run_action_repetitions", "List iteration-level details for an action that runs inside a loop (Apply_to_each / Do_until) within a run \u2014 the only way to see WHICH iteration failed. Each repetition has its own status, inputs/outputs links, and (on failure) error. Pass the name of an action **inside** the loop (e.g. a Compose within the Apply_to_each), NOT the loop container itself \u2014 the container action returns no repetitions. `flow` defaults to the pinned current flow (set_current_flow).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), run: external_exports.string().describe("Run ID"), action: external_exports.string().describe("Loop action name (e.g. Apply_to_each)") }, { readOnlyHint: true, title: "Loop Iteration Details" }, async ({ env, flow, run, action }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ const reps = await ctx.getClient().getRunActionRepetitions(ctx.resolveEnv(env), flowId, run, action);+ return safeResult({ action, count: reps.length, repetitions: reps });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("cancel_run", "Cancel a single in-progress (Running/Waiting) flow run. `flow` defaults to the pinned current flow.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), run: external_exports.string().describe("Run ID to cancel") }, { readOnlyHint: false, title: "Cancel Run" }, async ({ env, flow, run }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ return safeResult(await ctx.getClient().cancelRun(ctx.resolveEnv(env), flowId, run));+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("resubmit_run", "Resubmit a past run using its original trigger inputs (the trigger is auto-detected from the run). Useful after fixing the cause of a failure. `flow` defaults to the pinned current flow.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), run: external_exports.string().describe("Run ID to resubmit"), trigger: external_exports.string().optional().describe("Trigger name (auto-detected from the run if omitted)") }, { readOnlyHint: false, title: "Resubmit Run" }, async ({ env, flow, run, trigger }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ return safeResult(await ctx.getClient().resubmitRun(ctx.resolveEnv(env), flowId, run, { triggerName: trigger }));+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("cancel_all_runs", "Bulk-cancel every in-progress run of a flow \u2014 for incident response when many erroneous runs are queued. Uses the Dataverse CancelAllCloudFlowRuns bulk action when the flow has a Dataverse workflow record (solution AND modern non-solution flows); otherwise cancels each Running/Waiting run individually. Optionally turns the flow off afterwards (turnOff) so the root cause can be fixed. Statuses transition Running/Waiting \u2192 Canceling \u2192 Canceled (can take up to 24h). `flow` defaults to the pinned current flow.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), turnOff: external_exports.boolean().optional().describe("Also disable the flow after cancelling. Default false."), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution guard when turning the flow off. Default false.") }, { readOnlyHint: false, title: "Cancel All Runs" }, async ({ env, flow, turnOff, forceManaged }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ return safeResult(await ctx.getClient().cancelAllRuns(ctx.resolveEnv(env), flowId, { turnOff, forceManaged }));+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("diagnose_run", "Diagnose a flow run: classify each failed/timed-out action with an actionable remediation. Read-only \u2014 fetches run details + actions and maps known error codes (auth, throttling, 404, dependent-action, etc.) to fixes. `flow` defaults to the pinned current flow.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), run: external_exports.string().describe("Run ID to diagnose") }, { readOnlyHint: true, title: "Diagnose Run" }, async ({ env, flow, run }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ return safeResult(await ctx.getClient().diagnoseRun(ctx.resolveEnv(env), flowId, run));+ } catch (e) {+ return safeError(e, enhanceFlowApiError);+ }+ });+ server2.tool("get_expression_help", "Look up Power Automate (Logic Apps WDL) expression functions \u2014 name, signature, description, and a copy-pasteable example. Filter by `query` (matches name/signature/description) and/or `category`. No args returns the full curated reference.", { query: external_exports.string().optional().describe("Search term (e.g. 'date', 'concat', 'loop item')"), category: external_exports.enum(["string", "collection", "logical", "conversion", "math", "date", "reference", "workflow"]).optional().describe("Filter by category") }, { readOnlyHint: true, title: "Expression Help" }, async ({ query, category }) => {+ try {+ return safeResult(searchExpressionHelp({ query, category }));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("set_current_flow", "Pin a flow as the session's current flow. Once pinned, run/debug tools (cancel_run, resubmit_run, cancel_all_runs, get_run_action_repetitions, diagnose_run) use it when `flow` is omitted \u2014 a guardrail so an autonomous agent acts on exactly one flow.", { env: external_exports.string().optional().describe("Environment ID (for display only)"), flow: external_exports.string().describe("Flow ID to pin") }, { readOnlyHint: false, title: "Set Current Flow" }, async ({ env, flow }) => {+ try {+ let displayName = null;+ try {+ displayName = (await ctx.getClient().getFlow(ctx.resolveEnv(env), flow)).properties?.displayName ?? null;+ } catch {+ }+ const next = getActiveMcpContext().currentFlow.set(flow, { displayName, envId: env ?? null, source: "set_tool" });+ return safeResult(next);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_current_flow", "Get the session's pinned current flow (or null if none).", {}, { readOnlyHint: true, title: "Get Current Flow" }, async () => {+ try {+ return safeResult(getActiveMcpContext().currentFlow.get());+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("clear_current_flow", "Unpin the session's current flow.", {}, { readOnlyHint: false, title: "Clear Current Flow" }, async () => {+ try {+ return safeResult(getActiveMcpContext().currentFlow.clear());+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_past_trigger_inputs", "Fetch trigger input envelopes from past flow runs \u2014 same primitive the PA designer uses for 'Test with previous run data'. Returns most-recent first by default. Use --top to limit, --runId for a specific run, --statusFilter to filter Succeeded/Failed. Each entry includes triggerInputs + a contentDigest for deduping. Best companion to test_run for instant testing without manual scaffolding.", {+ env: external_exports.string().optional().describe("Environment ID"),+ flow: external_exports.string().describe("Flow ID"),+ top: external_exports.number().optional().describe("Max past runs to fetch (default 5)"),+ runId: external_exports.string().optional().describe("Fetch a specific run instead of latest"),+ statusFilter: external_exports.enum(["Succeeded", "Failed", "any"]).optional().describe("Filter by run status (default any)")+ }, { readOnlyHint: true, title: "Past Trigger Inputs" }, async ({ env, flow, top, runId, statusFilter }) => {+ try {+ const r = await ctx.getClient().getPastTriggerInputs(ctx.resolveEnv(env), flow, { top, runId, statusFilter });+ return safeResult(r);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("preflight_flow", "Pre-save sanity check: validate the definition + check connection-ref status + detect solution-wrap-will-block-publish risk. Use BEFORE create_flow or update_flow to catch the common failure modes (missing $authentication, broken connection ref, CannotStartUnpublishedSolutionFlow). Returns {overall: ready|warn|block, validation, connectionRefs, solutionWrap, summary[]}.", {+ env: external_exports.string().optional().describe("Environment ID"),+ definition: external_exports.record(external_exports.unknown()).describe("The flow definition to check"),+ connectionReferences: external_exports.record(external_exports.unknown()).optional().describe("Connection refs in flow body (same shape as create_flow)")+ }, { readOnlyHint: true, title: "Preflight Flow" }, async ({ env, definition, connectionReferences }) => {+ try {+ const envId = ctx.resolveEnv(env);+ const result = await ctx.getClient().preflightFlow(envId, definition, {+ connectionReferences+ });+ return safeResult(result);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_trigger_emulators", "List the trigger types FlowAgent can emulate via direct connector calls (SharePoint NewItem \u2192 CreateItem etc.). Use this to know whether emulate_live_trigger (P1, pending) can fire a real trigger event for a given flow without waiting for an organic external event. Returns array of {triggerOperation, connector, emulatorOperation, livenessImpact, defaultPayload, notes?}.", {}, { readOnlyHint: true, title: "List Trigger Emulators" }, async () => {+ try {+ const { listSupportedEmulators: listSupportedEmulators2 } = await Promise.resolve().then(() => (init_trigger_emulators(), trigger_emulators_exports));+ return safeResult(listSupportedEmulators2());+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_connections", "List connections in an environment, optionally filtered by connector. Returns summarized fields (name, connector, displayName, status, owner, accountName, createdTime).", { env: external_exports.string().optional().describe("Environment ID"), connector: external_exports.string().optional().describe("Connector name filter") }, { readOnlyHint: true, title: "List Connections" }, async ({ env, connector }) => {+ try {+ const c = ctx.getClient();+ const envId = ctx.resolveEnv(env);+ const conns = await c.getConnections(envId, connector ? { connector } : void 0);+ const summarized = conns.map((cn) => {+ const statuses = cn?.properties?.statuses;+ return {+ name: cn?.name,+ connector: cn?.properties?.apiId,+ displayName: cn?.properties?.displayName,+ status: Array.isArray(statuses) && statuses.length > 0 ? statuses[0]?.status : void 0,+ statuses,+ // keep full array for callers that need transient/error detail+ owner: cn?.properties?.createdBy?.displayName,+ ownerEmail: cn?.properties?.createdBy?.userPrincipalName,+ accountName: cn?.properties?.accountName,+ createdTime: cn?.properties?.createdTime,+ allowSharing: cn?.properties?.allowSharing+ };+ });+ return safeResult(summarized);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("resolve_refs", "Auto-discover connections for connectors and output connection references JSON. Tries Dataverse first, falls back to PPAPI lookup.", { env: external_exports.string().optional().describe("Environment ID"), connectors: external_exports.string().describe("Comma-separated connector names") }, { readOnlyHint: true, title: "Resolve Connection Refs" }, async ({ env, connectors }) => {+ try {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ const names = connectors.split(",").map((s) => s.trim()).filter(Boolean);+ const refs = await c.resolveConnectionRefs(envId, names);+ return safeResult(refs);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("pick_or_create_connection", "Idempotent: get a Connected connectionName for the requested connector. Discovers via Dataverse\u2192PPAPI fallback; if none found, creates one (uses silent first-party auth for M365 connectors, browser consent otherwise). Use this instead of stitching list_connections + resolve_refs + create_connection by hand. Returns {mode: found|created|found-not-connected|no-connection-and-create-disabled, connectionName, status, authMode, connector, refSourcePath}.", {+ env: external_exports.string().optional().describe("Environment ID"),+ connector: external_exports.string().describe("Connector name (e.g. shared_sharepointonline)"),+ mode: external_exports.enum(["find-or-create", "find-only", "create-only"]).optional().describe("Default: find-or-create"),+ noBrowser: external_exports.boolean().optional().describe("Don't open browser on consent (print URL instead)"),+ params: external_exports.record(external_exports.unknown()).optional().describe("Connection parameters (e.g. for SQL: server, database)")+ }, { readOnlyHint: false, title: "Pick or Create Connection" }, async ({ env, connector, mode, noBrowser, params }, extra) => {+ try {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ const prog = progress(extra);+ await prog.send(0, 100, `Looking for existing ${connector} connection\u2026`);+ const result = await c.pickOrCreateConnection(envId, connector, { mode, noBrowser, params });+ await prog.send(100, 100, result.mode === "found" ? `Found ${result.connectionName}` : result.mode === "created" ? `Created ${result.connectionName} (${result.authMode})` : `Status: ${result.mode}`);+ return safeResult(result);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("resolve_params", "Designer-emulating dropdown resolver: returns every parameter for a connector operation with its dynamic values (lists, trees, dynamic-schemas) already resolved. Replaces N round-trips of get_dynamic_list/tree/schema with one. Auto-discovers a connection if none passed (Dataverse\u2192PPAPI fallback \u2014 handles Dataverse-only orgs). Per-dropdown errors are returned per-parameter; the call never fails wholesale. Schema is cached per session for 5 min. Use before create_flow when you don't yet know the dropdown values to pass.", {+ env: external_exports.string().optional().describe("Environment ID"),+ connector: external_exports.string().describe("Connector name (e.g. shared_sharepointonline)"),+ operation: external_exports.string().describe("Operation ID (e.g. GetItems, PostMessageToChannel)"),+ connection: external_exports.string().optional().describe("Connection name; if omitted, auto-discovered via Dataverse\u2192PPAPI"),+ currentInputs: external_exports.record(external_exports.unknown()).optional().describe("Concrete values for parent params (e.g. siteUrl, listId) so child dropdowns can resolve")+ }, { readOnlyHint: true, title: "Resolve Connector Params" }, async ({ env, connector, operation, connection, currentInputs }, extra) => {+ try {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ const prog = progress(extra);+ const result = await c.resolveParams(envId, connector, operation, { connection, currentInputs }, prog.enabled ? prog : void 0);+ return safeResult(result);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("test_connection", "Check whether a specific connection is currently Connected. Use to verify a connection is still authenticated before relying on it (cheaper than running the flow and getting a runtime auth error).", {+ env: external_exports.string().optional().describe("Environment ID"),+ connector: external_exports.string().describe("Connector name"),+ connection: external_exports.string().describe("Connection name (the GUID-suffixed identifier)")+ }, { readOnlyHint: true, title: "Test Connection" }, async ({ env, connector, connection }) => {+ try {+ const envId = ctx.resolveEnv(env);+ const r = await ctx.getClient().testConnection(envId, connector, connection);+ return safeResult({+ connected: r.connected,+ connector,+ connection,+ statuses: r.statuses,+ owner: r.connection?.properties?.createdBy?.userPrincipalName,+ accountName: r.connection?.properties?.accountName+ });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("fix_connection", "Re-authenticate a broken connection (e.g. expired token). For first-party M365 connectors this is silent; for OAuth connectors a browser opens for consent. Use when test_connection returns connected=false or when a flow run fails with auth errors.", {+ env: external_exports.string().optional().describe("Environment ID"),+ connector: external_exports.string().describe("Connector name"),+ connection: external_exports.string().describe("Connection name to re-auth"),+ noBrowser: external_exports.boolean().optional().describe("Don't open browser; print consent URL instead")+ }, { readOnlyHint: false, title: "Fix Connection" }, async ({ env, connector, connection, noBrowser }, extra) => {+ try {+ const envId = ctx.resolveEnv(env);+ const prog = progress(extra);+ await prog.send(0, 100, `Re-authenticating ${connection}\u2026`);+ const r = await ctx.getClient().fixConnection(envId, connector, connection, { noBrowser });+ const statuses = r.properties?.statuses ?? [];+ const connected = statuses.some((s) => s.status === "Connected");+ await prog.send(100, 100, connected ? `Connected: ${connection}` : `Still not Connected: ${connection}`);+ return safeResult({+ connected,+ connector,+ connection: r.name ?? connection,+ statuses,+ owner: r.properties?.createdBy?.userPrincipalName+ });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("delete_connection", "Delete a connection. Requires confirm:true to actually delete (prevents accidental destruction). Note: deleting a connection used by an enabled flow will break that flow at next run; check `list_flows` for dependencies first.", {+ env: external_exports.string().optional().describe("Environment ID"),+ connector: external_exports.string().describe("Connector name"),+ connection: external_exports.string().describe("Connection name to delete"),+ confirm: external_exports.boolean().describe("Must be true to perform the delete. Prevents accidental destruction.")+ }, { readOnlyHint: false, destructiveHint: true, title: "Delete Connection" }, async ({ env, connector, connection, confirm }) => {+ try {+ if (!confirm) {+ return safeError({+ code: "ConfirmRequired",+ message: `Refusing to delete connection ${connection} without confirm:true. Pass confirm:true to actually delete.`,+ operation: "delete_connection",+ remediation: "Re-call with confirm:true. Consider checking list_flows first for any flow that depends on this connection."+ });+ }+ const envId = ctx.resolveEnv(env);+ await ctx.getClient().deleteConnection(envId, connector, connection);+ return safeResult({ deleted: true, connector, connection });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_connectors", "List available connectors. Use query to filter by name. Returns name + displayName + tier.", { env: external_exports.string().optional().describe("Environment ID"), query: external_exports.string().optional().describe("Filter by name (case-insensitive)"), top: external_exports.number().optional().describe("Max results") }, { readOnlyHint: true, title: "List Connectors" }, async ({ env, query, top }) => {+ try {+ const conns = await ctx.getClient().listConnectors(ctx.resolveEnv(env), top ? { top } : {});+ let s = conns.map((c) => ({ name: c.name, displayName: c.displayName, tier: c.tier }));+ if (query) {+ const q = query.toLowerCase();+ s = s.filter((c) => c.name?.toLowerCase().includes(q) || c.displayName?.toLowerCase().includes(q));+ }+ return safeResult(s);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_connector", "Get connector operation index. Use query to filter. Use get_operation_details for full param specs.", { env: external_exports.string().optional().describe("Environment ID"), connector: external_exports.string().describe("Connector name"), query: external_exports.string().optional().describe("Filter operations by keyword") }, { readOnlyHint: true, title: "Get Connector" }, async ({ env, connector, query }) => {+ try {+ const r = await ctx.getClient().getConnector(ctx.resolveEnv(env), connector);+ let ops = (r.operations ?? []).map((op) => ({ operationId: op.operationId, summary: op.summary ?? "", method: op.method, path: op.path, paramCount: op.parameters?.length ?? 0 }));+ if (query) {+ const q = query.toLowerCase();+ ops = ops.filter((o) => o.operationId?.toLowerCase().includes(q) || o.summary?.toLowerCase().includes(q));+ }+ return safeResult({ name: r.name, displayName: r.displayName, operationCount: (r.operations ?? []).length, ...query ? { matchedOperations: ops.length } : {}, operations: ops });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("search_operations", "Search connector operations by keyword. Returns operation name, description, connector, and type.", { env: external_exports.string().optional().describe("Environment ID"), query: external_exports.string().optional().describe("Search text"), connector: external_exports.string().optional().describe("Limit to connector"), top: external_exports.number().optional().describe("Max results (default 20)") }, { readOnlyHint: true, title: "Search Operations" }, async ({ env, query, connector, top }) => {+ try {+ const opts = {};+ if (query)+ opts.searchText = query;+ if (connector)+ opts.operationGroupName = connector;+ opts.top = top || 20;+ const results = await ctx.getClient().searchOperations(ctx.resolveEnv(env), opts);+ const s = (Array.isArray(results) ? results : []).map((op) => ({+ name: op.name,+ displayName: op.displayName,+ description: op.description?.slice(0, 100),+ type: op.type,+ connector: op.connector?.displayName ?? op.connector?.name+ }));+ return safeResult(s);+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_operation_details", "Get exact param names, types, enums, and required action type for a connector operation", { env: external_exports.string().optional().describe("Environment ID"), connector: external_exports.string().describe("Connector name"), operation: external_exports.string().describe("Operation ID") }, { readOnlyHint: true, title: "Operation Details" }, async ({ env, connector, operation }) => {+ try {+ const schema = await ctx.getClient().getOperationSchema(ctx.resolveEnv(env), connector, operation);+ const props = schema?.properties ?? schema;+ const inputs = props?.inputsDefinition ?? {};+ const params = inputs?.parameters ?? {};+ return safeResult({+ operationId: operation,+ connector,+ summary: props?.summary ?? props?.description,+ actionType: inferActionType(props),+ parameters: Object.fromEntries(Object.entries(params).map(([k, v]) => [k, { type: v?.type, required: v?.required ?? false, description: v?.summary ?? v?.description, enum: v?.enum, default: v?.default, dynamicValues: v?.["x-ms-dynamic-values"] ? true : void 0, dynamicTree: v?.["x-ms-dynamic-tree"] ? true : void 0 }]))+ });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("invoke_operation", "Call a connector's dynamic resolver (dropdowns, tree browsing, dynamic schemas)", { env: external_exports.string().optional().describe("Environment ID"), connector: external_exports.string().describe("Connector name"), connection: external_exports.string().describe("Connection ID"), operation: external_exports.string().describe("Operation ID"), params: external_exports.record(external_exports.unknown()).optional().describe("Parameters JSON") }, { readOnlyHint: false, title: "Invoke Operation" }, async ({ env, connector, connection, operation, params }) => {+ try {+ return safeResult(await ctx.getClient().invokeOperation(ctx.resolveEnv(env), connector, connection, operation, params));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_templates", "List built-in flow templates", {}, { readOnlyHint: true, title: "List Templates" }, async () => {+ try {+ return safeResult(listTemplates());+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("scaffold_flow", "Generate flow definition from template. Pass env to auto-resolve connections.", { template: external_exports.string().describe("Template ID"), env: external_exports.string().optional().describe("Environment ID for connection resolution") }, { readOnlyHint: true, title: "Scaffold Flow" }, async ({ template, env }) => {+ try {+ const tmpl = getTemplate(template);+ if (!tmpl)+ return safeError(new Error(`Template "${template}" not found. Use list_templates.`));+ const definition = injectTemplateMetadata(tmpl.definition);+ let refs;+ if (env && tmpl.connectors.length > 0) {+ try {+ refs = await ctx.getClient().resolveConnectionRefs(ctx.resolveEnv(env), tmpl.connectors);+ } catch {+ refs = generateConnectionRefs(tmpl.connectors);+ }+ } else {+ refs = generateConnectionRefs(tmpl.connectors);+ }+ return safeResult({ definition, connectionReferences: refs, template: { id: tmpl.id, name: tmpl.name, connectors: tmpl.connectors } });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("validate_flow", "Pre-validate a flow definition against PA rules", { definition: external_exports.record(external_exports.unknown()).describe("Flow definition JSON"), connectionRefs: external_exports.record(external_exports.unknown()).optional().describe("Connection references JSON") }, { readOnlyHint: true, title: "Validate Flow" }, async ({ definition, connectionRefs }) => {+ try {+ const errs = validateDefinition(definition, connectionRefs);+ return safeResult(errs.length === 0 ? { valid: true } : { valid: false, errors: errs });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("smoke_test", "End-to-end connectivity test: create, run, verify, cleanup", { env: external_exports.string().optional().describe("Environment ID") }, { readOnlyHint: false, title: "Smoke Test" }, async ({ env }) => {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ const t0 = Date.now();+ const def = { $schema: "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", contentVersion: "1.0.0.0", parameters: { $authentication: { defaultValue: {}, type: "SecureObject" }, $connections: { defaultValue: {}, type: "Object" } }, triggers: { manual: { type: "Request", kind: "Button", inputs: { schema: { type: "object", properties: {}, required: [] } } } }, actions: { Compose_Smoke: { type: "Compose", inputs: { smoke: "ok", ts: "@utcNow()" }, runAfter: {} } } };+ let fid;+ try {+ const f = await c.createFlow(envId, { properties: { displayName: `_smoke-test-${Date.now()}`, definition: def, state: "Started" } }, { allowDuplicate: true });+ fid = f.name;+ await c.runFlow(envId, fid, {});+ let st = "Running";+ const dl = Date.now() + 3e4;+ while (st === "Running" && Date.now() < dl) {+ await new Promise((r) => setTimeout(r, 2e3));+ const runs = await c.getRunHistory(envId, fid, { top: 1 });+ if (runs.length)+ st = runs[0].properties.status;+ }+ const el = ((Date.now() - t0) / 1e3).toFixed(1);+ await c.deleteFlow(envId, fid, { forceManaged: true, skipBackup: true });+ fid = void 0;+ return safeResult({ passed: st === "Succeeded", status: st, elapsed_seconds: parseFloat(el) });+ } catch (e) {+ const el = ((Date.now() - t0) / 1e3).toFixed(1);+ if (fid)+ try {+ await c.deleteFlow(envId, fid, { forceManaged: true, skipBackup: true });+ } catch {+ }+ return safeError(new Error(`Smoke test failed after ${el}s: ${e instanceof Error ? e.message : e}`));+ }+ });+ server2.tool("list_desktop_flows", "List desktop flows (RPA) in an environment", { env: external_exports.string().optional().describe("Environment ID"), top: external_exports.number().optional().describe("Max results"), name: external_exports.string().optional().describe("Filter by name") }, { readOnlyHint: true, title: "List Desktop Flows" }, async ({ env, top, name: name3 }) => {+ try {+ const opts = {};+ if (top)+ opts.top = top;+ if (name3)+ opts.nameFilter = name3;+ return safeResult(await ctx.getClient().listDesktopFlows(ctx.resolveEnv(env), opts));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("run_desktop_flow", "Trigger a desktop flow and wait for completion", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Desktop flow ID"), machineGroup: external_exports.string().optional().describe("Machine group name or ID"), body: external_exports.record(external_exports.unknown()).optional().describe("Input data JSON"), timeout: external_exports.number().optional().describe("Timeout seconds (default 120)") }, { readOnlyHint: false, title: "Run Desktop Flow" }, async ({ env, flow, machineGroup, body, timeout }) => {+ try {+ const envId = ctx.resolveEnv(env);+ const c = ctx.getClient();+ const opts = {};+ if (body)+ opts.inputs = body;+ if (timeout)+ opts.timeoutMs = timeout * 1e3;+ if (machineGroup) {+ const g = await c.resolveMachineGroup(envId, machineGroup);+ opts.machineGroupId = g.machineGroupId || machineGroup;+ }+ return safeResult(await c.runDesktopFlowAndWait(envId, flow, opts));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_machine_groups", "List machine groups in an environment", { env: external_exports.string().optional().describe("Environment ID") }, { readOnlyHint: true, title: "List Machine Groups" }, async ({ env }) => {+ try {+ return safeResult(await ctx.getClient().listMachineGroups(ctx.resolveEnv(env)));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("list_backups", "List pre-mutation backup snapshots captured for a flow. Newest first. Last 10 retained per flow.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID") }, { readOnlyHint: true, title: "List Backups" }, async ({ env, flow }) => {+ try {+ const envId = ctx.resolveEnv(env);+ const backups = listBackups(envId, flow);+ return safeResult({ backupRoot: getBackupRoot(), envId, flowId: flow, count: backups.length, backups });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("get_backup", "Read a specific backup snapshot's full contents (flow definition, connectionReferences, optional context).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), file: external_exports.string().describe("Backup filename from list_backups") }, { readOnlyHint: true, title: "Get Backup" }, async ({ env, flow, file }) => {+ try {+ const envId = ctx.resolveEnv(env);+ return safeResult(readBackup(envId, flow, file));+ } catch (e) {+ return safeError(e);+ }+ });+ server2.tool("restore_backup", "Restore a flow from a backup snapshot. If the flow still exists, the current state is itself backed up and then the flow is updated in place. If the flow was deleted, it is recreated (which yields a new flow ID). Pass file to choose a specific backup; omit for the latest.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID (original)"), file: external_exports.string().optional().describe("Backup filename. Defaults to most recent."), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.") }, { readOnlyHint: false, title: "Restore Backup" }, async ({ env, flow, file, forceManaged }) => {+ try {+ const envId = ctx.resolveEnv(env);+ let chosen = file;+ if (!chosen) {+ const list = listBackups(envId, flow);+ if (list.length === 0)+ throw new Error(`No backups found for ${flow} in env ${envId}.`);+ chosen = list[0].filename;+ }+ const result = await ctx.getClient().restoreFlowFromBackup(envId, flow, chosen, { forceManaged });+ return safeResult({ ...result, restoredFrom: chosen });+ } catch (e) {+ return safeError(e);+ }+ });+ server2.prompt("build-flow-from-trigger", "Guided multi-step flow creation: trigger type \u2192 actions \u2192 connections \u2192 validate \u2192 preflight \u2192 create. Use when the user asks 'build a flow that does X' without specifying the precise steps.", {+ goal: external_exports.string().describe("What the flow should do, in natural language"),+ envId: external_exports.string().optional().describe("Target environment ID")+ }, ({ goal, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Build a Power Automate cloud flow that achieves this goal:`,+ ``,+ `> ${goal}`,+ ``,+ `Workflow:`,+ envId ? `1. Use env: \`${envId}\`` : `1. Call \`list_environments\` and pick the active env.`,+ `2. Identify the trigger type (Request / Recurrence / SharePoint OnNewItem / etc.) and the actions.`,+ `3. For each connector touched, call \`pick_or_create_connection mode=find-or-create\`. Capture connection names.`,+ `4. For each connector operation, call \`resolve_params\` to know its parameters (especially dynamic dropdowns).`,+ `5. Compose the definition + connectionReferences.`,+ `6. Call \`preflight_flow\` \u2014 must return \`overall: "ready"\` or \`"warn"\` before continuing.`,+ `7. Call \`create_flow\` (auto-injects \`$authentication\` + \`$connections\` if missing).`,+ `8. Optionally \`publish_flow\` once the user confirms.`,+ ``,+ `If preflight returns \`block\` due to \`solutionWrap.detected\`, resolve all connection refs first.`,+ `If a connector you need isn't in the env, surface that to the user before proceeding.`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("debug-failed-run", "Triage a failed flow run by isolating the root-cause action and suggesting a fix. Follows the steps in `docs/recipes/debug-failed-run.md`.", {+ flowId: external_exports.string().describe("Flow ID with a failed run"),+ runId: external_exports.string().optional().describe("Specific run ID; if omitted, picks the most recent Failed run"),+ envId: external_exports.string().optional().describe("Environment ID")+ }, ({ flowId, runId, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Debug flow ${flowId}${runId ? `, run ${runId}` : ""}${envId ? ` in env ${envId}` : ""}.`,+ ``,+ `Recipe: \`docs/recipes/debug-failed-run.md\``,+ ``,+ `Steps:`,+ `1. \`get_run_history\` to confirm there's a Failed run (skip if runId provided).`,+ `2. \`get_run_actions env=... flow=... run=...\` for the failed run.`,+ `3. \`get_flow\` to inspect the action graph + runAfter dependencies.`,+ `4. Apply root-cause heuristic: Failed action whose runAfter dependencies all Succeeded = root cause; rest are cascades.`,+ `5. If the action has \`inputsLink.uri\`, GET it (no auth header \u2014 SAS URL) to see the resolved inputs.`,+ `6. Classify error: auth failure \u2192 \`fix_connection\`; bad expression \u2192 \`update_flow\`; transient \u2192 retry via \`run_flow\`.`,+ `7. Propose a single specific fix to the user with the exact tool call to apply it.`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("migrate-account", "Move flows from a connection-under-account-A to a new connection-under-account-B. PA connections are immutable on identity; the supported path is create-new \u2192 bulk-swap \u2192 delete-old.", {+ connector: external_exports.string().describe("Connector (e.g. shared_sharepointonline)"),+ oldConnection: external_exports.string().describe("Existing connection name to retire"),+ envId: external_exports.string().optional().describe("Environment ID")+ }, ({ connector, oldConnection, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Migrate flows from connection \`${oldConnection}\` (connector \`${connector}\`) to a new connection under a different account.`,+ ``,+ `Recipe: \`docs/recipes/migrate-account.md\``,+ ``,+ `**Important constraint**: PA connections are immutable bound to their OAuth identity. We can't swap accounts in-place. Workflow:`,+ ``,+ `1. **List dependencies**: GET \`/api/connections/${connector}/${oldConnection}/references?env=${envId ?? "<env>"}\` (dashboard) or iterate \`list_flows\` + \`get_flow\` (MCP-only).`,+ `2. **Account check**: confirm with the user that the new account is signed in to MSAL. If first-party silent auth would reuse the OLD account, advise \`az logout\` + \`az login\` as the new account first.`,+ `3. **Create new connection**: \`pick_or_create_connection env=${envId ?? "<env>"} connector=${connector} mode=create-only\`. Save the \`connectionName\`.`,+ `4. **Bulk-repoint**: dashboard \`POST /api/connections/${connector}/${oldConnection}/bulk-swap\` with \`{ "targetConnectionName": "<new>", "dryRun": true }\` first to preview, then \`dryRun: false\` to apply.`,+ `5. **Verify**: for one impacted flow, \`run_flow wait=true\` to confirm the new connection works end-to-end.`,+ `6. **Cleanup (optional)**: \`delete_connection connector=${connector} connection=${oldConnection} confirm=true\` once all flows are migrated.`,+ ``,+ `Surface every step to the user and pause for confirmation before steps 3, 4, and 6 (the mutating ones).`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("audit-env-for-orphans", "Find connection references in flows that point at non-existent connections, plus stale (long-disabled) flows. Follows `docs/recipes/audit-orphan-refs.md`.", {+ envId: external_exports.string().optional().describe("Environment ID"),+ staleAfterDays: external_exports.number().optional().describe("Flag flows with no successful run in this many days (default 90)")+ }, ({ envId, staleAfterDays }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Audit env ${envId ?? "(current)"} for orphan connection references and stale flows.`,+ ``,+ `Recipe: \`docs/recipes/audit-orphan-refs.md\``,+ ``,+ `Steps:`,+ `1. \`list_flows env=...\` \u2192 enumerate every flow.`,+ `2. \`list_connections env=...\` \u2192 build a set of (connector, connectionName) tuples that actually exist.`,+ `3. For each flow, \`get_flow\` \u2192 collect its \`connectionReferences\` (parallel, batch 5 at a time).`,+ `4. Diff: any (flow, ref) where ref.connectionName is NOT in the live set = orphan.`,+ `5. Stale check: any flow with state=Started but no successful run in the last ${staleAfterDays ?? 90} days = stale candidate.`,+ ``,+ `Return a structured report:`,+ `- **Orphan refs**: list of \`{ flowId, displayName, state, brokenRefs[] }\` grouped by connector`,+ `- **Stale flows**: list of \`{ flowId, displayName, state, lastSuccessAge }\``,+ `- **Suggested remediation** per row (swap-connection-bulk, delete, disable, etc.)`,+ ``,+ `Do NOT mutate anything in this audit \u2014 read-only.`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("test-with-past-input", "Run a flow using the trigger envelope from a previous run as the body. Best for 'reproduce that failure' or 'test my fix without making up inputs'.", {+ flowId: external_exports.string().describe("Flow to run"),+ sourceRunId: external_exports.string().optional().describe("Specific past run to copy from; omit for the latest successful run"),+ envId: external_exports.string().optional().describe("Environment ID")+ }, ({ flowId, sourceRunId, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Run flow \`${flowId}\`${envId ? ` in env \`${envId}\`` : ""} using past trigger input.`,+ ``,+ `1. \`get_past_trigger_inputs env=${envId ?? "<env>"} flow=${flowId} ${sourceRunId ? `runId=${sourceRunId}` : "top=1 statusFilter=Succeeded"}\``,+ `2. Show the user the resolved \`triggerInputs\` envelope, including the \`contentDigest\`.`,+ `3. Ask confirmation: "Run with this exact payload? Approvals will fire to real people; emails will send."`,+ `4. On confirmation, \`run_flow env=... flow=... wait=true body=<inputs.body or inputs>\``,+ `5. Report the result: status, per-action timings, and any error code.`,+ `6. If Failed, follow up with the \`debug-failed-run\` recipe.`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("save-and-publish", "Pre-publish safety pipeline: backup \u2192 preflight \u2192 preview \u2192 update \u2192 publish. Use before changing any production flow.", {+ flowId: external_exports.string().describe("Flow ID to update"),+ changeSummary: external_exports.string().describe("One-line description of what's changing"),+ envId: external_exports.string().optional().describe("Environment ID")+ }, ({ flowId, changeSummary, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Safely update flow \`${flowId}\`${envId ? ` in env \`${envId}\`` : ""}:`,+ ``,+ `> Change: ${changeSummary}`,+ ``,+ `1. \`get_flow env=... flow=...\` to capture the current state (backup is automatic via update_flow's snapshot).`,+ `2. \`preflight_flow definition=<proposed> connectionReferences=<proposed>\` \u2014 must return \`overall != "block"\`.`,+ `3. \`preview_update env=... flow=... definition=<proposed> connectionReferences=<proposed>\` \u2014 review the diff, capture the \`previewToken\`.`,+ `4. Show the user the diff summary. Pause for explicit confirmation.`,+ `5. On confirmation, \`update_flow ... previewToken=<token>\`. The token binds the apply to the exact diff you previewed \u2014 concurrent edits will reject.`,+ `6. Optionally \`publish_flow\` if the flow needs to be started.`,+ `7. If you need to roll back: \`list_backups flow=...\` \u2192 \`restore_backup file=<filename>\`.`,+ ``,+ `Refuse to proceed past step 2 if preflight returns \`overall: "block"\` without explicit user override.`+ ].join("\n")+ }+ }]+ }));+ server2.prompt("swap-connection-bulk-prompt", "Replace one connection with another across every flow that references it. Use for pre-prod \u2192 prod cutover or replacing a deprecated connection.", {+ connector: external_exports.string().describe("Connector name"),+ sourceConnection: external_exports.string().describe("Connection currently in use"),+ targetConnection: external_exports.string().describe("Connection to switch to (must exist)"),+ envId: external_exports.string().optional().describe("Environment ID")+ }, ({ connector, sourceConnection, targetConnection, envId }) => ({+ messages: [{+ role: "user",+ content: {+ type: "text",+ text: [+ `Repoint every flow that references \`${sourceConnection}\` to \`${targetConnection}\` (connector \`${connector}\`).`,+ ``,+ `Recipe: \`docs/recipes/swap-connection-bulk.md\``,+ ``,+ `1. Verify target exists: \`test_connection env=${envId ?? "<env>"} connector=${connector} connection=${targetConnection}\` \u2014 expect \`connected: true\`.`,+ `2. Dry-run via dashboard \`POST /api/connections/${connector}/${sourceConnection}/bulk-swap\` with \`{ "targetConnectionName": "${targetConnection}", "dryRun": true }\` to enumerate impacted flows.`,+ `3. Show the user the impacted-flow list and pause for confirmation.`,+ `4. Apply with \`dryRun: false\`.`,+ `5. Report per-flow success/failure. For failures, classify:`,+ ` - \`ManagedSolutionReadOnly\` \u2192 suggest either upstream solution change or \`forceManaged: true\`.`,+ ` - Concurrent modification \u2192 retry the failed subset.`,+ `6. Verify by running one impacted flow with the new connection.`+ ].join("\n")+ }+ }]+ }));+ server2.resource("validation-rules", "flowagent://rules/validation", { description: "Active flow-definition validation rules. Agent can read to know what `validate_flow` checks.", mimeType: "application/json" }, async () => {+ const rules = [+ { rule: "missing-authentication-param", severity: "error", message: "Definition must declare $authentication parameter (type: SecureObject)." },+ { rule: "missing-connections-param", severity: "error", message: "Definition must declare $connections parameter (type: Object). Auto-injected by create_flow." },+ { rule: "invalid-trigger-type", severity: "error", message: "Trigger type must be one of: Request, Recurrence, OpenApiConnection, OpenApiConnectionWebhook, OpenApiConnectionNotification, ApiConnection, ApiConnectionWebhook, ApiConnectionNotification, Http, HttpWebhook." },+ { rule: "invalid-request-kind", severity: "error", message: "Request trigger kind must be one of: Button, Http, PowerApp, PowerAppV2, VirtualAgent, Skills, ApiConnection, PowerPages." },+ { rule: "approvals-param-prefix", severity: "error", message: "StartAndWaitForAnApproval parameters must use WebhookApprovalCreationInput/ prefix (not bare names, not ApprovalCreationInput/)." },+ { rule: "approval-type-enum", severity: "error", message: "approvalType must be one of: Basic, BasicAwaitAll, CustomResponse, CustomResponseAwaitAll, Sequential." },+ { rule: "connection-ref-missing", severity: "error", message: "Every connector action must reference a connectionName that exists in connectionReferences." }+ ];+ return {+ contents: [{+ uri: "flowagent://rules/validation",+ mimeType: "application/json",+ text: JSON.stringify({ rules, _note: "Source of truth: packages/core/src/validation/flow-definition.ts. This resource summarises for agent context." }, null, 2)+ }]+ };+ });+ server2.resource("trigger-emulators", "flowagent://emulators/triggers", { description: "Map of trigger operations to their lowest-impact connector emulator. Used by emulate_live_trigger.", mimeType: "application/json" }, async () => {+ const { listSupportedEmulators: listSupportedEmulators2 } = await Promise.resolve().then(() => (init_trigger_emulators(), trigger_emulators_exports));+ return {+ contents: [{+ uri: "flowagent://emulators/triggers",+ mimeType: "application/json",+ text: JSON.stringify(listSupportedEmulators2(), null, 2)+ }]+ };+ });+ server2.resource("templates-catalog", "flowagent://templates/catalog", { description: "All built-in flow templates with their connector requirements and trigger types.", mimeType: "application/json" }, async () => {+ const cat = listTemplates();+ return {+ contents: [{+ uri: "flowagent://templates/catalog",+ mimeType: "application/json",+ text: JSON.stringify({+ templates: cat,+ _hint: "Use scaffold_flow with one of these IDs to generate a starting definition. Then update_flow to customise."+ }, null, 2)+ }]+ };+ });+ server2.resource("recipes-index", "flowagent://recipes/index", { description: "Index of step-by-step recipes for common workflows. Each entry points at a markdown file with detailed steps.", mimeType: "application/json" }, async () => {+ const recipes = [+ { slug: "migrate-account", title: "Move flows to a new connection under a different account", uri: "flowagent://recipes/migrate-account" },+ { slug: "swap-connection-bulk", title: "Replace one connection with another across many flows", uri: "flowagent://recipes/swap-connection-bulk" },+ { slug: "audit-orphan-refs", title: "Find dead connection references and stale flows", uri: "flowagent://recipes/audit-orphan-refs" },+ { slug: "upgrade-managed-flow", title: "Modify a flow that lives in a managed solution", uri: "flowagent://recipes/upgrade-managed-flow" },+ { slug: "add-error-handler", title: "Wrap a flow with a Send-Email-on-Failure handler", uri: "flowagent://recipes/add-error-handler" },+ { slug: "clone-flow-to-env", title: "Copy a flow to a different environment", uri: "flowagent://recipes/clone-flow-to-env" },+ { slug: "debug-failed-run", title: "Triage a failed run: isolate root cause", uri: "flowagent://recipes/debug-failed-run" },+ { slug: "build-from-it-equipment-demo", title: "Stand up the IT Equipment Request scenario", uri: "flowagent://recipes/build-from-it-equipment-demo" }+ ];+ return {+ contents: [{+ uri: "flowagent://recipes/index",+ mimeType: "application/json",+ text: JSON.stringify({ recipes, source_path: "flow-agent/docs/recipes/" }, null, 2)+ }]+ };+ });+ server2.resource("recipe-content", new ResourceTemplate("flowagent://recipes/{slug}", { list: void 0 }), { description: "Full markdown content of a specific recipe by slug.", mimeType: "text/markdown" }, async (uri, { slug }) => {+ const fs3 = await import("node:fs");+ const path3 = await import("node:path");+ const fileURLToPath = (await import("node:url")).fileURLToPath;+ const here = path3.dirname(fileURLToPath(import.meta.url));+ const recipesDir = path3.resolve(here, "..", "..", "docs", "recipes");+ const safeSlug = String(slug).replace(/[^a-z0-9-]/gi, "");+ const file = path3.join(recipesDir, `${safeSlug}.md`);+ try {+ const text = fs3.readFileSync(file, "utf-8");+ return { contents: [{ uri: uri.href, mimeType: "text/markdown", text }] };+ } catch {+ return { contents: [{ uri: uri.href, mimeType: "text/plain", text: `Recipe '${safeSlug}' not found. Available recipes: see flowagent://recipes/index` }] };+ }+ });+ return server2;+}++// packages/core/dist/index.js+init_logger();+function createTelemetryObserver(_opts) {+ return { onToolStart() {+ }, onToolEnd() {+ } };+}++// packages/cli/dist/bin/mcp-stdio.js+var auth = buildCompositeAuth();+var server = await createMcpServer(auth, {+ ...createTelemetryObserver({+ transport: "stdio",+ getClientInfo: () => server?.server?.getClientVersion?.()+ })+});+var transport = new StdioServerTransport();+await server.connect(transport);+var toolCount = countRegisteredTools(server);+console.error(`FlowAgent MCP server running on stdio (${toolCount} tools)`);+function countRegisteredTools(srv) {+ try {+ const internal = srv._registeredTools;+ if (internal && typeof internal === "object") {+ return Object.keys(internal).length;+ }+ } catch {+ }+ return 0;+}+/*! Bundled license information:++@azure/msal-node/dist/cache/serializer/Serializer.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-common/dist/utils/Constants.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/constants/AADServerParamKeys.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/AuthError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/ClientConfigurationError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/StringUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/ClientAuthError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/request/ScopeSet.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/request/RequestParameterBuilder.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/UrlUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/crypto/ICrypto.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/logger/Logger.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/packageMetadata.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/AuthorityOptions.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/account/AuthToken.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/account/AccountInfo.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/url/UrlString.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/AuthorityMetadata.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/CacheErrorCodes.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/CacheError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/account/ClientInfo.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/AuthorityType.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/account/TokenClaims.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/ProtocolMode.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/cache/utils/AccountEntityUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/cache/CacheManager.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/config/ClientConfiguration.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/TimeUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/cache/utils/CacheHelpers.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/telemetry/performance/PerformanceEvents.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/FunctionWrappers.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/crypto/PopTokenGenerator.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/ServerError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/ProtocolUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/response/ResponseHandler.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/account/CcsCredential.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/utils/ClientAssertionUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/network/RequestThumbprint.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/network/ThrottlingUtils.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/NetworkError.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/protocol/Token.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/RegionDiscovery.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/Authority.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/authority/AuthorityFactory.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/client/AuthorizationCodeClient.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/client/RefreshTokenClient.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/client/SilentFlowClient.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/protocol/Authorize.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/request/BaseAuthRequest.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/error/AuthErrorCodes.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-common/dist/index-node.mjs:+ (*! @azure/msal-common v16.11.0 2026-06-30 *)++@azure/msal-node/dist/cache/serializer/Deserializer.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/internals.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/utils/Constants.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/network/HttpClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/error/ManagedIdentityError.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/config/ManagedIdentityId.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/error/NodeAuthError.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/config/Configuration.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/crypto/GuidGenerator.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/utils/EncodingUtils.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/crypto/HashUtils.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/crypto/PkceGenerator.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/crypto/CryptoProvider.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/cache/CacheHelpers.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/cache/NodeStorage.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/cache/TokenCache.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++safe-buffer/index.js:+ (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)++@azure/msal-node/dist/error/ClientAuthErrorCodes.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ClientAssertion.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/packageMetadata.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/BaseClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/UsernamePasswordClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/protocol/Authorize.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ClientApplication.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/network/LoopbackClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/DeviceCodeClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/PublicClientApplication.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ClientCredentialClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/OnBehalfOfClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/UserFederatedIdentityCredentialClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ConfidentialClientApplication.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/utils/TimeUtils.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/network/HttpClientWithRetries.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/retry/LinearRetryStrategy.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentityClient.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/client/ManagedIdentityApplication.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)++@azure/msal-node/dist/index.mjs:+ (*! @azure/msal-node v5.3.1 2026-06-30 *)+*/diff --git a/plugins/power-automate/skills/browse-flows/SKILL.md b/plugins/power-automate/skills/browse-flows/SKILL.mdnew file mode 100644index 000000000..07a1743e9--- /dev/null+++ b/plugins/power-automate/skills/browse-flows/SKILL.md@@ -0,0 +1,39 @@+---+name: browse-flows+description: Browse Power Automate environments and flows interactively. Use when the user wants to browse, list, or explore their flows and environments.+user-invocable: true+argument-hint: "[environment-id]"+allowed-tools: Bash, Read, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow+model: opus+---++# Browse Environments and Flows++Interactive skill for discovering Power Automate environments and flows.++## Tools++This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients+surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in+Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent+MCP server.++## Steps++1. **Resolve environment**:+ - If `$ARGUMENTS` contains an environment ID, use it.+ - Otherwise call `list_environments` (use `query` to filter if user mentioned a name).+ - If multiple environments, use AskUserQuestion to let user pick.++2. **List flows**: Call `list_flows` on the selected environment. Use `name` param if user is looking for something specific.++3. **Present results** in a table:++ | # | Name | State | Trigger | Actions | Last Modified |+ |---|------|-------|---------|---------|---------------|++4. **Offer next steps** via AskUserQuestion:+ - View flow details (`get_flow`)+ - Check run history (`get_run_history`)+ - Debug a failed flow (use `/debug-flow`)+ - Create a new flow (use `/create-flow`)diff --git a/plugins/power-automate/skills/build-flow/SKILL.md b/plugins/power-automate/skills/build-flow/SKILL.mdnew file mode 100644index 000000000..ab83c8ea7--- /dev/null+++ b/plugins/power-automate/skills/build-flow/SKILL.md@@ -0,0 +1,97 @@+---+name: build-flow+description: Autonomously build a complete Power Automate flow from a description. Use when you need to generate a full flow definition and create it.+user-invocable: true+argument-hint: "<description>"+context: fork+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Flow Builder Agent++You are an autonomous Power Automate flow builder agent. Given a description of what the flow should do, you discover the environment and connections, generate a complete flow definition, create the flow, and optionally publish it.++## Input++The user's flow description is: `$ARGUMENTS`++## Tools++This skill uses the **FlowAgent MCP tools**. Clients surface them with a+client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.+If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.++| Tool | Purpose |+|------|---------|+| `list_environments` | Find environments |+| `get_connector` | Get the operation index for a connector |+| `get_operation_details` | Exact parameter names, types, enums, and required action type |+| `list_connections` | Verify connections exist |+| `invoke_operation` | Resolve dynamic dropdown/tree values |+| `get_expression_help` | Look up Logic Apps expression functions + examples |+| `validate_flow` | Pre-flight definition check (offline rules) |+| `preflight_flow` | Multi-signal readiness check (missing refs, solution-wrap) |+| `create_flow` | Create the flow |+| `edit_flow` | Apply surgical action-level edits when iterating |+| `get_flow` | Verify creation |+| `publish_flow` | Enable the flow |+| `scaffold_flow` | Generate from a built-in template |++## Critical Rules++1. **ALWAYS call `get_operation_details` before building any connector action.** Never guess parameter names, enum values, or action types. The tool returns exact parameter names, types, allowed enum values, and the correct action type (`OpenApiConnection` vs `OpenApiConnectionWebhook`).++2. **Use the correct action type.** Standard operations use `OpenApiConnection`. Webhook operations (Approvals `StartAndWaitForAnApproval`, etc.) use `OpenApiConnectionWebhook`. `get_operation_details` returns this in the `actionType` field.++3. **Always declare both parameters** in the definition:+ ```json+ "parameters": {+ "$authentication": { "defaultValue": {}, "type": "SecureObject" },+ "$connections": { "defaultValue": {}, "type": "Object" }+ }+ ```++4. **Do NOT include `authentication` in action inputs.** The Flow API auto-injects it on save.++5. **Use `Embedded` source** in connection references. Never `Invoker`.++6. **HTTP Request triggers (`kind: "Http"`) require Premium.** Use `kind: "Button"` for free/seeded plans.++7. **Validate before creating.** Call `validate_flow` to catch errors before hitting the API.++## Workflow++1. **Discover environment**: Call `list_environments`. Use `query` param to filter by name if the user specified one.++2. **Check for templates**: If the description matches a common pattern, call `list_templates` and `scaffold_flow` to start from a template instead of building from scratch.++3. **Look up connector operations**: For each connector the flow needs, call `get_connector` with a `query` to find the right operation (e.g., `get_connector(connector="shared_teams", query="post message")`).++4. **Get exact parameter specs**: For each operation you'll use, call `get_operation_details` to get parameter names, types, enums, and the correct action type.++5. **Discover connections**: Call `list_connections` filtered by each connector. Verify at least one has "Connected" status.++6. **Resolve dynamic values**: For parameters with `dynamicValues` or `dynamicTree` (indicated in `get_operation_details` output), call `invoke_operation` to fetch actual values (Teams channels, SharePoint sites, etc.).++7. **Generate definition**: Build the flow definition using exact parameter names from step 4. Write to a JSON file.++8. **Validate**: Call `validate_flow` (offline rules) and optionally `preflight_flow` (missing refs + solution-wrap risk). Fix any errors.++9. **Create flow**: Call `create_flow` in Stopped state.++10. **Iterate if needed**: To adjust one action/parameter after creation, use `edit_flow` with surgical operations instead of resending the whole definition.++11. **Report**: Output flow ID, name, and state.++## Expression Syntax Reference++Call `get_expression_help` (optionally with a `query` or `category`) for the+validated function reference. Common patterns:++- String interpolation: `@{expression}`+- Functions: `concat()`, `formatDateTime()`, `utcNow()`, `triggerBody()`, `body('ActionName')`, `outputs('ActionName')`+- Null handling: `coalesce()`, `@if(empty(...), 'default', ...)`+- `result()` function only works inside Scope/ForEach/Until/Switch actions+- `triggerBody()` may be null when flow is triggered via management API (use `coalesce`)diff --git a/plugins/power-automate/skills/create-flow/SKILL.md b/plugins/power-automate/skills/create-flow/SKILL.mdnew file mode 100644index 000000000..949a765bf--- /dev/null+++ b/plugins/power-automate/skills/create-flow/SKILL.md@@ -0,0 +1,48 @@+---+name: create-flow+description: Guided flow creation wizard. Use when the user wants to create a new flow interactively.+user-invocable: true+argument-hint: "[description]"+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Guided Flow Creation Wizard++Walk the user through creating a Power Automate flow step by step.++## Tools++This skill uses the **FlowAgent MCP tools**. Clients surface them with a+client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.+If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.++## Steps++1. **Gather requirements**: Ask what the flow should do. Identify triggers, actions, connectors.++2. **Select environment**: Call `list_environments` (use `query` to filter). Let user pick or auto-select.++3. **Check for templates**: Call `list_templates`. If a template matches (approval, digest, webhook, etc.), offer to use `scaffold_flow` as a starting point.++4. **Discover connectors**: For each connector, call `get_connector` with `query` to find the operation, then `get_operation_details` for exact parameters. **Never guess parameter names or types.**++5. **Verify connections**: Call `list_connections` filtered by each connector. Confirm Connected status.++6. **Resolve dynamic values**: For params with `dynamicValues`/`dynamicTree` annotations, call `invoke_operation` to get actual values (Teams channels, SharePoint sites, etc.).++7. **Review with user**: Present the flow design. Use AskUserQuestion to confirm trigger, actions, and connections before creating.++8. **Generate definition**: Build following all rules:+ - Always declare `$authentication` (SecureObject) and `$connections` (Object) parameters+ - Use correct action type: `OpenApiConnection` or `OpenApiConnectionWebhook` (from `get_operation_details`)+ - Do NOT include `authentication` in action inputs+ - Use `Embedded` source in connection references+ - HTTP Request triggers require Premium; prefer `Button` kind++9. **Validate**: Call `validate_flow` (and optionally `preflight_flow`) to pre-check. For expressions, look up syntax with `get_expression_help`.++10. **Create**: Call `create_flow` in Stopped state. Report ID and name.++11. **Optionally publish**: Ask if user wants to enable. If yes, call `publish_flow`. For later one-off tweaks, use `edit_flow` (surgical) rather than resending the whole definition.diff --git a/plugins/power-automate/skills/debug-flow/SKILL.md b/plugins/power-automate/skills/debug-flow/SKILL.mdnew file mode 100644index 000000000..5cd590d18--- /dev/null+++ b/plugins/power-automate/skills/debug-flow/SKILL.md@@ -0,0 +1,85 @@+---+name: debug-flow+description: Debug a failed Power Automate flow run. Use when a flow failed, has errors, or the user wants to troubleshoot a run.+user-invocable: true+argument-hint: "[flow-id] [run-id]"+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Debug a Failed Flow Run++You are helping the user debug a failed Power Automate flow run.++## Tools++This skill uses the **FlowAgent MCP tools**. Clients surface them with a+client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.+If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.++| Tool | Purpose |+|------|---------|+| `list_flows` | Find flows by name (use `name` param for search) |+| `get_run_history` | Get recent runs for a flow |+| `diagnose_run` | One-shot: classify failed actions with remediations |+| `get_run_details` | Get details for a specific run |+| `get_run_actions` | Get action-level execution trace |+| `get_run_action_repetitions` | Iteration-level detail for a loop (which iteration failed — pass an action **inside** the loop) |+| `get_flow` | Get flow definition for context |+| `get_operation_details` | Confirm the correct action type / parameters |+| `edit_flow` | Apply a surgical fix to one action/parameter |+| `update_flow` | Replace the whole definition (large rewrites) |+| `run_flow` | Re-run after fix (use `wait: true` to see result) |+| `resubmit_run` / `cancel_run` | Resubmit a fixed run / cancel a stuck one |++## Steps++1. **Identify the flow and run**+ - Parse `$ARGUMENTS` for flow ID and optional run ID.+ - If no flow ID, call `list_flows` with `name` param to search. Ask user to pick if ambiguous.+ - If no run ID, call `get_run_history` and find the most recent failed run.+ - Present recent runs in a table: Run ID | Status | Start Time | Error++2. **Fast triage with `diagnose_run`**+ - Call `diagnose_run` for the run — it returns the failed/timed-out actions already classified with a remediation each. Use this as the starting point.+ - For deeper analysis, also fetch (in parallel): `get_run_actions` (full trace) and `get_flow` (definition context). For a failed loop, call `get_run_action_repetitions` on an action **inside** the loop to find the failing iteration.++3. **Analyze failures**+ - Identify actions with status != "Succeeded"+ - Trace the `runAfter` dependency chain to separate root cause from cascading failures:+ - **Root cause**: action whose dependencies all Succeeded but it failed+ - **Cascading**: actions skipped because a dependency failed+ - Report root cause actions with: name, type, error code, error message++4. **Root cause classification**+ - **Connection errors** (`AuthorizationFailed`, `ConnectionNotFound`, `InvokerConnectionOverrideFailed`): Suggest re-auth or fix connection source to Embedded+ - **Expression errors** (`ExpressionEvaluationFailed`, `InvalidTemplate`): Show the expression, explain what's wrong, suggest fix+ - **API/External errors** (401/403/404/429/500+): Explain the HTTP error, check connector status+ - **Parameter errors** (`WorkflowOperationParametersRuntimeMissingValue`): Missing/empty required parameter. Add null guard: `@if(empty(...), 'default', ...)`+ - **Timeout** (`ActionTimedOut`): Suggest retry policy or splitting the operation+ - **Type mismatch** (`InvalidOpenApiConnectionOperationType`): Wrong action type. Call `get_operation_details` to find correct type.++5. **Suggest fix**+ - Provide a specific fix with code/expression changes.+ - If the fix is a definition change, offer to apply it with `edit_flow` (surgical, one action/parameter) — fall back to `update_flow` only for large rewrites.++6. **Re-test**+ - Offer to call `run_flow` with `wait: true` to verify the fix works (or `resubmit_run` to retry the original run with its trigger inputs).+ - Report the result: Succeeded/Failed with action details.++## Output Format++### Diagnosis Summary+- **Flow**: [name] ([ID])+- **Run**: [run ID] | [start time] | Status: **[status]**++### Failed Actions+| # | Action | Status | Error Code | Error Message |+|---|--------|--------|------------|---------------|++### Root Cause+[Classification]: [Explanation]++### Fix+[Step-by-step fix with code]diff --git a/plugins/power-automate/skills/diagnose-flow/SKILL.md b/plugins/power-automate/skills/diagnose-flow/SKILL.mdnew file mode 100644index 000000000..832c61eea--- /dev/null+++ b/plugins/power-automate/skills/diagnose-flow/SKILL.md@@ -0,0 +1,57 @@+---+name: diagnose-flow+description: Deep autonomous diagnosis of a failed flow run. Provide environment, flow, and run IDs. Use when the user asks to diagnose or deeply investigate a specific failed flow run.+user-invocable: true+argument-hint: "<env-id> <flow-id> <run-id>"+context: fork+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Deep Flow Diagnostic Agent++You are an autonomous diagnostic agent. Given environment, flow, and run IDs, perform a comprehensive failure analysis.++## Input++Parse `$ARGUMENTS` for: environment ID, flow ID, run ID.++## Tools++This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients+surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in+Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent+MCP server.++## Workflow++1. **Triage with `diagnose_run`**, then gather full context in parallel:+ - `diagnose_run` — classified failed/timed-out actions with a remediation each (start here)+ - `get_run_details` for overall run status+ - `get_run_actions` for the full action-level execution trace+ - `get_flow` for definition context+ - For a failed loop, `get_run_action_repetitions` on an action **inside** the loop (the container returns none) to find the failing iteration++2. **Build execution graph**: Map each action's `runAfter` dependencies. Identify parallel branches.++3. **Identify failed actions**: Filter for status != Succeeded. Classify each as:+ - **Root failure**: dependencies all Succeeded but this action failed+ - **Cascading skip**: skipped because a dependency failed++4. **Analyze each root failure** against common patterns:+ - Authorization/Connection errors+ - Expression evaluation failures+ - HTTP 4xx/5xx from external services+ - Timeout errors+ - Parameter validation failures (empty required fields, wrong enum values)+ - Action type mismatches (OpenApiConnection vs OpenApiConnectionWebhook)++5. **Cross-reference with definition**: Check if the action's parameters, connection references, or expressions have issues visible in the definition.++6. **Write diagnosis report** with:+ - Execution timeline+ - Root cause identification+ - Specific fix with code changes+ - Confidence level (high/medium/low)++7. **Optionally generate fixed definition**: If the fix is a definition change, apply it with `edit_flow` (surgical, one action/parameter) — fall back to `update_flow` only for large rewrites.diff --git a/plugins/power-automate/skills/manage-desktop-flows/SKILL.md b/plugins/power-automate/skills/manage-desktop-flows/SKILL.mdnew file mode 100644index 000000000..dfdaeec4d--- /dev/null+++ b/plugins/power-automate/skills/manage-desktop-flows/SKILL.md@@ -0,0 +1,39 @@+---+name: manage-desktop-flows+description: Manage and run Power Automate Desktop (RPA) flows and machine groups. Use when the user asks about desktop flows, RPA, or machine groups.+user-invocable: true+argument-hint: "[environment-id]"+allowed-tools: Bash, Read, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Desktop Flow Manager++Manage Power Automate Desktop (RPA) flows, machine groups, and run sessions.++## Tools++This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients+surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in+Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent+MCP server.++| Tool | Purpose |+|------|---------|+| `list_desktop_flows` | Browse RPA flows (filter by `name`) |+| `run_desktop_flow` | Trigger with optional `machineGroup`, `body`, `timeout` |+| `list_machine_groups` | Browse machine infrastructure |++## Operations++### List Desktop Flows+Call `list_desktop_flows`. Present in table: Name | Status | Created | Modified++### Run Desktop Flow+1. Call `list_desktop_flows` to find the flow (if name given, use `name` filter)+2. Optionally call `list_machine_groups` to target a specific group+3. Call `run_desktop_flow` with optional `machineGroup`, `body` (input data), `timeout`+4. Report: session status (Waiting/InProgress/Failed/Cancelled/Succeeded), outputs++### Machine Infrastructure+Call `list_machine_groups`. Present: Name | Type | Status | Machinesdiff --git a/plugins/power-automate/skills/manage-flows/SKILL.md b/plugins/power-automate/skills/manage-flows/SKILL.mdnew file mode 100644index 000000000..aba8dcc61--- /dev/null+++ b/plugins/power-automate/skills/manage-flows/SKILL.md@@ -0,0 +1,55 @@+---+name: manage-flows+description: Manage flow lifecycle - publish, test, batch operations, inventory reports. Use when the user asks to publish, test, batch manage, or get an inventory of flows.+user-invocable: true+argument-hint: "<operation> [flow-ids...]"+context: fork+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# Flow Lifecycle Manager++Autonomous agent for flow lifecycle operations: publish-and-test, batch operations, inventory reports.++## Tools++This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients+surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in+Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent+MCP server.++## Capabilities++### 1. Publish-and-Test Cycle+1. Call `publish_flow` to enable+2. Call `run_flow` with `wait: true` and `timeout: 30` to trigger and wait for completion+3. Report: pass/fail, duration, action statuses++### 2. Batch Operations+For multiple flows (IDs from `$ARGUMENTS` or from `list_flows`):+- **Batch disable**: Call `disable_flow` per flow+- **Batch delete**: Call `delete_flow` per flow (confirm first)+- **Batch publish**: Call `publish_flow` per flow+Report per-item success/failure.++### 3. Inventory Report+1. Call `list_environments` to get environments+2. Call `list_flows` on each (or specified) environment+3. Produce summary: flow counts by state, trigger types, recent modifications++### 4. Health Check+For each flow in an environment:+1. Call `get_run_history` with `top: 5`+2. Count Succeeded vs Failed runs+3. Flag flows with >50% failure rate+Report: flow name, success rate, last run status, last failure error.++### 5. Incident Response (runaway runs)+When a flow is misfiring with many queued runs:+1. Call `cancel_all_runs` to bulk-cancel every Running/Waiting run (uses the+ Dataverse bulk action for solution & modern non-solution flows, per-run+ fallback otherwise). Pass `turnOff: true` to also disable the flow while the+ root cause is fixed.+2. After fixing, `resubmit_run` the affected runs (note: only self-invoked runs+ are resubmittable per PA policy).diff --git a/plugins/power-automate/skills/route-environments/SKILL.md b/plugins/power-automate/skills/route-environments/SKILL.mdnew file mode 100644index 000000000..43b944d1d--- /dev/null+++ b/plugins/power-automate/skills/route-environments/SKILL.md@@ -0,0 +1,69 @@+---+name: route-environments+description: Manage environment resolution — check which environment you create flows in by default, list available environments, and set your working environment. Use when the user asks about environments, their default environment, where to create flows, or switching environments.+user-invocable: true+argument-hint: "[list|check|set]"+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment+model: opus+---++# Environment Resolution++You are helping the user understand and manage which Power Automate environment+they work in — where their flows are created, where they should build new ones,+and how to switch between environments.++> Uses the **FlowAgent MCP tools** (`resolve_environment`, `list_environments`,+> `set_current_env`, `get_current_env`).++## Step 1: Understand what the user needs++- **"Which environment am I in?"** → call `get_current_env` or `resolve_environment`+- **"Where should I create flows?"** → help them pick the right environment+- **"What environments do I have?"** → call `list_environments`+- **"Switch my environment"** → call `set_current_env`++## Step 2: List and explain environments++Call `list_environments` and present a clear summary:++| Environment | Type | Location | Notes |+|-------------|------|----------|-------|+| ... | Default / Developer / Sandbox / Production | ... | ... |++Help the user identify:+- **Default environment** — shared, not recommended for production flows+- **Developer environments** — personal, ideal for building and testing+- **Production/Sandbox** — team environments for deployed flows++## Step 3: Set the working environment++If the user wants to create flows in a specific environment, call+`set_current_env` with that environment ID. This pins all subsequent+FlowAgent operations to that environment (no need to pass `--env` each time).++**Recommendation for new users**: If they have a Developer environment, suggest+using that. If not, suggest they ask their admin to provision one, or use the+default environment for simple personal automations.++## Guidance++- `resolve_environment` shows how the environment resolves (routing → poll → fallback)+- `set_current_env` changes the session default — it does NOT change tenant-level routing+- Tenant-level environment routing (which env new makers land in by default) is+ configured at the admin level in `admin.powerplatform.microsoft.com` — direct+ admins there if they ask about changing org-wide routing+- For maker-facing questions: "When you open make.powerautomate.com, your default+ environment determines where new flows are created"++## Decision Tree++```+User asks about environments?+├── "Which environment am I in?" → get_current_env / resolve_environment+├── "What environments exist?" → list_environments with summary table+├── "Where should I build?" → Recommend Developer env; set_current_env+├── "Switch to X environment" → set_current_env+├── "How do I create a new environment?" → Direct to PPAC admin center+└── "What is environment routing?" → Explain: determines default for new makers+```diff --git a/plugins/power-automate/skills/setup/SKILL.md b/plugins/power-automate/skills/setup/SKILL.mdnew file mode 100644index 000000000..7133dd173--- /dev/null+++ b/plugins/power-automate/skills/setup/SKILL.md@@ -0,0 +1,131 @@+---+name: setup+description: Set up Power Automate CLI prerequisites. Use when the user is new, something isn't working, or they need help getting started.+user-invocable: true+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators+model: opus+---++# First-Time Setup Guide++You are helping a non-technical user get the Power Automate plugin working for the first time. Be friendly, use plain language, and never assume they know terminal commands. Walk them through each step one at a time.++## Step 1: Check Node.js++Run silently:+```bash+node --version 2>&1+```++- **If it works** (prints something like `v18.x.x` or higher): Tell them "Node.js is installed" and move on.+- **If it fails or version is below 18**: Tell them they need Node.js 18 or newer. Ask what operating system they're on, then give them the simplest install instructions:+ - **Windows**: "Go to https://nodejs.org, download the LTS version, and run the installer. Click Next through everything."+ - **Mac**: "Open Terminal and run: `brew install node`" (or direct them to nodejs.org)+ - After they've installed it, re-check with `node --version`.++## Step 2: Check Azure CLI++Run silently:+```bash+az --version 2>&1+```++- **If it works**: Tell them "Azure CLI is installed" and move on.+- **If it fails**: Tell them they need the Azure CLI. Ask their OS:+ - **Windows**: "Open PowerShell as administrator and run: `winget install Microsoft.AzureCLI`" or direct them to https://aka.ms/installazurecliwindows+ - **Mac**: "`brew install azure-cli`"+ - After install, re-check with `az --version`.++## Step 3: Azure Login++Check if they're already logged in:+```bash+az account show --output json 2>&1+```++- **If it works** (shows account info): Tell them who they're logged in as (show the `user.name` field) and ask if that's the right account.+- **If it fails**: Tell them "Let's sign you into Azure." Then run:+ ```bash+ az login+ ```+ This will open their browser. Tell them: "A browser window should open. Sign in with your work account — the one you use for Power Automate."+ After login completes, confirm it worked by running `az account show` again.++**Verify token access** — this catches permission issues early:+```bash+az account get-access-token --resource https://service.flow.microsoft.com --output json 2>&1+```+- **If it works**: Move on.+- **If it fails with "AADSTS"**: The user's account may not have Power Automate access. Tell them: "Your Azure account doesn't seem to have access to Power Automate. Check with your IT admin that you have a Power Automate license."+- **If it fails with other errors**: Show the error and suggest they contact IT support.++## Step 4: Check the FlowAgent tools are wired++The plugin talks to Power Automate through the **FlowAgent MCP server**, which is+launched automatically from the plugin's `.mcp.json` via a small Node+bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and imports+`server/mcp.mjs`.++- **If `flowagent-*` / `mcp__flowagent__*` tools appear in your tool list**: tell+ them "The Power Automate tools are connected" and move on.+- **If they're missing**: the MCP server isn't registered. Ask the user for+ confirmation before fixing:++ **Tell them**: "The FlowAgent MCP server isn't wired up yet. I can fix this+ by adding it to your `~/.copilot/mcp-config.json`. Shall I go ahead?"++ **If they confirm**, fix it:++ 1. **Locate the installed plugin's MCP bundle.** Run:+ ```bash+ node -e "const fs=require('fs'),p=require('path'),d=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','installed-plugins');try{const find=(dir)=>{for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory())try{const r=find(f);if(r)return r}catch{}if(e.name==='mcp.mjs'&&dir.split(p.sep).includes('power-automate'))return dir}return null};const r=find(d);if(r)console.log(JSON.stringify({found:true,serverDir:r,mcpMjs:p.join(r,'mcp.mjs')}));else console.log(JSON.stringify({found:false}))}catch(e){console.log(JSON.stringify({found:false,error:e.message}))}"+ ```++ 2. **If found**, read `~/.copilot/mcp-config.json`, add the `flowagent` MCP+ entry, and write it back:+ ```bash+ node -e "const fs=require('fs'),p=require('path');const cfgPath=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','mcp-config.json');let cfg;try{cfg=JSON.parse(fs.readFileSync(cfgPath,'utf8'))}catch{cfg={mcpServers:{}}};if(!cfg.mcpServers)cfg.mcpServers={};if(cfg.mcpServers.flowagent){console.log('already registered');process.exit(0)}const pluginDir=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','installed-plugins');const find=(dir)=>{for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory())try{const r=find(f);if(r)return r}catch{}if(e.name==='mcp.mjs'&&dir.split(p.sep).includes('power-automate'))return dir}return null};const srvDir=find(pluginDir);if(!srvDir){console.log('mcp.mjs not found');process.exit(1)}const mcpPath=p.join(srvDir,'mcp.mjs');cfg.mcpServers.flowagent={command:'node',args:[mcpPath]};fs.writeFileSync(cfgPath,JSON.stringify(cfg,null,2)+'\n');console.log('registered flowagent MCP at '+mcpPath)"+ ```++ 3. **Tell the user** to restart the agent (Copilot CLI: `/restart`, Claude Code:+ restart the process). After restart, `flowagent-*` tools should appear.++ 4. **If not found** (plugin not installed at all): tell them to install the+ plugin first:+ ```+ /plugin marketplace add microsoft/power-platform-skills+ /plugin install power-automate@power-platform-skills+ ```+ Then run `/setup` again.++## Step 5: Smoke Test++Verify everything works end-to-end by listing the user's environments:++- **Preferred**: call the `list_environments` tool.+- **If MCP tools aren't available**: run `node <path-to-plugin>/server/mcp.mjs`+ to confirm the bundled MCP server starts cleanly, then fix the plugin install+ or `.mcp.json` wiring before retrying.++- **If it returns environments**: Success! Tell them:+ - "Everything is working! Here are your Power Automate environments:"+ - Show the environments in a simple table (name, location).+ - If there are multiple, ask which one they mainly use and suggest setting it+ as the default (the `set_current_env` tool, or ask "set my default+ environment to <name>").+ - Tell them about the available skills:+ - **`/browse-flows`** — Browse your flows+ - **`/create-flow`** — Create a new flow+ - **`/debug-flow`** — Fix a broken flow+- **If it fails**: Check the error. Common issues:+ - Auth error → go back to Step 3+ - Tools not found → go back to Step 4+ - Network error → ask if they're behind a corporate proxy/VPN++## Tone Guidelines++- Use "we" language: "Let's check if Node.js is installed"+- Celebrate small wins: "Great, Node.js is ready!"+- Don't dump all steps at once — do one at a time and confirm before moving on+- If something fails, don't panic — explain what went wrong in plain English and what to do+- Never show raw JSON errors to the user without explaining what they mean