From 443fee4afd79ea8842df6245085bf73e6e95600b Mon Sep 17 00:00:00 2001 From: Giorgio Ughini Date: Mon, 10 Nov 2025 16:07:03 +0100 Subject: [PATCH 1/2] Add reasoning/thinking activities sample --- ShowReasoningSample/README.md | 121 +++ .../copilotstudio/acquireToken.js | 39 + ShowReasoningSample/copilotstudio/index.js | 14 + ShowReasoningSample/copilotstudio/settings.js | 35 + ShowReasoningSample/index.html | 110 +++ .../pkg/agents-copilotstudio-client/README.md | 127 +++ .../dist/package.json | 58 ++ .../dist/src/agentType.d.ts | 17 + .../dist/src/agentType.js | 22 + .../dist/src/agentType.js.map | 1 + .../dist/src/browser.mjs | 8 + .../dist/src/browser.mjs.map | 7 + .../dist/src/browser/os.d.ts | 7 + .../dist/src/browser/os.js | 8 + .../dist/src/browser/os.js.map | 1 + .../dist/src/connectionSettings.d.ts | 56 ++ .../dist/src/connectionSettings.js | 77 ++ .../dist/src/connectionSettings.js.map | 1 + .../dist/src/copilotStudioClient.d.ts | 71 ++ .../dist/src/copilotStudioClient.js | 193 +++++ .../dist/src/copilotStudioClient.js.map | 1 + .../src/copilotStudioConnectionSettings.d.ts | 27 + .../src/copilotStudioConnectionSettings.js | 7 + .../copilotStudioConnectionSettings.js.map | 1 + .../dist/src/copilotStudioWebChat.d.ts | 189 +++++ .../dist/src/copilotStudioWebChat.js | 310 ++++++++ .../dist/src/copilotStudioWebChat.js.map | 1 + .../dist/src/executeTurnRequest.d.ts | 18 + .../dist/src/executeTurnRequest.js | 22 + .../dist/src/executeTurnRequest.js.map | 1 + .../dist/src/index.d.ts | 8 + .../dist/src/index.js | 25 + .../dist/src/index.js.map | 1 + .../dist/src/powerPlatformCloud.d.ts | 77 ++ .../dist/src/powerPlatformCloud.js | 82 ++ .../dist/src/powerPlatformCloud.js.map | 1 + .../dist/src/powerPlatformEnvironment.d.ts | 24 + .../dist/src/powerPlatformEnvironment.js | 246 ++++++ .../dist/src/powerPlatformEnvironment.js.map | 1 + .../src/strategies/prebuiltBotStrategy.d.ts | 15 + .../src/strategies/prebuiltBotStrategy.js | 25 + .../src/strategies/prebuiltBotStrategy.js.map | 1 + .../src/strategies/publishedBotStrategy.d.ts | 15 + .../src/strategies/publishedBotStrategy.js | 25 + .../strategies/publishedBotStrategy.js.map | 1 + .../dist/src/strategies/strategy.d.ts | 7 + .../dist/src/strategies/strategy.js | 7 + .../dist/src/strategies/strategy.js.map | 1 + .../dist/tsconfig.tsbuildinfo | 1 + .../agents-copilotstudio-client/package.json | 58 ++ .../src/agentType.d.ts | 17 + .../src/agentType.js | 22 + .../src/agentType.js.map | 1 + .../src/agentType.ts | 18 + .../src/browser/os.d.ts | 7 + .../src/browser/os.js | 8 + .../src/browser/os.js.map | 1 + .../src/browser/os.ts | 8 + .../src/connectionSettings.d.ts | 56 ++ .../src/connectionSettings.js | 77 ++ .../src/connectionSettings.js.map | 1 + .../src/connectionSettings.ts | 101 +++ .../src/copilotStudioClient.d.ts | 71 ++ .../src/copilotStudioClient.js | 193 +++++ .../src/copilotStudioClient.js.map | 1 + .../src/copilotStudioClient.ts | 206 +++++ .../src/copilotStudioConnectionSettings.d.ts | 27 + .../src/copilotStudioConnectionSettings.js | 7 + .../copilotStudioConnectionSettings.js.map | 1 + .../src/copilotStudioConnectionSettings.ts | 36 + .../src/copilotStudioWebChat.d.ts | 189 +++++ .../src/copilotStudioWebChat.js | 310 ++++++++ .../src/copilotStudioWebChat.js.map | 1 + .../src/copilotStudioWebChat.ts | 411 ++++++++++ .../src/executeTurnRequest.d.ts | 18 + .../src/executeTurnRequest.js | 22 + .../src/executeTurnRequest.js.map | 1 + .../src/executeTurnRequest.ts | 23 + .../src/index.d.ts | 8 + .../agents-copilotstudio-client/src/index.js | 25 + .../src/index.js.map | 1 + .../agents-copilotstudio-client/src/index.ts | 8 + .../src/powerPlatformCloud.d.ts | 77 ++ .../src/powerPlatformCloud.js | 82 ++ .../src/powerPlatformCloud.js.map | 1 + .../src/powerPlatformCloud.ts | 78 ++ .../src/powerPlatformEnvironment.d.ts | 24 + .../src/powerPlatformEnvironment.js | 246 ++++++ .../src/powerPlatformEnvironment.js.map | 1 + .../src/powerPlatformEnvironment.ts | 277 +++++++ .../src/strategies/prebuiltBotStrategy.d.ts | 15 + .../src/strategies/prebuiltBotStrategy.js | 25 + .../src/strategies/prebuiltBotStrategy.js.map | 1 + .../src/strategies/prebuiltBotStrategy.ts | 37 + .../src/strategies/publishedBotStrategy.d.ts | 15 + .../src/strategies/publishedBotStrategy.js | 25 + .../strategies/publishedBotStrategy.js.map | 1 + .../src/strategies/publishedBotStrategy.ts | 37 + .../src/strategies/strategy.d.ts | 7 + .../src/strategies/strategy.js | 7 + .../src/strategies/strategy.js.map | 1 + .../src/strategies/strategy.ts | 8 + .../test/copilotStudioClient.test.d.ts | 1 + .../test/copilotStudioClient.test.js | 74 ++ .../test/copilotStudioClient.test.js.map | 1 + .../test/copilotStudioClient.test.ts | 79 ++ .../agents-copilotstudio-client/tsconfig.json | 14 + ShowReasoningSample/script.js | 376 +++++++++ ShowReasoningSample/styles.css | 727 ++++++++++++++++++ 109 files changed, 6284 insertions(+) create mode 100644 ShowReasoningSample/README.md create mode 100644 ShowReasoningSample/copilotstudio/acquireToken.js create mode 100644 ShowReasoningSample/copilotstudio/index.js create mode 100644 ShowReasoningSample/copilotstudio/settings.js create mode 100644 ShowReasoningSample/index.html create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/README.md create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/package.json create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser/os.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser/os.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser/os.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/connectionSettings.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/connectionSettings.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/connectionSettings.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioClient.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioClient.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioClient.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioConnectionSettings.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioConnectionSettings.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioConnectionSettings.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioWebChat.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioWebChat.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/copilotStudioWebChat.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/executeTurnRequest.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/executeTurnRequest.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/executeTurnRequest.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/index.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/index.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/index.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformCloud.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformCloud.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformCloud.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformEnvironment.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformEnvironment.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/powerPlatformEnvironment.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/prebuiltBotStrategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/prebuiltBotStrategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/prebuiltBotStrategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/publishedBotStrategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/publishedBotStrategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/publishedBotStrategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/strategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/strategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/strategies/strategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/dist/tsconfig.tsbuildinfo create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/package.json create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/agentType.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/agentType.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/agentType.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/agentType.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/browser/os.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/browser/os.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/browser/os.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/browser/os.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/connectionSettings.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/connectionSettings.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/connectionSettings.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/connectionSettings.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioClient.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioClient.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioClient.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioClient.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioConnectionSettings.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioConnectionSettings.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioConnectionSettings.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioConnectionSettings.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioWebChat.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioWebChat.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioWebChat.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/copilotStudioWebChat.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/executeTurnRequest.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/executeTurnRequest.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/executeTurnRequest.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/executeTurnRequest.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/index.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/index.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/index.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/index.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformCloud.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformCloud.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformCloud.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformCloud.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformEnvironment.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformEnvironment.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformEnvironment.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/powerPlatformEnvironment.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/prebuiltBotStrategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/prebuiltBotStrategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/prebuiltBotStrategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/prebuiltBotStrategy.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/publishedBotStrategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/publishedBotStrategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/publishedBotStrategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/publishedBotStrategy.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/strategy.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/strategy.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/strategy.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/src/strategies/strategy.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/test/copilotStudioClient.test.d.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/test/copilotStudioClient.test.js create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/test/copilotStudioClient.test.js.map create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/test/copilotStudioClient.test.ts create mode 100644 ShowReasoningSample/pkg/agents-copilotstudio-client/tsconfig.json create mode 100644 ShowReasoningSample/script.js create mode 100644 ShowReasoningSample/styles.css diff --git a/ShowReasoningSample/README.md b/ShowReasoningSample/README.md new file mode 100644 index 00000000..83d4102a --- /dev/null +++ b/ShowReasoningSample/README.md @@ -0,0 +1,121 @@ +# Showing Agent Reasoning in Custom UIs + +> **IMPORTANT!** This is the sample repository for [https://microsoft.github.io/mcscatblog/posts/show-reasoning-agents-sdk/](This article). Follow the article for a more detailed explanation. + +Render Anthropic reasoning traces from Microsoft 365 Copilot Studio agents inside your own UI. This README distills the companion article posted on MCS CAT blog. + +## Why Bubble Up Reasoning? +- Strengthen trust in automated or assisted decisions. +- Give operators visibility into multi-step, decision-heavy workflows. +- Help end users judge the suitability of an answer before acting on it. + +## Demo Scenario +The reference sample (static HTML + JS) simulates an organization triaging monday.com tickets with an Anthropic-enabled Copilot Studio agent. Submitting a new ticket shows incremental reasoning as typing activities, and near-duplicate tickets are merged automatically instead of duplicated. + +## Prerequisites +- Copilot Studio agent configured with an Anthropic model (Settings -> Agent model). +- Custom UI wired to the Microsoft 365 Agents SDK. +- Optional backend summarization endpoint to shorten verbose reasoning (recommended for UX). GPT-family models do not yet emit reasoning traces. + +## Core Flow +1. **Initialize the client** + ```js + import { CopilotStudioClient } from '@microsoft/agents-copilotstudio-client'; + import { acquireToken } from './acquireToken.js'; + import { settings } from './settings.js'; + + export const createCopilotClient = async () => { + const token = await acquireToken(settings); + return new CopilotStudioClient(settings, token); + }; + ``` +2. **Start a conversation** + ```js + const copilotClient = await createCopilotClient(); + let conversationId; + + for await (const act of copilotClient.startConversationAsync(true)) { + conversationId = act.conversation?.id ?? conversationId; + if (conversationId) break; + } + ``` +3. **Send a prompt** + ```js + const prompt = `Create the following ticket:\n\nTitle: ${shortTitle}\nDescription: ${longDescription}`; + const activityStream = copilotClient.askQuestionAsync(prompt, conversationId); + ``` +4. **Capture reasoning and answers** + ```js + for await (const activity of activityStream) { + if (!activity) continue; + + const activityType = activity.type?.toLowerCase(); + + if (activityType === 'typing' && activity.channelData?.streamType === 'informative') { + const streamKey = resolveStreamKey(activity); + const previousActivity = streamLastActivity.get(streamKey); + + if (previousActivity && isContinuationOfPrevious(previousActivity, activity)) { + streamLastActivity.set(streamKey, activity); + continue; + } + + await flushActivity(previousActivity, false); + streamLastActivity.set(streamKey, activity); + continue; + } + + if (activityType === 'message') { + agentMessages.push(activity.text); + continue; + } + } + ``` + +### Detect Informative Typing +```js +const isReasoningTyping = (activity) => + (activity?.type || '').toLowerCase() === 'typing' && + activity?.channelData?.streamType === 'informative'; +``` + +## Summarize Long Thoughts +Reasoning chunks can be lengthy. Capture completed thoughts and optionally POST them to a backend summarizer: +```js +async function summarizeSafely(text) { + try { + const res = await fetch('/api/summarize', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text }) + }); + const { summary } = await res.json(); + return summary.trim(); + } catch { + return null; + } +} +``` +Keep API keys server-side and apply rate limiting. The sample UI exposes an input control so end users can supply their summarizer key during demos. + +## UI Pattern Tips +- Show a calm, rotating status label once users submit a ticket (for example, "Reviewing possible options..."). +- Keep the spinner visible while informative typing events are active. +- Prepend the newest summarized reasoning to the top, keeping the latest five items. +- Add a subtle entrance animation and collapse the panel once the final answer arrives, with an optional "Show details" toggle. + +## Summary Checklist +1. Switch your agent to an Anthropic model. +2. Iterate the Microsoft 365 Agents SDK activity stream. +3. Detect reasoning via `type === 'typing'` and `channelData.streamType === 'informative'`. +4. Group reasoning chunks by `channelData.streamId`. +5. Flush pending reasoning when you receive the final message. +6. Optionally summarize server-side to protect secrets. +7. Render a compact Thinking panel with recent updates. + +## Try It Yourself +- Clone the reference implementation. +- Configure Copilot Studio with an Anthropic model. +- Run the sample locally, observe informative typing streams, and integrate your summarizer. + +Questions or feedback on the pattern are welcome. diff --git a/ShowReasoningSample/copilotstudio/acquireToken.js b/ShowReasoningSample/copilotstudio/acquireToken.js new file mode 100644 index 00000000..e9914040 --- /dev/null +++ b/ShowReasoningSample/copilotstudio/acquireToken.js @@ -0,0 +1,39 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +export async function acquireToken (settings) { + const msalInstance = new window.msal.PublicClientApplication({ + auth: { + clientId: settings.appClientId, + authority: `https://login.microsoftonline.com/${settings.tenantId}`, + }, + }) + + await msalInstance.initialize() + const loginRequest = { + scopes: ['https://api.powerplatform.com/.default'], + redirectUri: window.location.origin, + } + + // When there are not accounts or the acquireTokenSilent fails, + // it will fall back to loginPopup. + try { + const accounts = await msalInstance.getAllAccounts() + if (accounts.length > 0) { + const response = await msalInstance.acquireTokenSilent({ + ...loginRequest, + account: accounts[0], + }) + return response.accessToken + } + } catch (e) { + if (!(e instanceof window.msal.InteractionRequiredAuthError)) { + throw e + } + } + + const response = await msalInstance.loginPopup(loginRequest) + return response.accessToken +} \ No newline at end of file diff --git a/ShowReasoningSample/copilotstudio/index.js b/ShowReasoningSample/copilotstudio/index.js new file mode 100644 index 00000000..c11b1d06 --- /dev/null +++ b/ShowReasoningSample/copilotstudio/index.js @@ -0,0 +1,14 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +import { CopilotStudioClient } from '@microsoft/agents-copilotstudio-client' + +import { acquireToken } from './acquireToken.js' +import { settings } from './settings.js' + +export const createCopilotClient = async () => { + const token = await acquireToken(settings) + return new CopilotStudioClient(settings, token) +} \ No newline at end of file diff --git a/ShowReasoningSample/copilotstudio/settings.js b/ShowReasoningSample/copilotstudio/settings.js new file mode 100644 index 00000000..91c6bb70 --- /dev/null +++ b/ShowReasoningSample/copilotstudio/settings.js @@ -0,0 +1,35 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ + +// This file emulates the process object in node. +// rename this file to settings.js before running this test sample +import { ConnectionSettings } from '@microsoft/agents-copilotstudio-client' + +// Flag to enable debug mode, which will store the debug information in localStorage. +// Copilot Studio Client uses the "debug" library for logging (https://github.com/debug-js/debug?tab=readme-ov-file#browser-support). +window.localStorage.debug = 'copilot-studio-client' + +export const settings = new ConnectionSettings({ + // App ID of the App Registration used to log in, this should be in the same tenant as the Copilot. + appClientId: 'APP-REGISTRATION-CLIENT-ID-HERE', + // Tenant ID of the App Registration used to log in, this should be in the same tenant as the Copilot. + tenantId: 'YOUR-TENANT-ID-HERE', + // Authority endpoint for the Azure AD login. Default is 'https://login.microsoftonline.com'. + authority: 'https://login.microsoftonline.com', + // Environment ID of the environment with the Copilot Studio App. + environmentId: undefined, + // Schema Name of the Copilot to use. + agentIdentifier: undefined, + // PowerPlatformCloud enum key. + cloud: undefined, + // Power Platform API endpoint to use if Cloud is configured as "Other". + customPowerPlatformCloud: undefined, + // AgentType enum key. + copilotAgentType: undefined, + // URL used to connect to the Copilot Studio service. + directConnectUrl: "YOUR-DIRECT-CONNECT-URL-HERE", + // Flag to use the "x-ms-d2e-experimental" header URL on subsequent calls to the Copilot Studio service. + useExperimentalEndpoint: false +}) \ No newline at end of file diff --git a/ShowReasoningSample/index.html b/ShowReasoningSample/index.html new file mode 100644 index 00000000..5bb1b2b5 --- /dev/null +++ b/ShowReasoningSample/index.html @@ -0,0 +1,110 @@ + + + + + + Next-Gen Incident Desk + + + + + + + + +
+
+
+
+
+
+ +
+
+ PP + PPCC Ticket Portal +
+ Raise a Ticket +
+ +
+
+
+

Hyper-intelligent ticketing, one agent away.

+

+ Feed our AI-native ITSM engine and let it unravel the root cause, urgency, + and best responder in seconds thanks to Copilot Studio. Craft your + description, we decode the rest. +

+ Submit an Issue +
+ +
+ +
+
+
+

Open a new support request

+

+ Keep the title sharp. Use the long description to narrate the full + story – our Copilot Studio Agent will ingests it to extract signals, timelines, + stakeholders, and impact automatically. +

+
+
+ + + + + +
+
+
+
+
+ + + + + + + diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/README.md b/ShowReasoningSample/pkg/agents-copilotstudio-client/README.md new file mode 100644 index 00000000..cc86f388 --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/README.md @@ -0,0 +1,127 @@ +# @microsoft/agents-copilotstudio-client + +## Overview + +The `@microsoft/agents-copilotstudio-client` package allows you to interact with Copilot Studio Agents using the Direct Engine Protocol. This client library is designed to facilitate communication with agents, enabling seamless integration and interaction within your JavaScript or TypeScript applications. + +This package provides exports for CommonJS and ES6 modules, and also a bundle to be used in the browser. + +> [!NOTE] +> The Client needs to be initialized with a valid JWT Token. + +## Installation + +To install the package, use npm or yarn: + +```sh +npm install @microsoft/agents-copilotstudio-client +``` + +### Prerequisite + +To use this library, you will need the following: + +1. An Agent Created in Microsoft Copilot Studio. +1. Ability to Create or Edit an Application Identity in Azure + 1. (Option 1) for a Public Client/Native App Registration or access to an existing registration (Public Client/Native App) that has the **CopilotStudio.Copilot.Invoke API Delegated Permission assigned**. + 1. (Option 2) for a Confidential Client/Service Principal App Registration or access to an existing App Registration (Confidential Client/Service Principal) with the **CopilotStudio.Copilot.Invoke API Application Permission assigned**. + +### Create a Agent in Copilot Studio + +1. Create or open an Agent in [Copilot Studio](https://copilotstudio.microsoft.com) + 1. Make sure that the Copilot is Published + 1. Goto Settings => Advanced => Metadata and copy the following values. You will need them later: + 1. Schema name - this is the 'unique name' of your agent inside this environment. + 1. Environment Id - this is the ID of the environment that contains the agent. + +### Create an Application Registration in Entra ID to support user authentication to Copilot Studio + +> [!IMPORTANT] +> If you are using this client from a service, you will need to exchange the user token used to login to your service for a token for your agent hosted in copilot studio. This is called a On Behalf Of (OBO) authentication token. You can find more information about this authentication flow in [Entra Documentation](https://learn.microsoft.com/entra/msal/dotnet/acquiring-tokens/web-apps-apis/on-behalf-of-flow). +> +> When using this method, you will need to add the `CopilotStudio.Copilots.Invoke` _delegated_ API permision to your application registration's API privilages + +### Add the CopilotStudio.Copilots.Invoke permissions to your Application Registration in Entra ID to support User or Service Principal authentication to Copilot Studio + +This step will require permissions to edit application identities in your Azure tenant. + +1. In your azure application + 1. Goto Manage + 1. Goto API Permissions + 1. Click Add Permission + 1. In the side pannel that appears, Click the tab `API's my organization uses` + 1. Search for `Power Platform API`. + 1. _If you do not see `Power Platform API` see the note at the bottom of this section._ + 1. For _User Interactive Permissions_, choose `Delegated Permissions` + 1. In the permissions list choose `CopilotStudio` and Check `CopilotStudio.Copilots.Invoke` + 1. Click `Add Permissions` + 1. For _Service Principal/Confidential Client_, choose `Application Permissions` + 1. In the permissions list choose `CopilotStudio` and Check `CopilotStudio.Copilots.Invoke` + 1. Click `Add Permissions` + 1. An appropriate administrator must then `Grant Admin consent for copilotsdk` before the permissions will be available to the application. + 1. Close Azure Portal + +> [!TIP] +> If you do not see `Power Platform API` in the list of API's your organization uses, you need to add the Power Platform API to your tenant. To do that, goto [Power Platform API Authentication](https://learn.microsoft.com/power-platform/admin/programmability-authentication-v2#step-2-configure-api-permissions) and follow the instructions on Step 2 to add the Power Platform Admin API to your Tenant + +## How-to use + +The Copilot Client is configured using the `ConnectionSettings` class and a `jwt token` to authenticate to the service. +The `ConnectionSettings` class can be configured using either instantiating the class or loading the settings from a `.env`. + +#### Using the default class + +There are a few options for configuring the `ConnectionSettings` class. The following are the most _common_ options: + +Using Environment ID and Copilot Studio Agent Schema Name: + +```ts +const settings: ConnectionSettings = { + environmentId: "your-environment-id", + agentIdentifier: "your-agent-schema-name", +}; +``` + +Using the DirectConnectUrl: + +```ts +const settings: ConnectionSettings = { + directConnectUrl: "https://direct.connect.url", +}; +``` + +> [!NOTE] +> By default, it's assumed your agent is in the Microsoft Public Cloud. If you are using a different cloud, you will need to set the `Cloud` property to the appropriate value. See the `PowerPlatformCloud` enum for the supported values + +#### Using the .env file + +You can use the `loadCopilotStudioConnectionSettingsFromEnv` function to load the `ConnectionSettings` from a `.env` file. + +The following are the most _common_ options: + +Using Environment ID and Copilot Studio Agent Schema Name: + +``` +environmentId=your-environment-id +agentIdentifier=your-agent-schema-name +``` + +Using the DirectConnectUrl: + +``` +directConnectUrl=https://direct.connect.url +``` + +#### Example of how to create a Copilot client + +```ts +const createClient = async (): Promise => { + const settings = loadCopilotStudioConnectionSettingsFromEnv() + const token = await acquireToken(settings) + const copilotClient = new CopilotStudioClient(settings, token) + return copilotClient +} +const copilotClient = await createClient() +const replies = await copilotClient.startConversationAsync(true) +replies.forEach(r => console.log(r.text)) +``` diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/package.json b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/package.json new file mode 100644 index 00000000..b9c16ff5 --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/package.json @@ -0,0 +1,58 @@ +{ + "name": "@microsoft/agents-copilotstudio-client", + "version": "0.1.0", + "homepage": "https://github.com/microsoft/Agents-for-js", + "repository": { + "type": "git", + "url": "git+https://github.com/microsoft/Agents-for-js.git" + }, + "author": { + "name": "Microsoft", + "email": "agentssdk@microsoft.com", + "url": "https://aka.ms/Agents" + }, + "description": "Microsoft Copilot Studio Client for JavaScript. Copilot Studio Client.", + "keywords": [ + "Agents", + "copilotstudio", + "powerplatform" + ], + "main": "dist/src/index.js", + "types": "dist/src/index.d.ts", + "browser": { + "os": "./src/browser/os.ts", + "crypto": "./src/browser/crypto.ts" + }, + "scripts": { + "build:browser": "esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts" + }, + "dependencies": { + "@microsoft/agents-activity": "file:../agents-activity", + "eventsource-client": "^1.2.0", + "rxjs": "7.8.2", + "uuid": "^11.1.0" + }, + "license": "MIT", + "files": [ + "README.md", + "dist/src", + "src", + "package.json" + ], + "exports": { + ".": { + "types": "./dist/src/index.d.ts", + "import": { + "browser": "./dist/src/browser.mjs", + "default": "./dist/src/index.js" + }, + "require": { + "default": "./dist/src/index.js" + } + }, + "./package.json": "./package.json" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.d.ts b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.d.ts new file mode 100644 index 00000000..198759ac --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +/** + * Enum representing the type of agent. + */ +export declare enum AgentType { + /** + * Represents a published agent. + */ + Published = "Published", + /** + * Represents a prebuilt agent. + */ + Prebuilt = "Prebuilt" +} diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js new file mode 100644 index 00000000..8c99d48f --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js @@ -0,0 +1,22 @@ +"use strict"; +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AgentType = void 0; +/** + * Enum representing the type of agent. + */ +var AgentType; +(function (AgentType) { + /** + * Represents a published agent. + */ + AgentType["Published"] = "Published"; + /** + * Represents a prebuilt agent. + */ + AgentType["Prebuilt"] = "Prebuilt"; +})(AgentType || (exports.AgentType = AgentType = {})); +//# sourceMappingURL=agentType.js.map \ No newline at end of file diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js.map b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js.map new file mode 100644 index 00000000..0a2de4ea --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/agentType.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agentType.js","sourceRoot":"","sources":["../../src/agentType.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;GAEG;AACH,IAAY,SASX;AATD,WAAY,SAAS;IACnB;;OAEG;IACH,oCAAuB,CAAA;IACvB;;OAEG;IACH,kCAAqB,CAAA;AACvB,CAAC,EATW,SAAS,yBAAT,SAAS,QASpB"} \ No newline at end of file diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs new file mode 100644 index 00000000..d7ea20a7 --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs @@ -0,0 +1,8 @@ +var My=Object.create;var si=Object.defineProperty;var ky=Object.getOwnPropertyDescriptor;var Fy=Object.getOwnPropertyNames;var Ry=Object.getPrototypeOf,Zy=Object.prototype.hasOwnProperty;var Pr=(e,r)=>()=>(e&&(r=e(e=0)),r);var d=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),qr=(e,r)=>{for(var t in r)si(e,t,{get:r[t],enumerable:!0})},ui=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Fy(r))!Zy.call(e,i)&&i!==t&&si(e,i,{get:()=>r[i],enumerable:!(n=ky(r,i))||n.enumerable});return e},q=(e,r,t)=>(ui(e,r,"default"),t&&ui(t,r,"default")),ke=(e,r,t)=>(t=e!=null?My(Ry(e)):{},ui(r||!e||!e.__esModule?si(t,"default",{value:e,enumerable:!0}):t,e)),Fe=e=>ui(si({},"__esModule",{value:!0}),e);var Vl=d(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.AgentType=void 0;var Dl;(function(e){e.Published="Published",e.Prebuilt="Prebuilt"})(Dl||(ci.AgentType=Dl={}))});var ls={};qr(ls,{AgentType:()=>cs});var cs,li=Pr(()=>{"use strict";cs=(t=>(t.Published="Published",t.Prebuilt="Prebuilt",t))(cs||{})});var fs={};qr(fs,{PowerPlatformCloud:()=>ds});var ds,di=Pr(()=>{"use strict";ds=(O=>(O.Unknown="Unknown",O.Exp="Exp",O.Dev="Dev",O.Test="Test",O.Preprod="Preprod",O.FirstRelease="FirstRelease",O.Prod="Prod",O.Gov="Gov",O.High="High",O.DoD="DoD",O.Mooncake="Mooncake",O.Ex="Ex",O.Rx="Rx",O.Prv="Prv",O.Local="Local",O.GovFR="GovFR",O.Other="Other",O))(ds||{})});var $l=d(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.loadCopilotStudioConnectionSettingsFromEnv=at.ConnectionSettings=void 0;var vs=(li(),Fe(ls)),ps=(di(),Fe(fs)),hs=class{constructor(){this.appClientId="",this.tenantId="",this.authority="",this.environmentId="",this.agentIdentifier="",this.useExperimentalEndpoint=!1}},fi=class extends hs{constructor(r){var t,n;if(super(),!r)return;let i=(t=r.cloud)!==null&&t!==void 0?t:ps.PowerPlatformCloud.Prod,o=(n=r.copilotAgentType)!==null&&n!==void 0?n:vs.AgentType.Published,a=r.authority&&r.authority.trim()!==""?r.authority:"https://login.microsoftonline.com";if(!Object.values(ps.PowerPlatformCloud).includes(i))throw new Error(`Invalid PowerPlatformCloud: '${i}'. Supported values: ${Object.values(ps.PowerPlatformCloud).join(", ")}`);if(!Object.values(vs.AgentType).includes(o))throw new Error(`Invalid AgentType: '${o}'. Supported values: ${Object.values(vs.AgentType).join(", ")}`);Object.assign(this,{...r,cloud:i,copilotAgentType:o,authority:a})}};at.ConnectionSettings=fi;var Uy=()=>{var e,r,t,n,i,o;return new fi({appClientId:(e=process.env.appClientId)!==null&&e!==void 0?e:"",tenantId:(r=process.env.tenantId)!==null&&r!==void 0?r:"",authority:(t=process.env.authorityEndpoint)!==null&&t!==void 0?t:"https://login.microsoftonline.com",environmentId:(n=process.env.environmentId)!==null&&n!==void 0?n:"",agentIdentifier:(i=process.env.agentIdentifier)!==null&&i!==void 0?i:"",cloud:process.env.cloud,customPowerPlatformCloud:process.env.customPowerPlatformCloud,copilotAgentType:process.env.copilotAgentType,directConnectUrl:process.env.directConnectUrl,useExperimentalEndpoint:((o=process.env.useExperimentalEndpoint)===null||o===void 0?void 0:o.toLowerCase())==="true"})};at.loadCopilotStudioConnectionSettingsFromEnv=Uy});var Wl=d(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});var Cn=class extends Error{constructor(r,t){super(r),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ms(e){}function Ly(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:r=ms,onError:t=ms,onRetry:n=ms,onComment:i}=e,o="",a=!0,u,l="",s="";function f(y){let _=a?y.replace(/^\xEF\xBB\xBF/,""):y,[O,R]=Ny(`${o}${_}`);for(let V of O)v(V);o=R,a=!1}function v(y){if(y===""){b();return}if(y.startsWith(":")){i&&i(y.slice(y.startsWith(": ")?2:1));return}let _=y.indexOf(":");if(_!==-1){let O=y.slice(0,_),R=y[_+1]===" "?2:1,V=y.slice(_+R);m(O,V,y);return}m(y,"",y)}function m(y,_,O){switch(y){case"event":s=_;break;case"data":l=`${l}${_} +`;break;case"id":u=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):t(new Cn(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:O}));break;default:t(new Cn(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:_,line:O}));break}}function b(){l.length>0&&r({id:u,event:s||void 0,data:l.endsWith(` +`)?l.slice(0,-1):l}),u=void 0,l="",s=""}function g(y={}){o&&y.consume&&v(o),a=!0,u=void 0,l="",s="",o=""}return{feed:f,reset:g}}function Ny(e){let r=[],t="",n=0;for(;n{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});var zy=Wl(),ys="connecting",Bl="open",hi="closed",pi=()=>{};function Dy(e,{getStream:r}){let t=typeof e=="string"||e instanceof URL?{url:e}:e,{onMessage:n,onComment:i=pi,onConnect:o=pi,onDisconnect:a=pi,onScheduleReconnect:u=pi}=t,{fetch:l,url:s,initialLastEventId:f}=Vy(t),v={...t.headers},m=[],b=n?[n]:[],g=W=>b.forEach(we=>we(W)),y=zy.createParser({onEvent:xy,onRetry:Ty,onComment:i}),_,O=s.toString(),R=new AbortController,V=f,G=2e3,ye,B=hi;return wr(),{close:Pn,connect:wr,[Symbol.iterator]:()=>{throw new Error("EventSource does not support synchronous iteration. Use `for await` instead.")},[Symbol.asyncIterator]:ss,get lastEventId(){return V},get url(){return O},get readyState(){return B}};function wr(){_||(B=ys,R=new AbortController,_=l(s,Ey()).then(Ay).catch(W=>{_=null,!(W.name==="AbortError"||W.type==="aborted"||R.signal.aborted)&&Ll()}))}function Pn(){B=hi,R.abort(),y.reset(),clearTimeout(ye),m.forEach(W=>W())}function ss(){let W=[],we=[];function qn(){return new Promise(ne=>{let Se=we.shift();Se?ne({value:Se,done:!1}):W.push(ne)})}let ot=function(ne){let Se=W.shift();Se?Se({value:ne,done:!1}):we.push(ne)};function Sr(){for(b.splice(b.indexOf(ot),1);W.shift(););for(;we.shift(););}function jn(){let ne=W.shift();ne&&(ne({done:!0,value:void 0}),Sr())}return m.push(jn),b.push(ot),{next(){return B===hi?this.return():qn()},return(){return Sr(),Promise.resolve({done:!0,value:void 0})},throw(ne){return Sr(),Promise.reject(ne)},[Symbol.asyncIterator](){return this}}}function Ll(){u({delay:G}),!R.signal.aborted&&(B=ys,ye=setTimeout(wr,G))}async function Ay(W){o(),y.reset();let{body:we,redirected:qn,status:ot}=W;if(ot===204){a(),Pn();return}if(!we)throw new Error("Missing response body");qn&&(O=W.url);let Sr=r(we),jn=new TextDecoder,ne=Sr.getReader(),Se=!0;B=Bl;do{let{done:Nl,value:zl}=await ne.read();zl&&y.feed(jn.decode(zl,{stream:!Nl})),Nl&&(Se=!1,_=null,y.reset(),Ll(),a())}while(Se)}function xy(W){typeof W.id=="string"&&(V=W.id),g(W)}function Ty(W){G=W}function Ey(){let{mode:W,credentials:we,body:qn,method:ot,redirect:Sr,referrer:jn,referrerPolicy:ne}=t,Se={Accept:"text/event-stream",...v,...V?{"Last-Event-ID":V}:void 0};return{mode:W,credentials:we,body:qn,method:ot,redirect:Sr,referrer:jn,referrerPolicy:ne,headers:Se,cache:"no-store",signal:R.signal}}}function Vy(e){let r=e.fetch||globalThis.fetch;if(!$y(r))throw new Error("No fetch implementation provided, and one was not found on the global object.");if(typeof AbortController!="function")throw new Error("Missing AbortController implementation");let{url:t,initialLastEventId:n}=e;if(typeof t!="string"&&!(t instanceof URL))throw new Error("Invalid URL provided - must be string or URL instance");if(typeof n!="string"&&n!==void 0)throw new Error("Invalid initialLastEventId provided - must be string or undefined");return{fetch:r,url:t,initialLastEventId:n}}function $y(e){return typeof e=="function"}var Wy={getStream:Gy};function By(e){return Dy(e,Wy)}function Gy(e){if(!(e instanceof ReadableStream))throw new Error("Invalid stream, expected a web ReadableStream");return e}ut.CLOSED=hi;ut.CONNECTING=ys;ut.OPEN=Bl;ut.createEventSource=By});var Hl=d((bZ,Yl)=>{var st=1e3,ct=st*60,lt=ct*60,jr=lt*24,Yy=jr*7,Hy=jr*365.25;Yl.exports=function(e,r){r=r||{};var t=typeof e;if(t==="string"&&e.length>0)return Ky(e);if(t==="number"&&isFinite(e))return r.long?Qy(e):Jy(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Ky(e){if(e=String(e),!(e.length>100)){var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(r){var t=parseFloat(r[1]),n=(r[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*Hy;case"weeks":case"week":case"w":return t*Yy;case"days":case"day":case"d":return t*jr;case"hours":case"hour":case"hrs":case"hr":case"h":return t*lt;case"minutes":case"minute":case"mins":case"min":case"m":return t*ct;case"seconds":case"second":case"secs":case"sec":case"s":return t*st;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Jy(e){var r=Math.abs(e);return r>=jr?Math.round(e/jr)+"d":r>=lt?Math.round(e/lt)+"h":r>=ct?Math.round(e/ct)+"m":r>=st?Math.round(e/st)+"s":e+"ms"}function Qy(e){var r=Math.abs(e);return r>=jr?mi(e,r,jr,"day"):r>=lt?mi(e,r,lt,"hour"):r>=ct?mi(e,r,ct,"minute"):r>=st?mi(e,r,st,"second"):e+" ms"}function mi(e,r,t,n){var i=r>=t*1.5;return Math.round(e/t)+" "+n+(i?"s":"")}});var Jl=d((gZ,Kl)=>{function Xy(e){t.debug=t,t.default=t,t.coerce=l,t.disable=a,t.enable=i,t.enabled=u,t.humanize=Hl(),t.destroy=s,Object.keys(e).forEach(f=>{t[f]=e[f]}),t.names=[],t.skips=[],t.formatters={};function r(f){let v=0;for(let m=0;m{if(B==="%%")return"%";G++;let Pn=t.formatters[wr];if(typeof Pn=="function"){let ss=_[G];B=Pn.call(O,ss),_.splice(G,1),G--}return B}),t.formatArgs.call(O,_),(O.log||t.log).apply(O,_)}return y.namespace=f,y.useColors=t.useColors(),y.color=t.selectColor(f),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(b!==t.namespaces&&(b=t.namespaces,g=t.enabled(f)),g),set:_=>{m=_}}),typeof t.init=="function"&&t.init(y),y}function n(f,v){let m=t(this.namespace+(typeof v=="undefined"?":":v)+f);return m.log=this.log,m}function i(f){t.save(f),t.namespaces=f,t.names=[],t.skips=[];let v=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of v)m[0]==="-"?t.skips.push(m.slice(1)):t.names.push(m)}function o(f,v){let m=0,b=0,g=-1,y=0;for(;m"-"+v)].join(",");return t.enable(""),f}function u(f){for(let v of t.skips)if(o(f,v))return!1;for(let v of t.names)if(o(f,v))return!0;return!1}function l(f){return f instanceof Error?f.stack||f.message:f}function s(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Kl.exports=Xy});var Ql=d((ie,yi)=>{ie.formatArgs=r_;ie.save=t_;ie.load=n_;ie.useColors=e_;ie.storage=i_();ie.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ie.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function e_(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r_(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+yi.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;e.splice(1,0,r,"color: inherit");let t=0,n=0;e[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),e.splice(n,0,r)}ie.log=console.debug||console.log||(()=>{});function t_(e){try{e?ie.storage.setItem("debug",e):ie.storage.removeItem("debug")}catch{}}function n_(){let e;try{e=ie.storage.getItem("debug")||ie.storage.getItem("DEBUG")}catch{}return!e&&typeof process!="undefined"&&"env"in process&&(e=process.env.DEBUG),e}function i_(){try{return localStorage}catch{}}yi.exports=Jl()(ie);var{formatters:o_}=yi.exports;o_.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}});var dt=d(Cr=>{"use strict";var a_=Cr&&Cr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.Logger=void 0;Cr.debug=c_;var u_=a_(Ql()),s_=["info","warn","error","debug"],_i=class{constructor(r=""){this.loggers={},this.initializeLoggers(r)}initializeLoggers(r){for(let t of s_){let n=(0,u_.default)(`${r}:${t}`);n.color=this.getPlatformColor(t),this.loggers[t]=n}}getPlatformColor(r){return{node:{info:"2",warn:"3",error:"1",debug:"4"},browser:{info:"#33CC99",warn:"#CCCC33",error:"#CC3366",debug:"#0066FF"}}[typeof window!="undefined"?"browser":"node"][r]}info(r,...t){this.loggers.info(r,...t)}warn(r,...t){this.loggers.warn(r,...t)}error(r,...t){this.loggers.error(r,...t)}debug(r,...t){this.loggers.debug(r,...t)}};Cr.Logger=_i;function c_(e){return new _i(e)}});var Xl={};qr(Xl,{PrebuiltBotStrategy:()=>In});var In,_s=Pr(()=>{"use strict";In=class{constructor(r){this.API_VERSION="2022-03-01-preview";let{identifier:t,host:n}=r;this.baseURL=new URL(`/copilotstudio/prebuilt/authenticated/bots/${t}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(r){let t=new URL(this.baseURL.href);return t.pathname=`${t.pathname}/conversations`,r&&(t.pathname=`${t.pathname}/${r}`),t.href}}});var ed={};qr(ed,{PublishedBotStrategy:()=>An});var An,bs=Pr(()=>{"use strict";An=class{constructor(r){this.API_VERSION="2022-03-01-preview";let{schema:t,host:n}=r;this.baseURL=new URL(`/copilotstudio/dataverse-backed/authenticated/bots/${t}`,n),this.baseURL.searchParams.append("api-version",this.API_VERSION)}getConversationUrl(r){let t=new URL(this.baseURL.href);return t.pathname=`${t.pathname}/conversations`,r&&(t.pathname=`${t.pathname}/${r}`),t.href}}});var id={};qr(id,{getCopilotStudioConnectionUrl:()=>nd,getTokenAudience:()=>l_});function nd(e,r){var u,l,s,f,v,m;if((u=e.directConnectUrl)!=null&&u.trim()){if(ft.debug(`Using direct connection: ${e.directConnectUrl}`),!xn(e.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return e.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(ft.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${e.directConnectUrl}`),nd({...e,directConnectUrl:""},r)):d_(e.directConnectUrl,r).href}let t=(l=e.cloud)!=null?l:"Prod",n=(s=e.copilotAgentType)!=null?s:"Published";if(ft.debug(`Using cloud setting: ${t}`),ft.debug(`Using agent type: ${n}`),!((f=e.environmentId)!=null&&f.trim()))throw new Error("EnvironmentId must be provided");if(!((v=e.agentIdentifier)!=null&&v.trim()))throw new Error("AgentIdentifier must be provided");if(t==="Other")if((m=e.customPowerPlatformCloud)!=null&&m.trim())if(xn(e.customPowerPlatformCloud))ft.debug(`Using custom Power Platform cloud: ${e.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let i=f_(t,e.environmentId,e.customPowerPlatformCloud),a={Published:()=>new An({host:i,schema:e.agentIdentifier}),Prebuilt:()=>new In({host:i,identifier:e.agentIdentifier})}[n]().getConversationUrl(r);return ft.debug(`Generated Copilot Studio connection URL: ${a}`),a}function l_(e,r="Unknown",t="",n=""){var i,o;if(!n&&!(e!=null&&e.directConnectUrl)){if(r==="Other"&&!t)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!e&&r==="Unknown")throw new Error("Either settings or cloud must be provided");if(e&&e.cloud&&e.cloud!=="Unknown"&&(r=e.cloud),r==="Other")if(t&&xn(t))r="Other";else if(e!=null&&e.customPowerPlatformCloud&&xn(e.customPowerPlatformCloud))r="Other",t=e.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return t!=null||(t="api.unknown.powerplatform.com"),`https://${bi(r,t)}/.default`}else if(n||(n=(i=e==null?void 0:e.directConnectUrl)!=null?i:""),n&&xn(n)){if(rd(new URL(n))==="Unknown"){let a=(o=e==null?void 0:e.cloud)!=null?o:r;if(a==="Other"||a==="Unknown")throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(a!=="Unknown")return`https://${bi(a,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${bi(rd(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function xn(e){try{let r=e.startsWith("http")?e:`https://${e}`;return!!new URL(r)}catch{return!1}}function d_(e,r){let t=new URL(e);return t.searchParams.has("api-version")||t.searchParams.append("api-version","2022-03-01-preview"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.pathname.includes("/conversations")&&(t.pathname=t.pathname.substring(0,t.pathname.indexOf("/conversations"))),t.pathname=`${t.pathname}/conversations`,r&&(t.pathname=`${t.pathname}/${r}`),t}function f_(e,r,t){if(e==="Other"&&(!t||!t.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");t=t!=null?t:"api.unknown.powerplatform.com";let n=r.toLowerCase().replaceAll("-",""),i=v_(e),o=n.substring(0,n.length-i),a=n.substring(n.length-i);return new URL(`https://${o}.${a}.environment.${bi(e,t)}`)}function bi(e,r){switch(e){case"Local":return"api.powerplatform.localhost";case"Exp":return"api.exp.powerplatform.com";case"Dev":return"api.dev.powerplatform.com";case"Prv":return"api.prv.powerplatform.com";case"Test":return"api.test.powerplatform.com";case"Preprod":return"api.preprod.powerplatform.com";case"FirstRelease":case"Prod":return"api.powerplatform.com";case"GovFR":return"api.gov.powerplatform.microsoft.us";case"Gov":return"api.gov.powerplatform.microsoft.us";case"High":return"api.high.powerplatform.microsoft.us";case"DoD":return"api.appsplatform.us";case"Mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"Ex":return"api.powerplatform.eaglex.ic.gov";case"Rx":return"api.powerplatform.microsoft.scloud";case"Other":return r;default:throw new Error(`Invalid cluster category value: ${e}`)}}function v_(e){switch(e){case"FirstRelease":case"Prod":return 2;default:return 1}}function rd(e){switch(e.host.toLowerCase()){case"api.powerplatform.localhost":return"Local";case"api.exp.powerplatform.com":return"Exp";case"api.dev.powerplatform.com":return"Dev";case"api.prv.powerplatform.com":return"Prv";case"api.test.powerplatform.com":return"Test";case"api.preprod.powerplatform.com":return"Preprod";case"api.powerplatform.com":return"Prod";case"api.gov.powerplatform.microsoft.us":return"GovFR";case"api.high.powerplatform.microsoft.us":return"High";case"api.appsplatform.us":return"DoD";case"api.powerplatform.partner.microsoftonline.cn":return"Mooncake";default:return"Unknown"}}var td,ft,od=Pr(()=>{"use strict";li();td=ke(dt());di();_s();bs();ft=(0,td.debug)("copilot-studio:power-platform")});var Tn=d(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.getParsedType=D.ZodParsedType=D.objectUtil=D.util=void 0;var gs;(function(e){e.assertEqual=i=>{};function r(i){}e.assertIs=r;function t(i){throw new Error}e.assertNever=t,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(u=>typeof i[i[u]]!="number"),a={};for(let u of o)a[u]=i[u];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(gs||(D.util=gs={}));var ad;(function(e){e.mergeShapes=(r,t)=>({...r,...t})})(ad||(D.objectUtil=ad={}));D.ZodParsedType=gs.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var p_=e=>{switch(typeof e){case"undefined":return D.ZodParsedType.undefined;case"string":return D.ZodParsedType.string;case"number":return Number.isNaN(e)?D.ZodParsedType.nan:D.ZodParsedType.number;case"boolean":return D.ZodParsedType.boolean;case"function":return D.ZodParsedType.function;case"bigint":return D.ZodParsedType.bigint;case"symbol":return D.ZodParsedType.symbol;case"object":return Array.isArray(e)?D.ZodParsedType.array:e===null?D.ZodParsedType.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?D.ZodParsedType.promise:typeof Map!="undefined"&&e instanceof Map?D.ZodParsedType.map:typeof Set!="undefined"&&e instanceof Set?D.ZodParsedType.set:typeof Date!="undefined"&&e instanceof Date?D.ZodParsedType.date:D.ZodParsedType.object;default:return D.ZodParsedType.unknown}};D.getParsedType=p_});var gi=d(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ZodError=Ge.quotelessJson=Ge.ZodIssueCode=void 0;var ud=Tn();Ge.ZodIssueCode=ud.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 h_=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");Ge.quotelessJson=h_;var En=class e extends Error{get errors(){return this.issues}constructor(r){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=r}format(r){let t=r||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let u=n,l=0;for(;lt.message){let t={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];t[o]=t[o]||[],t[o].push(r(i))}else n.push(r(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};Ge.ZodError=En;En.create=e=>new En(e)});var ws=d(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var Q=gi(),Ir=Tn(),m_=(e,r)=>{let t;switch(e.code){case Q.ZodIssueCode.invalid_type:e.received===Ir.ZodParsedType.undefined?t="Required":t=`Expected ${e.expected}, received ${e.received}`;break;case Q.ZodIssueCode.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(e.expected,Ir.util.jsonStringifyReplacer)}`;break;case Q.ZodIssueCode.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ir.util.joinValues(e.keys,", ")}`;break;case Q.ZodIssueCode.invalid_union:t="Invalid input";break;case Q.ZodIssueCode.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ir.util.joinValues(e.options)}`;break;case Q.ZodIssueCode.invalid_enum_value:t=`Invalid enum value. Expected ${Ir.util.joinValues(e.options)}, received '${e.received}'`;break;case Q.ZodIssueCode.invalid_arguments:t="Invalid function arguments";break;case Q.ZodIssueCode.invalid_return_type:t="Invalid function return type";break;case Q.ZodIssueCode.invalid_date:t="Invalid date";break;case Q.ZodIssueCode.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(t=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?t=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?t=`Invalid input: must end with "${e.validation.endsWith}"`:Ir.util.assertNever(e.validation):e.validation!=="regex"?t=`Invalid ${e.validation}`:t="Invalid";break;case Q.ZodIssueCode.too_small:e.type==="array"?t=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?t=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?t=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?t=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?t=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:t="Invalid input";break;case Q.ZodIssueCode.too_big:e.type==="array"?t=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?t=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?t=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?t=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?t=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:t="Invalid input";break;case Q.ZodIssueCode.custom:t="Invalid input";break;case Q.ZodIssueCode.invalid_intersection_types:t="Intersection results could not be merged";break;case Q.ZodIssueCode.not_multiple_of:t=`Number must be a multiple of ${e.multipleOf}`;break;case Q.ZodIssueCode.not_finite:t="Number must be finite";break;default:t=r.defaultError,Ir.util.assertNever(e)}return{message:t}};Os.default=m_});var Oi=d(Ye=>{"use strict";var y_=Ye&&Ye.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.defaultErrorMap=void 0;Ye.setErrorMap=__;Ye.getErrorMap=b_;var sd=y_(ws());Ye.defaultErrorMap=sd.default;var cd=sd.default;function __(e){cd=e}function b_(){return cd}});var Ps=d(U=>{"use strict";var g_=U&&U.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(U,"__esModule",{value:!0});U.isAsync=U.isValid=U.isDirty=U.isAborted=U.OK=U.DIRTY=U.INVALID=U.ParseStatus=U.EMPTY_PATH=U.makeIssue=void 0;U.addIssueToContext=S_;var O_=Oi(),ld=g_(ws()),w_=e=>{let{data:r,path:t,errorMaps:n,issueData:i}=e,o=[...t,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let u="",l=n.filter(s=>!!s).slice().reverse();for(let s of l)u=s(a,{data:r,defaultError:u}).message;return{...i,path:o,message:u}};U.makeIssue=w_;U.EMPTY_PATH=[];function S_(e,r){let t=(0,O_.getErrorMap)(),n=(0,U.makeIssue)({issueData:r,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,t,t===ld.default?void 0:ld.default].filter(i=>!!i)});e.common.issues.push(n)}var Ss=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(r,t){let n=[];for(let i of t){if(i.status==="aborted")return U.INVALID;i.status==="dirty"&&r.dirty(),n.push(i.value)}return{status:r.value,value:n}}static async mergeObjectAsync(r,t){let n=[];for(let i of t){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return e.mergeObjectSync(r,n)}static mergeObjectSync(r,t){let n={};for(let i of t){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return U.INVALID;o.status==="dirty"&&r.dirty(),a.status==="dirty"&&r.dirty(),o.value!=="__proto__"&&(typeof a.value!="undefined"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:r.value,value:n}}};U.ParseStatus=Ss;U.INVALID=Object.freeze({status:"aborted"});var P_=e=>({status:"dirty",value:e});U.DIRTY=P_;var q_=e=>({status:"valid",value:e});U.OK=q_;var j_=e=>e.status==="aborted";U.isAborted=j_;var C_=e=>e.status==="dirty";U.isDirty=C_;var I_=e=>e.status==="valid";U.isValid=I_;var A_=e=>typeof Promise!="undefined"&&e instanceof Promise;U.isAsync=A_});var fd=d(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0})});var pd=d(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.errorUtil=void 0;var vd;(function(e){e.errToObj=r=>typeof r=="string"?{message:r}:r||{},e.toString=r=>typeof r=="string"?r:r==null?void 0:r.message})(vd||(wi.errorUtil=vd={}))});var jd=d(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.discriminatedUnion=p.date=p.boolean=p.bigint=p.array=p.any=p.coerce=p.ZodFirstPartyTypeKind=p.late=p.ZodSchema=p.Schema=p.ZodReadonly=p.ZodPipeline=p.ZodBranded=p.BRAND=p.ZodNaN=p.ZodCatch=p.ZodDefault=p.ZodNullable=p.ZodOptional=p.ZodTransformer=p.ZodEffects=p.ZodPromise=p.ZodNativeEnum=p.ZodEnum=p.ZodLiteral=p.ZodLazy=p.ZodFunction=p.ZodSet=p.ZodMap=p.ZodRecord=p.ZodTuple=p.ZodIntersection=p.ZodDiscriminatedUnion=p.ZodUnion=p.ZodObject=p.ZodArray=p.ZodVoid=p.ZodNever=p.ZodUnknown=p.ZodAny=p.ZodNull=p.ZodUndefined=p.ZodSymbol=p.ZodDate=p.ZodBoolean=p.ZodBigInt=p.ZodNumber=p.ZodString=p.ZodType=void 0;p.NEVER=p.void=p.unknown=p.union=p.undefined=p.tuple=p.transformer=p.symbol=p.string=p.strictObject=p.set=p.record=p.promise=p.preprocess=p.pipeline=p.ostring=p.optional=p.onumber=p.oboolean=p.object=p.number=p.nullable=p.null=p.never=p.nativeEnum=p.nan=p.map=p.literal=p.lazy=p.intersection=p.instanceof=p.function=p.enum=p.effect=void 0;p.datetimeRegex=bd;p.custom=Od;var w=gi(),Si=Oi(),I=pd(),h=Ps(),S=Tn(),ve=class{constructor(r,t,n,i){this._cachedPath=[],this.parent=r,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hd=(e,r)=>{if((0,h.isValid)(r))return{success:!0,data:r.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new w.ZodError(e.common.issues);return this._error=t,this._error}}};function M(e){if(!e)return{};let{errorMap:r,invalid_type_error:t,required_error:n,description:i}=e;if(r&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return r?{errorMap:r,description:i}:{errorMap:(a,u)=>{var s,f;let{message:l}=e;return a.code==="invalid_enum_value"?{message:l!=null?l:u.defaultError}:typeof u.data=="undefined"?{message:(s=l!=null?l:n)!=null?s:u.defaultError}:a.code!=="invalid_type"?{message:u.defaultError}:{message:(f=l!=null?l:t)!=null?f:u.defaultError}},description:i}}var k=class{get description(){return this._def.description}_getType(r){return(0,S.getParsedType)(r.data)}_getOrReturnCtx(r,t){return t||{common:r.parent.common,data:r.data,parsedType:(0,S.getParsedType)(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}_processInputParams(r){return{status:new h.ParseStatus,ctx:{common:r.parent.common,data:r.data,parsedType:(0,S.getParsedType)(r.data),schemaErrorMap:this._def.errorMap,path:r.path,parent:r.parent}}}_parseSync(r){let t=this._parse(r);if((0,h.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(r){let t=this._parse(r);return Promise.resolve(t)}parse(r,t){let n=this.safeParse(r,t);if(n.success)return n.data;throw n.error}safeParse(r,t){var o;let n={common:{issues:[],async:(o=t==null?void 0:t.async)!=null?o:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:(0,S.getParsedType)(r)},i=this._parseSync({data:r,path:n.path,parent:n});return hd(n,i)}"~validate"(r){var n,i;let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:(0,S.getParsedType)(r)};if(!this["~standard"].async)try{let o=this._parseSync({data:r,path:[],parent:t});return(0,h.isValid)(o)?{value:o.value}:{issues:t.common.issues}}catch(o){(i=(n=o==null?void 0:o.message)==null?void 0:n.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:r,path:[],parent:t}).then(o=>(0,h.isValid)(o)?{value:o.value}:{issues:t.common.issues})}async parseAsync(r,t){let n=await this.safeParseAsync(r,t);if(n.success)return n.data;throw n.error}async safeParseAsync(r,t){let n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:r,parsedType:(0,S.getParsedType)(r)},i=this._parse({data:r,path:n.path,parent:n}),o=await((0,h.isAsync)(i)?i:Promise.resolve(i));return hd(n,o)}refine(r,t){let n=i=>typeof t=="string"||typeof t=="undefined"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let a=r(i),u=()=>o.addIssue({code:w.ZodIssueCode.custom,...n(i)});return typeof Promise!="undefined"&&a instanceof Promise?a.then(l=>l?!0:(u(),!1)):a?!0:(u(),!1)})}refinement(r,t){return this._refinement((n,i)=>r(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(r){return new le({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:r}})}superRefine(r){return this._refinement(r)}constructor(r){this.spa=this.safeParseAsync,this._def=r,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:t=>this["~validate"](t)}}optional(){return fe.create(this,this._def)}nullable(){return qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return Je.create(this,this._def)}or(r){return Fr.create([this,r],this._def)}and(r){return Rr.create(this,r,this._def)}transform(r){return new le({...M(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:r}})}default(r){let t=typeof r=="function"?r:()=>r;return new zr({...M(this._def),innerType:this,defaultValue:t,typeName:T.ZodDefault})}brand(){return new Mn({typeName:T.ZodBranded,type:this,...M(this._def)})}catch(r){let t=typeof r=="function"?r:()=>r;return new Dr({...M(this._def),innerType:this,catchValue:t,typeName:T.ZodCatch})}describe(r){let t=this.constructor;return new t({...this._def,description:r})}pipe(r){return kn.create(this,r)}readonly(){return Vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};p.ZodType=k;p.Schema=k;p.ZodSchema=k;var x_=/^c[^\s-]{8,}$/i,T_=/^[0-9a-z]+$/,E_=/^[0-9A-HJKMNP-TV-Z]{26}$/i,M_=/^[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,k_=/^[a-z0-9_-]{21}$/i,F_=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,R_=/^[-+]?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)?)??$/,Z_=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,U_="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",qs,L_=/^(?:(?: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])$/,N_=/^(?:(?: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])$/,z_=/^(([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]))$/,D_=/^(([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])$/,V_=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$_=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yd="((\\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])))",W_=new RegExp(`^${yd}$`);function _d(e){let r="[0-5]\\d";e.precision?r=`${r}\\.\\d{${e.precision}}`:e.precision==null&&(r=`${r}(\\.\\d+)?`);let t=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${r})${t}`}function B_(e){return new RegExp(`^${_d(e)}$`)}function bd(e){let r=`${yd}T${_d(e)}`,t=[];return t.push(e.local?"Z?":"Z"),e.offset&&t.push("([+-]\\d{2}:?\\d{2})"),r=`${r}(${t.join("|")})`,new RegExp(`^${r}$`)}function G_(e,r){return!!((r==="v4"||!r)&&L_.test(e)||(r==="v6"||!r)&&z_.test(e))}function Y_(e,r){if(!F_.test(e))return!1;try{let[t]=e.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||r&&i.alg!==r)}catch{return!1}}function H_(e,r){return!!((r==="v4"||!r)&&N_.test(e)||(r==="v6"||!r)&&D_.test(e))}var He=class e extends k{_parse(r){if(this._def.coerce&&(r.data=String(r.data)),this._getType(r)!==S.ZodParsedType.string){let o=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(o,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.string,received:o.parsedType}),h.INVALID}let n=new h.ParseStatus,i;for(let o of this._def.checks)if(o.kind==="min")r.data.lengtho.value&&(i=this._getOrReturnCtx(r,i),(0,h.addIssueToContext)(i,{code:w.ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=r.data.length>o.value,u=r.data.lengthr.test(i),{validation:t,code:w.ZodIssueCode.invalid_string,...I.errorUtil.errToObj(n)})}_addCheck(r){return new e({...this._def,checks:[...this._def.checks,r]})}email(r){return this._addCheck({kind:"email",...I.errorUtil.errToObj(r)})}url(r){return this._addCheck({kind:"url",...I.errorUtil.errToObj(r)})}emoji(r){return this._addCheck({kind:"emoji",...I.errorUtil.errToObj(r)})}uuid(r){return this._addCheck({kind:"uuid",...I.errorUtil.errToObj(r)})}nanoid(r){return this._addCheck({kind:"nanoid",...I.errorUtil.errToObj(r)})}cuid(r){return this._addCheck({kind:"cuid",...I.errorUtil.errToObj(r)})}cuid2(r){return this._addCheck({kind:"cuid2",...I.errorUtil.errToObj(r)})}ulid(r){return this._addCheck({kind:"ulid",...I.errorUtil.errToObj(r)})}base64(r){return this._addCheck({kind:"base64",...I.errorUtil.errToObj(r)})}base64url(r){return this._addCheck({kind:"base64url",...I.errorUtil.errToObj(r)})}jwt(r){return this._addCheck({kind:"jwt",...I.errorUtil.errToObj(r)})}ip(r){return this._addCheck({kind:"ip",...I.errorUtil.errToObj(r)})}cidr(r){return this._addCheck({kind:"cidr",...I.errorUtil.errToObj(r)})}datetime(r){var t,n;return typeof r=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:r}):this._addCheck({kind:"datetime",precision:typeof(r==null?void 0:r.precision)=="undefined"?null:r==null?void 0:r.precision,offset:(t=r==null?void 0:r.offset)!=null?t:!1,local:(n=r==null?void 0:r.local)!=null?n:!1,...I.errorUtil.errToObj(r==null?void 0:r.message)})}date(r){return this._addCheck({kind:"date",message:r})}time(r){return typeof r=="string"?this._addCheck({kind:"time",precision:null,message:r}):this._addCheck({kind:"time",precision:typeof(r==null?void 0:r.precision)=="undefined"?null:r==null?void 0:r.precision,...I.errorUtil.errToObj(r==null?void 0:r.message)})}duration(r){return this._addCheck({kind:"duration",...I.errorUtil.errToObj(r)})}regex(r,t){return this._addCheck({kind:"regex",regex:r,...I.errorUtil.errToObj(t)})}includes(r,t){return this._addCheck({kind:"includes",value:r,position:t==null?void 0:t.position,...I.errorUtil.errToObj(t==null?void 0:t.message)})}startsWith(r,t){return this._addCheck({kind:"startsWith",value:r,...I.errorUtil.errToObj(t)})}endsWith(r,t){return this._addCheck({kind:"endsWith",value:r,...I.errorUtil.errToObj(t)})}min(r,t){return this._addCheck({kind:"min",value:r,...I.errorUtil.errToObj(t)})}max(r,t){return this._addCheck({kind:"max",value:r,...I.errorUtil.errToObj(t)})}length(r,t){return this._addCheck({kind:"length",value:r,...I.errorUtil.errToObj(t)})}nonempty(r){return this.min(1,I.errorUtil.errToObj(r))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(r=>r.kind==="datetime")}get isDate(){return!!this._def.checks.find(r=>r.kind==="date")}get isTime(){return!!this._def.checks.find(r=>r.kind==="time")}get isDuration(){return!!this._def.checks.find(r=>r.kind==="duration")}get isEmail(){return!!this._def.checks.find(r=>r.kind==="email")}get isURL(){return!!this._def.checks.find(r=>r.kind==="url")}get isEmoji(){return!!this._def.checks.find(r=>r.kind==="emoji")}get isUUID(){return!!this._def.checks.find(r=>r.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(r=>r.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(r=>r.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(r=>r.kind==="cuid2")}get isULID(){return!!this._def.checks.find(r=>r.kind==="ulid")}get isIP(){return!!this._def.checks.find(r=>r.kind==="ip")}get isCIDR(){return!!this._def.checks.find(r=>r.kind==="cidr")}get isBase64(){return!!this._def.checks.find(r=>r.kind==="base64")}get isBase64url(){return!!this._def.checks.find(r=>r.kind==="base64url")}get minLength(){let r=null;for(let t of this._def.checks)t.kind==="min"&&(r===null||t.value>r)&&(r=t.value);return r}get maxLength(){let r=null;for(let t of this._def.checks)t.kind==="max"&&(r===null||t.value{var r;return new He({checks:[],typeName:T.ZodString,coerce:(r=e==null?void 0:e.coerce)!=null?r:!1,...M(e)})};function K_(e,r){let t=(e.toString().split(".")[1]||"").length,n=(r.toString().split(".")[1]||"").length,i=t>n?t:n,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(r.toFixed(i).replace(".",""));return o%a/10**i}var Ar=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(r){if(this._def.coerce&&(r.data=Number(r.data)),this._getType(r)!==S.ZodParsedType.number){let o=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(o,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.number,received:o.parsedType}),h.INVALID}let n,i=new h.ParseStatus;for(let o of this._def.checks)o.kind==="int"?S.util.isInteger(r.data)||(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?r.datao.value:r.data>=o.value)&&(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?K_(r.data,o.value)!==0&&(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(r.data)||(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.not_finite,message:o.message}),i.dirty()):S.util.assertNever(o);return{status:i.value,value:r.data}}gte(r,t){return this.setLimit("min",r,!0,I.errorUtil.toString(t))}gt(r,t){return this.setLimit("min",r,!1,I.errorUtil.toString(t))}lte(r,t){return this.setLimit("max",r,!0,I.errorUtil.toString(t))}lt(r,t){return this.setLimit("max",r,!1,I.errorUtil.toString(t))}setLimit(r,t,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:r,value:t,inclusive:n,message:I.errorUtil.toString(i)}]})}_addCheck(r){return new e({...this._def,checks:[...this._def.checks,r]})}int(r){return this._addCheck({kind:"int",message:I.errorUtil.toString(r)})}positive(r){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.errorUtil.toString(r)})}negative(r){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.errorUtil.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.errorUtil.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.errorUtil.toString(r)})}multipleOf(r,t){return this._addCheck({kind:"multipleOf",value:r,message:I.errorUtil.toString(t)})}finite(r){return this._addCheck({kind:"finite",message:I.errorUtil.toString(r)})}safe(r){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.errorUtil.toString(r)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.errorUtil.toString(r)})}get minValue(){let r=null;for(let t of this._def.checks)t.kind==="min"&&(r===null||t.value>r)&&(r=t.value);return r}get maxValue(){let r=null;for(let t of this._def.checks)t.kind==="max"&&(r===null||t.valuer.kind==="int"||r.kind==="multipleOf"&&S.util.isInteger(r.value))}get isFinite(){let r=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(r===null||n.valuenew Ar({checks:[],typeName:T.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...M(e)});var xr=class e extends k{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(r){if(this._def.coerce)try{r.data=BigInt(r.data)}catch{return this._getInvalidInput(r)}if(this._getType(r)!==S.ZodParsedType.bigint)return this._getInvalidInput(r);let n,i=new h.ParseStatus;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?r.datao.value:r.data>=o.value)&&(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?r.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(r,n),(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):S.util.assertNever(o);return{status:i.value,value:r.data}}_getInvalidInput(r){let t=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.bigint,received:t.parsedType}),h.INVALID}gte(r,t){return this.setLimit("min",r,!0,I.errorUtil.toString(t))}gt(r,t){return this.setLimit("min",r,!1,I.errorUtil.toString(t))}lte(r,t){return this.setLimit("max",r,!0,I.errorUtil.toString(t))}lt(r,t){return this.setLimit("max",r,!1,I.errorUtil.toString(t))}setLimit(r,t,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:r,value:t,inclusive:n,message:I.errorUtil.toString(i)}]})}_addCheck(r){return new e({...this._def,checks:[...this._def.checks,r]})}positive(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.errorUtil.toString(r)})}negative(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.errorUtil.toString(r)})}nonpositive(r){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.errorUtil.toString(r)})}nonnegative(r){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.errorUtil.toString(r)})}multipleOf(r,t){return this._addCheck({kind:"multipleOf",value:r,message:I.errorUtil.toString(t)})}get minValue(){let r=null;for(let t of this._def.checks)t.kind==="min"&&(r===null||t.value>r)&&(r=t.value);return r}get maxValue(){let r=null;for(let t of this._def.checks)t.kind==="max"&&(r===null||t.value{var r;return new xr({checks:[],typeName:T.ZodBigInt,coerce:(r=e==null?void 0:e.coerce)!=null?r:!1,...M(e)})};var Tr=class extends k{_parse(r){if(this._def.coerce&&(r.data=!!r.data),this._getType(r)!==S.ZodParsedType.boolean){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.boolean,received:n.parsedType}),h.INVALID}return(0,h.OK)(r.data)}};p.ZodBoolean=Tr;Tr.create=e=>new Tr({typeName:T.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...M(e)});var Er=class e extends k{_parse(r){if(this._def.coerce&&(r.data=new Date(r.data)),this._getType(r)!==S.ZodParsedType.date){let o=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(o,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.date,received:o.parsedType}),h.INVALID}if(Number.isNaN(r.data.getTime())){let o=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(o,{code:w.ZodIssueCode.invalid_date}),h.INVALID}let n=new h.ParseStatus,i;for(let o of this._def.checks)o.kind==="min"?r.data.getTime()o.value&&(i=this._getOrReturnCtx(r,i),(0,h.addIssueToContext)(i,{code:w.ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):S.util.assertNever(o);return{status:n.value,value:new Date(r.data.getTime())}}_addCheck(r){return new e({...this._def,checks:[...this._def.checks,r]})}min(r,t){return this._addCheck({kind:"min",value:r.getTime(),message:I.errorUtil.toString(t)})}max(r,t){return this._addCheck({kind:"max",value:r.getTime(),message:I.errorUtil.toString(t)})}get minDate(){let r=null;for(let t of this._def.checks)t.kind==="min"&&(r===null||t.value>r)&&(r=t.value);return r!=null?new Date(r):null}get maxDate(){let r=null;for(let t of this._def.checks)t.kind==="max"&&(r===null||t.valuenew Er({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:T.ZodDate,...M(e)});var pt=class extends k{_parse(r){if(this._getType(r)!==S.ZodParsedType.symbol){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.symbol,received:n.parsedType}),h.INVALID}return(0,h.OK)(r.data)}};p.ZodSymbol=pt;pt.create=e=>new pt({typeName:T.ZodSymbol,...M(e)});var Mr=class extends k{_parse(r){if(this._getType(r)!==S.ZodParsedType.undefined){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.undefined,received:n.parsedType}),h.INVALID}return(0,h.OK)(r.data)}};p.ZodUndefined=Mr;Mr.create=e=>new Mr({typeName:T.ZodUndefined,...M(e)});var kr=class extends k{_parse(r){if(this._getType(r)!==S.ZodParsedType.null){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.null,received:n.parsedType}),h.INVALID}return(0,h.OK)(r.data)}};p.ZodNull=kr;kr.create=e=>new kr({typeName:T.ZodNull,...M(e)});var Ke=class extends k{constructor(){super(...arguments),this._any=!0}_parse(r){return(0,h.OK)(r.data)}};p.ZodAny=Ke;Ke.create=e=>new Ke({typeName:T.ZodAny,...M(e)});var Ze=class extends k{constructor(){super(...arguments),this._unknown=!0}_parse(r){return(0,h.OK)(r.data)}};p.ZodUnknown=Ze;Ze.create=e=>new Ze({typeName:T.ZodUnknown,...M(e)});var _e=class extends k{_parse(r){let t=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.never,received:t.parsedType}),h.INVALID}};p.ZodNever=_e;_e.create=e=>new _e({typeName:T.ZodNever,...M(e)});var ht=class extends k{_parse(r){if(this._getType(r)!==S.ZodParsedType.undefined){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.void,received:n.parsedType}),h.INVALID}return(0,h.OK)(r.data)}};p.ZodVoid=ht;ht.create=e=>new ht({typeName:T.ZodVoid,...M(e)});var Ue=class e extends k{_parse(r){let{ctx:t,status:n}=this._processInputParams(r),i=this._def;if(t.parsedType!==S.ZodParsedType.array)return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.array,received:t.parsedType}),h.INVALID;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,u=t.data.lengthi.maxLength.value&&((0,h.addIssueToContext)(t,{code:w.ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,u)=>i.type._parseAsync(new ve(t,a,t.path,u)))).then(a=>h.ParseStatus.mergeArray(n,a));let o=[...t.data].map((a,u)=>i.type._parseSync(new ve(t,a,t.path,u)));return h.ParseStatus.mergeArray(n,o)}get element(){return this._def.type}min(r,t){return new e({...this._def,minLength:{value:r,message:I.errorUtil.toString(t)}})}max(r,t){return new e({...this._def,maxLength:{value:r,message:I.errorUtil.toString(t)}})}length(r,t){return new e({...this._def,exactLength:{value:r,message:I.errorUtil.toString(t)}})}nonempty(r){return this.min(1,r)}};p.ZodArray=Ue;Ue.create=(e,r)=>new Ue({type:e,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...M(r)});function vt(e){if(e instanceof oe){let r={};for(let t in e.shape){let n=e.shape[t];r[t]=fe.create(vt(n))}return new oe({...e._def,shape:()=>r})}else return e instanceof Ue?new Ue({...e._def,type:vt(e.element)}):e instanceof fe?fe.create(vt(e.unwrap())):e instanceof qe?qe.create(vt(e.unwrap())):e instanceof Pe?Pe.create(e.items.map(r=>vt(r))):e}var oe=class e extends k{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let r=this._def.shape(),t=S.util.objectKeys(r);return this._cached={shape:r,keys:t},this._cached}_parse(r){if(this._getType(r)!==S.ZodParsedType.object){let s=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(s,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.object,received:s.parsedType}),h.INVALID}let{status:n,ctx:i}=this._processInputParams(r),{shape:o,keys:a}=this._getCached(),u=[];if(!(this._def.catchall instanceof _e&&this._def.unknownKeys==="strip"))for(let s in i.data)a.includes(s)||u.push(s);let l=[];for(let s of a){let f=o[s],v=i.data[s];l.push({key:{status:"valid",value:s},value:f._parse(new ve(i,v,i.path,s)),alwaysSet:s in i.data})}if(this._def.catchall instanceof _e){let s=this._def.unknownKeys;if(s==="passthrough")for(let f of u)l.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(s==="strict")u.length>0&&((0,h.addIssueToContext)(i,{code:w.ZodIssueCode.unrecognized_keys,keys:u}),n.dirty());else if(s!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let s=this._def.catchall;for(let f of u){let v=i.data[f];l.push({key:{status:"valid",value:f},value:s._parse(new ve(i,v,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let s=[];for(let f of l){let v=await f.key,m=await f.value;s.push({key:v,value:m,alwaysSet:f.alwaysSet})}return s}).then(s=>h.ParseStatus.mergeObjectSync(n,s)):h.ParseStatus.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(r){return I.errorUtil.errToObj,new e({...this._def,unknownKeys:"strict",...r!==void 0?{errorMap:(t,n)=>{var o,a,u,l;let i=(u=(a=(o=this._def).errorMap)==null?void 0:a.call(o,t,n).message)!=null?u:n.defaultError;return t.code==="unrecognized_keys"?{message:(l=I.errorUtil.errToObj(r).message)!=null?l:i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(r){return new e({...this._def,shape:()=>({...this._def.shape(),...r})})}merge(r){return new e({unknownKeys:r._def.unknownKeys,catchall:r._def.catchall,shape:()=>({...this._def.shape(),...r._def.shape()}),typeName:T.ZodObject})}setKey(r,t){return this.augment({[r]:t})}catchall(r){return new e({...this._def,catchall:r})}pick(r){let t={};for(let n of S.util.objectKeys(r))r[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new e({...this._def,shape:()=>t})}omit(r){let t={};for(let n of S.util.objectKeys(this.shape))r[n]||(t[n]=this.shape[n]);return new e({...this._def,shape:()=>t})}deepPartial(){return vt(this)}partial(r){let t={};for(let n of S.util.objectKeys(this.shape)){let i=this.shape[n];r&&!r[n]?t[n]=i:t[n]=i.optional()}return new e({...this._def,shape:()=>t})}required(r){let t={};for(let n of S.util.objectKeys(this.shape))if(r&&!r[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof fe;)o=o._def.innerType;t[n]=o}return new e({...this._def,shape:()=>t})}keyof(){return gd(S.util.objectKeys(this.shape))}};p.ZodObject=oe;oe.create=(e,r)=>new oe({shape:()=>e,unknownKeys:"strip",catchall:_e.create(),typeName:T.ZodObject,...M(r)});oe.strictCreate=(e,r)=>new oe({shape:()=>e,unknownKeys:"strict",catchall:_e.create(),typeName:T.ZodObject,...M(r)});oe.lazycreate=(e,r)=>new oe({shape:e,unknownKeys:"strip",catchall:_e.create(),typeName:T.ZodObject,...M(r)});var Fr=class extends k{_parse(r){let{ctx:t}=this._processInputParams(r),n=this._def.options;function i(o){for(let u of o)if(u.result.status==="valid")return u.result;for(let u of o)if(u.result.status==="dirty")return t.common.issues.push(...u.ctx.common.issues),u.result;let a=o.map(u=>new w.ZodError(u.ctx.common.issues));return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_union,unionErrors:a}),h.INVALID}if(t.common.async)return Promise.all(n.map(async o=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let l of n){let s={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.path,parent:s});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let u=a.map(l=>new w.ZodError(l));return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_union,unionErrors:u}),h.INVALID}}get options(){return this._def.options}};p.ZodUnion=Fr;Fr.create=(e,r)=>new Fr({options:e,typeName:T.ZodUnion,...M(r)});var Re=e=>e instanceof Zr?Re(e.schema):e instanceof le?Re(e.innerType()):e instanceof Ur?[e.value]:e instanceof Lr?e.options:e instanceof Nr?S.util.objectValues(e.enum):e instanceof zr?Re(e._def.innerType):e instanceof Mr?[void 0]:e instanceof kr?[null]:e instanceof fe?[void 0,...Re(e.unwrap())]:e instanceof qe?[null,...Re(e.unwrap())]:e instanceof Mn||e instanceof Vr?Re(e.unwrap()):e instanceof Dr?Re(e._def.innerType):[],Pi=class e extends k{_parse(r){let{ctx:t}=this._processInputParams(r);if(t.parsedType!==S.ZodParsedType.object)return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.object,received:t.parsedType}),h.INVALID;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):((0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),h.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(r,t,n){let i=new Map;for(let o of t){let a=Re(o.shape[r]);if(!a.length)throw new Error(`A discriminator value for key \`${r}\` could not be extracted from all schema options`);for(let u of a){if(i.has(u))throw new Error(`Discriminator property ${String(r)} has duplicate value ${String(u)}`);i.set(u,o)}}return new e({typeName:T.ZodDiscriminatedUnion,discriminator:r,options:t,optionsMap:i,...M(n)})}};p.ZodDiscriminatedUnion=Pi;function js(e,r){let t=(0,S.getParsedType)(e),n=(0,S.getParsedType)(r);if(e===r)return{valid:!0,data:e};if(t===S.ZodParsedType.object&&n===S.ZodParsedType.object){let i=S.util.objectKeys(r),o=S.util.objectKeys(e).filter(u=>i.indexOf(u)!==-1),a={...e,...r};for(let u of o){let l=js(e[u],r[u]);if(!l.valid)return{valid:!1};a[u]=l.data}return{valid:!0,data:a}}else if(t===S.ZodParsedType.array&&n===S.ZodParsedType.array){if(e.length!==r.length)return{valid:!1};let i=[];for(let o=0;o{if((0,h.isAborted)(o)||(0,h.isAborted)(a))return h.INVALID;let u=js(o.value,a.value);return u.valid?(((0,h.isDirty)(o)||(0,h.isDirty)(a))&&t.dirty(),{status:t.value,value:u.data}):((0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_intersection_types}),h.INVALID)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};p.ZodIntersection=Rr;Rr.create=(e,r,t)=>new Rr({left:e,right:r,typeName:T.ZodIntersection,...M(t)});var Pe=class e extends k{_parse(r){let{status:t,ctx:n}=this._processInputParams(r);if(n.parsedType!==S.ZodParsedType.array)return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.array,received:n.parsedType}),h.INVALID;if(n.data.lengththis._def.items.length&&((0,h.addIssueToContext)(n,{code:w.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((a,u)=>{let l=this._def.items[u]||this._def.rest;return l?l._parse(new ve(n,a,n.path,u)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>h.ParseStatus.mergeArray(t,a)):h.ParseStatus.mergeArray(t,o)}get items(){return this._def.items}rest(r){return new e({...this._def,rest:r})}};p.ZodTuple=Pe;Pe.create=(e,r)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Pe({items:e,typeName:T.ZodTuple,rest:null,...M(r)})};var qi=class e extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:t,ctx:n}=this._processInputParams(r);if(n.parsedType!==S.ZodParsedType.object)return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.object,received:n.parsedType}),h.INVALID;let i=[],o=this._def.keyType,a=this._def.valueType;for(let u in n.data)i.push({key:o._parse(new ve(n,u,n.path,u)),value:a._parse(new ve(n,n.data[u],n.path,u)),alwaysSet:u in n.data});return n.common.async?h.ParseStatus.mergeObjectAsync(t,i):h.ParseStatus.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(r,t,n){return t instanceof k?new e({keyType:r,valueType:t,typeName:T.ZodRecord,...M(n)}):new e({keyType:He.create(),valueType:r,typeName:T.ZodRecord,...M(t)})}};p.ZodRecord=qi;var mt=class extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(r){let{status:t,ctx:n}=this._processInputParams(r);if(n.parsedType!==S.ZodParsedType.map)return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.map,received:n.parsedType}),h.INVALID;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([u,l],s)=>({key:i._parse(new ve(n,u,n.path,[s,"key"])),value:o._parse(new ve(n,l,n.path,[s,"value"]))}));if(n.common.async){let u=new Map;return Promise.resolve().then(async()=>{for(let l of a){let s=await l.key,f=await l.value;if(s.status==="aborted"||f.status==="aborted")return h.INVALID;(s.status==="dirty"||f.status==="dirty")&&t.dirty(),u.set(s.value,f.value)}return{status:t.value,value:u}})}else{let u=new Map;for(let l of a){let s=l.key,f=l.value;if(s.status==="aborted"||f.status==="aborted")return h.INVALID;(s.status==="dirty"||f.status==="dirty")&&t.dirty(),u.set(s.value,f.value)}return{status:t.value,value:u}}}};p.ZodMap=mt;mt.create=(e,r,t)=>new mt({valueType:r,keyType:e,typeName:T.ZodMap,...M(t)});var yt=class e extends k{_parse(r){let{status:t,ctx:n}=this._processInputParams(r);if(n.parsedType!==S.ZodParsedType.set)return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.set,received:n.parsedType}),h.INVALID;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&((0,h.addIssueToContext)(n,{code:w.ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function a(l){let s=new Set;for(let f of l){if(f.status==="aborted")return h.INVALID;f.status==="dirty"&&t.dirty(),s.add(f.value)}return{status:t.value,value:s}}let u=[...n.data.values()].map((l,s)=>o._parse(new ve(n,l,n.path,s)));return n.common.async?Promise.all(u).then(l=>a(l)):a(u)}min(r,t){return new e({...this._def,minSize:{value:r,message:I.errorUtil.toString(t)}})}max(r,t){return new e({...this._def,maxSize:{value:r,message:I.errorUtil.toString(t)}})}size(r,t){return this.min(r,t).max(r,t)}nonempty(r){return this.min(1,r)}};p.ZodSet=yt;yt.create=(e,r)=>new yt({valueType:e,minSize:null,maxSize:null,typeName:T.ZodSet,...M(r)});var ji=class e extends k{constructor(){super(...arguments),this.validate=this.implement}_parse(r){let{ctx:t}=this._processInputParams(r);if(t.parsedType!==S.ZodParsedType.function)return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.function,received:t.parsedType}),h.INVALID;function n(u,l){return(0,h.makeIssue)({data:u,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,Si.getErrorMap)(),Si.defaultErrorMap].filter(s=>!!s),issueData:{code:w.ZodIssueCode.invalid_arguments,argumentsError:l}})}function i(u,l){return(0,h.makeIssue)({data:u,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,(0,Si.getErrorMap)(),Si.defaultErrorMap].filter(s=>!!s),issueData:{code:w.ZodIssueCode.invalid_return_type,returnTypeError:l}})}let o={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Je){let u=this;return(0,h.OK)(async function(...l){let s=new w.ZodError([]),f=await u._def.args.parseAsync(l,o).catch(b=>{throw s.addIssue(n(l,b)),s}),v=await Reflect.apply(a,this,f);return await u._def.returns._def.type.parseAsync(v,o).catch(b=>{throw s.addIssue(i(v,b)),s})})}else{let u=this;return(0,h.OK)(function(...l){let s=u._def.args.safeParse(l,o);if(!s.success)throw new w.ZodError([n(l,s.error)]);let f=Reflect.apply(a,this,s.data),v=u._def.returns.safeParse(f,o);if(!v.success)throw new w.ZodError([i(f,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...r){return new e({...this._def,args:Pe.create(r).rest(Ze.create())})}returns(r){return new e({...this._def,returns:r})}implement(r){return this.parse(r)}strictImplement(r){return this.parse(r)}static create(r,t,n){return new e({args:r||Pe.create([]).rest(Ze.create()),returns:t||Ze.create(),typeName:T.ZodFunction,...M(n)})}};p.ZodFunction=ji;var Zr=class extends k{get schema(){return this._def.getter()}_parse(r){let{ctx:t}=this._processInputParams(r);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};p.ZodLazy=Zr;Zr.create=(e,r)=>new Zr({getter:e,typeName:T.ZodLazy,...M(r)});var Ur=class extends k{_parse(r){if(r.data!==this._def.value){let t=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(t,{received:t.data,code:w.ZodIssueCode.invalid_literal,expected:this._def.value}),h.INVALID}return{status:"valid",value:r.data}}get value(){return this._def.value}};p.ZodLiteral=Ur;Ur.create=(e,r)=>new Ur({value:e,typeName:T.ZodLiteral,...M(r)});function gd(e,r){return new Lr({values:e,typeName:T.ZodEnum,...M(r)})}var Lr=class e extends k{_parse(r){if(typeof r.data!="string"){let t=this._getOrReturnCtx(r),n=this._def.values;return(0,h.addIssueToContext)(t,{expected:S.util.joinValues(n),received:t.parsedType,code:w.ZodIssueCode.invalid_type}),h.INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(r.data)){let t=this._getOrReturnCtx(r),n=this._def.values;return(0,h.addIssueToContext)(t,{received:t.data,code:w.ZodIssueCode.invalid_enum_value,options:n}),h.INVALID}return(0,h.OK)(r.data)}get options(){return this._def.values}get enum(){let r={};for(let t of this._def.values)r[t]=t;return r}get Values(){let r={};for(let t of this._def.values)r[t]=t;return r}get Enum(){let r={};for(let t of this._def.values)r[t]=t;return r}extract(r,t=this._def){return e.create(r,{...this._def,...t})}exclude(r,t=this._def){return e.create(this.options.filter(n=>!r.includes(n)),{...this._def,...t})}};p.ZodEnum=Lr;Lr.create=gd;var Nr=class extends k{_parse(r){let t=S.util.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(r);if(n.parsedType!==S.ZodParsedType.string&&n.parsedType!==S.ZodParsedType.number){let i=S.util.objectValues(t);return(0,h.addIssueToContext)(n,{expected:S.util.joinValues(i),received:n.parsedType,code:w.ZodIssueCode.invalid_type}),h.INVALID}if(this._cache||(this._cache=new Set(S.util.getValidEnumValues(this._def.values))),!this._cache.has(r.data)){let i=S.util.objectValues(t);return(0,h.addIssueToContext)(n,{received:n.data,code:w.ZodIssueCode.invalid_enum_value,options:i}),h.INVALID}return(0,h.OK)(r.data)}get enum(){return this._def.values}};p.ZodNativeEnum=Nr;Nr.create=(e,r)=>new Nr({values:e,typeName:T.ZodNativeEnum,...M(r)});var Je=class extends k{unwrap(){return this._def.type}_parse(r){let{ctx:t}=this._processInputParams(r);if(t.parsedType!==S.ZodParsedType.promise&&t.common.async===!1)return(0,h.addIssueToContext)(t,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.promise,received:t.parsedType}),h.INVALID;let n=t.parsedType===S.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,h.OK)(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};p.ZodPromise=Je;Je.create=(e,r)=>new Je({type:e,typeName:T.ZodPromise,...M(r)});var le=class extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(r){let{status:t,ctx:n}=this._processInputParams(r),i=this._def.effect||null,o={addIssue:a=>{(0,h.addIssueToContext)(n,a),a.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async u=>{if(t.value==="aborted")return h.INVALID;let l=await this._def.schema._parseAsync({data:u,path:n.path,parent:n});return l.status==="aborted"?h.INVALID:l.status==="dirty"||t.value==="dirty"?(0,h.DIRTY)(l.value):l});{if(t.value==="aborted")return h.INVALID;let u=this._def.schema._parseSync({data:a,path:n.path,parent:n});return u.status==="aborted"?h.INVALID:u.status==="dirty"||t.value==="dirty"?(0,h.DIRTY)(u.value):u}}if(i.type==="refinement"){let a=u=>{let l=i.refinement(u,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(n.common.async===!1){let u=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return u.status==="aborted"?h.INVALID:(u.status==="dirty"&&t.dirty(),a(u.value),{status:t.value,value:u.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(u=>u.status==="aborted"?h.INVALID:(u.status==="dirty"&&t.dirty(),a(u.value).then(()=>({status:t.value,value:u.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!(0,h.isValid)(a))return h.INVALID;let u=i.transform(a.value,o);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:u}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>(0,h.isValid)(a)?Promise.resolve(i.transform(a.value,o)).then(u=>({status:t.value,value:u})):h.INVALID);S.util.assertNever(i)}};p.ZodEffects=le;p.ZodTransformer=le;le.create=(e,r,t)=>new le({schema:e,typeName:T.ZodEffects,effect:r,...M(t)});le.createWithPreprocess=(e,r,t)=>new le({schema:r,effect:{type:"preprocess",transform:e},typeName:T.ZodEffects,...M(t)});var fe=class extends k{_parse(r){return this._getType(r)===S.ZodParsedType.undefined?(0,h.OK)(void 0):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};p.ZodOptional=fe;fe.create=(e,r)=>new fe({innerType:e,typeName:T.ZodOptional,...M(r)});var qe=class extends k{_parse(r){return this._getType(r)===S.ZodParsedType.null?(0,h.OK)(null):this._def.innerType._parse(r)}unwrap(){return this._def.innerType}};p.ZodNullable=qe;qe.create=(e,r)=>new qe({innerType:e,typeName:T.ZodNullable,...M(r)});var zr=class extends k{_parse(r){let{ctx:t}=this._processInputParams(r),n=t.data;return t.parsedType===S.ZodParsedType.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};p.ZodDefault=zr;zr.create=(e,r)=>new zr({innerType:e,typeName:T.ZodDefault,defaultValue:typeof r.default=="function"?r.default:()=>r.default,...M(r)});var Dr=class extends k{_parse(r){let{ctx:t}=this._processInputParams(r),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return(0,h.isAsync)(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new w.ZodError(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new w.ZodError(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};p.ZodCatch=Dr;Dr.create=(e,r)=>new Dr({innerType:e,typeName:T.ZodCatch,catchValue:typeof r.catch=="function"?r.catch:()=>r.catch,...M(r)});var _t=class extends k{_parse(r){if(this._getType(r)!==S.ZodParsedType.nan){let n=this._getOrReturnCtx(r);return(0,h.addIssueToContext)(n,{code:w.ZodIssueCode.invalid_type,expected:S.ZodParsedType.nan,received:n.parsedType}),h.INVALID}return{status:"valid",value:r.data}}};p.ZodNaN=_t;_t.create=e=>new _t({typeName:T.ZodNaN,...M(e)});p.BRAND=Symbol("zod_brand");var Mn=class extends k{_parse(r){let{ctx:t}=this._processInputParams(r),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};p.ZodBranded=Mn;var kn=class e extends k{_parse(r){let{status:t,ctx:n}=this._processInputParams(r);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?h.INVALID:o.status==="dirty"?(t.dirty(),(0,h.DIRTY)(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?h.INVALID:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(r,t){return new e({in:r,out:t,typeName:T.ZodPipeline})}};p.ZodPipeline=kn;var Vr=class extends k{_parse(r){let t=this._def.innerType._parse(r),n=i=>((0,h.isValid)(i)&&(i.value=Object.freeze(i.value)),i);return(0,h.isAsync)(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};p.ZodReadonly=Vr;Vr.create=(e,r)=>new Vr({innerType:e,typeName:T.ZodReadonly,...M(r)});function md(e,r){let t=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e;return typeof t=="string"?{message:t}:t}function Od(e,r={},t){return e?Ke.create().superRefine((n,i)=>{var a,u;let o=e(n);if(o instanceof Promise)return o.then(l=>{var s,f;if(!l){let v=md(r,n),m=(f=(s=v.fatal)!=null?s:t)!=null?f:!0;i.addIssue({code:"custom",...v,fatal:m})}});if(!o){let l=md(r,n),s=(u=(a=l.fatal)!=null?a:t)!=null?u:!0;i.addIssue({code:"custom",...l,fatal:s})}}):Ke.create()}p.late={object:oe.lazycreate};var T;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(T||(p.ZodFirstPartyTypeKind=T={}));var J_=(e,r={message:`Input not instance of ${e.name}`})=>Od(t=>t instanceof e,r);p.instanceof=J_;var wd=He.create;p.string=wd;var Sd=Ar.create;p.number=Sd;var Q_=_t.create;p.nan=Q_;var X_=xr.create;p.bigint=X_;var Pd=Tr.create;p.boolean=Pd;var eb=Er.create;p.date=eb;var rb=pt.create;p.symbol=rb;var tb=Mr.create;p.undefined=tb;var nb=kr.create;p.null=nb;var ib=Ke.create;p.any=ib;var ob=Ze.create;p.unknown=ob;var ab=_e.create;p.never=ab;var ub=ht.create;p.void=ub;var sb=Ue.create;p.array=sb;var cb=oe.create;p.object=cb;var lb=oe.strictCreate;p.strictObject=lb;var db=Fr.create;p.union=db;var fb=Pi.create;p.discriminatedUnion=fb;var vb=Rr.create;p.intersection=vb;var pb=Pe.create;p.tuple=pb;var hb=qi.create;p.record=hb;var mb=mt.create;p.map=mb;var yb=yt.create;p.set=yb;var _b=ji.create;p.function=_b;var bb=Zr.create;p.lazy=bb;var gb=Ur.create;p.literal=gb;var Ob=Lr.create;p.enum=Ob;var wb=Nr.create;p.nativeEnum=wb;var Sb=Je.create;p.promise=Sb;var qd=le.create;p.effect=qd;p.transformer=qd;var Pb=fe.create;p.optional=Pb;var qb=qe.create;p.nullable=qb;var jb=le.createWithPreprocess;p.preprocess=jb;var Cb=kn.create;p.pipeline=Cb;var Ib=()=>wd().optional();p.ostring=Ib;var Ab=()=>Sd().optional();p.onumber=Ab;var xb=()=>Pd().optional();p.oboolean=xb;p.coerce={string:(e=>He.create({...e,coerce:!0})),number:(e=>Ar.create({...e,coerce:!0})),boolean:(e=>Tr.create({...e,coerce:!0})),bigint:(e=>xr.create({...e,coerce:!0})),date:(e=>Er.create({...e,coerce:!0}))};p.NEVER=h.INVALID});var Cs=d(pe=>{"use strict";var Tb=pe&&pe.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),bt=pe&&pe.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Tb(r,e,t)};Object.defineProperty(pe,"__esModule",{value:!0});bt(Oi(),pe);bt(Ps(),pe);bt(fd(),pe);bt(Tn(),pe);bt(jd(),pe);bt(gi(),pe)});var N=d(ae=>{"use strict";var Cd=ae&&ae.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Eb=ae&&ae.__setModuleDefault||(Object.create?(function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}):function(e,r){e.default=r}),Mb=ae&&ae.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t in e)t!=="default"&&Object.prototype.hasOwnProperty.call(e,t)&&Cd(r,e,t);return Eb(r,e),r},kb=ae&&ae.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&Cd(r,e,t)};Object.defineProperty(ae,"__esModule",{value:!0});ae.z=void 0;var Id=Mb(Cs());ae.z=Id;kb(Cs(),ae);ae.default=Id});var Is=d(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.actionTypesZodSchema=gt.ActionTypes=void 0;var Fb=N(),Ad;(function(e){e.OpenUrl="openUrl",e.ImBack="imBack",e.PostBack="postBack",e.PlayAudio="playAudio",e.PlayVideo="playVideo",e.ShowImage="showImage",e.DownloadFile="downloadFile",e.Signin="signin",e.Call="call",e.MessageBack="messageBack",e.OpenApp="openApp"})(Ad||(gt.ActionTypes=Ad={}));gt.actionTypesZodSchema=Fb.z.enum(["openUrl","imBack","postBack","playAudio","showImage","downloadFile","signin","call","messageBack","openApp"])});var As=d(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.semanticActionStateTypesZodSchema=Ot.SemanticActionStateTypes=void 0;var Rb=N(),xd;(function(e){e.Start="start",e.Continue="continue",e.Done="done"})(xd||(Ot.SemanticActionStateTypes=xd={}));Ot.semanticActionStateTypesZodSchema=Rb.z.enum(["start","continue","done"])});var xs=d(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.attachmentLayoutTypesZodSchema=wt.AttachmentLayoutTypes=void 0;var Zb=N(),Td;(function(e){e.List="list",e.Carousel="carousel"})(Td||(wt.AttachmentLayoutTypes=Td={}));wt.attachmentLayoutTypesZodSchema=Zb.z.enum(["list","carousel"])});var Ts=d(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.Channels=void 0;var Ed;(function(e){e.Alexa="alexa",e.Console="console",e.Directline="directline",e.DirectlineSpeech="directlinespeech",e.Email="email",e.Emulator="emulator",e.Facebook="facebook",e.Groupme="groupme",e.Line="line",e.Msteams="msteams",e.Omni="omnichannel",e.Outlook="outlook",e.Skype="skype",e.Slack="slack",e.Sms="sms",e.Telegram="telegram",e.Telephony="telephony",e.Test="test",e.Webchat="webchat"})(Ed||(Ci.Channels=Ed={}))});var Es=d(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.endOfConversationCodesZodSchema=St.EndOfConversationCodes=void 0;var Ub=N(),Md;(function(e){e.Unknown="unknown",e.CompletedSuccessfully="completedSuccessfully",e.UserCancelled="userCancelled",e.AgentTimedOut="agentTimedOut",e.AgentIssuedInvalidMessage="agentIssuedInvalidMessage",e.ChannelFailed="channelFailed"})(Md||(St.EndOfConversationCodes=Md={}));St.endOfConversationCodesZodSchema=Ub.z.enum(["unknown","completedSuccessfully","userCancelled","agentTimedOut","agentIssuedInvalidMessage","channelFailed"])});var Fd=d(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.membershipSourceTypeZodSchema=Pt.MembershipSourceTypes=void 0;var Lb=N(),kd;(function(e){e.Channel="channel",e.Team="team"})(kd||(Pt.MembershipSourceTypes=kd={}));Pt.membershipSourceTypeZodSchema=Lb.z.enum(["channel","team"])});var Zd=d(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.membershipTypeZodSchema=qt.MembershipTypes=void 0;var Nb=N(),Rd;(function(e){e.Direct="direct",e.Transitive="transitive"})(Rd||(qt.MembershipTypes=Rd={}));qt.membershipTypeZodSchema=Nb.z.enum(["direct","transitive"])});var Ii=d(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.roleTypeZodSchema=jt.RoleTypes=void 0;var zb=N(),Ud;(function(e){e.User="user",e.Agent="bot",e.Skill="skill"})(Ud||(jt.RoleTypes=Ud={}));jt.roleTypeZodSchema=zb.z.enum(["user","bot","skill"])});var Ld=d(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.addAIToActivity=void 0;var Db=(e,r,t)=>{var n;let i={type:"https://schema.org/Message","@type":"Message","@context":"https://schema.org","@id":"",additionalType:["AIGeneratedContent"],citation:r,usageInfo:t};(n=e.entities)!==null&&n!==void 0||(e.entities=[]),e.entities.push(i)};Ai.addAIToActivity=Db});var Nd=d(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.adaptiveCardInvokeActionZodSchema=void 0;var $r=N();xi.adaptiveCardInvokeActionZodSchema=$r.z.object({type:$r.z.string().min(1),id:$r.z.string().optional(),verb:$r.z.string().min(1),data:$r.z.record($r.z.string().min(1),$r.z.any())})});var zd=d(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.default="ffffffff-ffff-ffff-ffff-ffffffffffff"});var Dd=d(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.default="00000000-0000-0000-0000-000000000000"});var Vd=d(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});var Fn=d(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});var Vb=Vd();function $b(e){return typeof e=="string"&&Vb.default.test(e)}Rs.default=$b});var Rn=d(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var Wb=Fn();function Bb(e){if(!(0,Wb.default)(e))throw TypeError("Invalid UUID");let r;return Uint8Array.of((r=parseInt(e.slice(0,8),16))>>>24,r>>>16&255,r>>>8&255,r&255,(r=parseInt(e.slice(9,13),16))>>>8,r&255,(r=parseInt(e.slice(14,18),16))>>>8,r&255,(r=parseInt(e.slice(19,23),16))>>>8,r&255,(r=parseInt(e.slice(24,36),16))/1099511627776&255,r/4294967296&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255)}Zs.default=Bb});var Le=d(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.unsafeStringify=void 0;var Gb=Fn(),Y=[];for(let e=0;e<256;++e)Y.push((e+256).toString(16).slice(1));function $d(e,r=0){return(Y[e[r+0]]+Y[e[r+1]]+Y[e[r+2]]+Y[e[r+3]]+"-"+Y[e[r+4]]+Y[e[r+5]]+"-"+Y[e[r+6]]+Y[e[r+7]]+"-"+Y[e[r+8]]+Y[e[r+9]]+"-"+Y[e[r+10]]+Y[e[r+11]]+Y[e[r+12]]+Y[e[r+13]]+Y[e[r+14]]+Y[e[r+15]]).toLowerCase()}Zn.unsafeStringify=$d;function Yb(e,r=0){let t=$d(e,r);if(!(0,Gb.default)(t))throw TypeError("Stringified UUID is invalid");return t}Zn.default=Yb});var Ti=d(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});var Us,Hb=new Uint8Array(16);function Kb(){if(!Us){if(typeof crypto=="undefined"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Us=crypto.getRandomValues.bind(crypto)}return Us(Hb)}Ls.default=Kb});var Ns=d(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.updateV1State=void 0;var Wd=Ti(),Jb=Le(),Un={};function Qb(e,r,t){var o,a,u,l;let n,i=(o=e==null?void 0:e._v6)!=null?o:!1;if(e){let s=Object.keys(e);s.length===1&&s[0]==="_v6"&&(e=void 0)}if(e)n=Bd((l=(u=e.random)!=null?u:(a=e.rng)==null?void 0:a.call(e))!=null?l:(0,Wd.default)(),e.msecs,e.nsecs,e.clockseq,e.node,r,t);else{let s=Date.now(),f=(0,Wd.default)();Gd(Un,s,f),n=Bd(f,Un.msecs,Un.nsecs,i?void 0:Un.clockseq,i?void 0:Un.node,r,t)}return r!=null?r:(0,Jb.unsafeStringify)(n)}function Gd(e,r,t){var n,i;return(n=e.msecs)!=null||(e.msecs=-1/0),(i=e.nsecs)!=null||(e.nsecs=0),r===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):r>e.msecs?e.nsecs=0:r= 16");if(!o)o=new Uint8Array(16),a=0;else if(a<0||a+16>o.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`);r!=null||(r=Date.now()),t!=null||(t=0),n!=null||(n=(e[8]<<8|e[9])&16383),i!=null||(i=e.slice(10,16)),r+=122192928e5;let u=((r&268435455)*1e4+t)%4294967296;o[a++]=u>>>24&255,o[a++]=u>>>16&255,o[a++]=u>>>8&255,o[a++]=u&255;let l=r/4294967296*1e4&268435455;o[a++]=l>>>8&255,o[a++]=l&255,o[a++]=l>>>24&15|16,o[a++]=l>>>16&255,o[a++]=n>>>8|128,o[a++]=n&255;for(let s=0;s<6;++s)o[a++]=i[s];return o}Ln.default=Qb});var Ds=d(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var Xb=Rn(),eg=Le();function rg(e){let r=typeof e=="string"?(0,Xb.default)(e):e,t=tg(r);return typeof e=="string"?(0,eg.unsafeStringify)(t):t}zs.default=rg;function tg(e){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var Hd=d(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});function ng(e){let r=ag(e),t=og(r,e.length*8);return ig(t)}function ig(e){let r=new Uint8Array(e.length*4);for(let t=0;t>2]>>>t%4*8&255;return r}function Yd(e){return(e+64>>>9<<4)+14+1}function og(e,r){let t=new Uint32Array(Yd(r)).fill(0);t.set(e),t[r>>5]|=128<>2]|=(e[t]&255)<>16)+(r>>16)+(t>>16)<<16|t&65535}function ug(e,r){return e<>>32-r}function Ei(e,r,t,n,i,o){return Qe(ug(Qe(Qe(r,e),Qe(n,o)),i),t)}function X(e,r,t,n,i,o,a){return Ei(r&t|~r&n,e,r,i,o,a)}function ee(e,r,t,n,i,o,a){return Ei(r&n|t&~n,e,r,i,o,a)}function re(e,r,t,n,i,o,a){return Ei(r^t^n,e,r,i,o,a)}function te(e,r,t,n,i,o,a){return Ei(t^(r|~n),e,r,i,o,a)}Vs.default=ng});var Nn=d(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.URL=Ne.DNS=Ne.stringToBytes=void 0;var Kd=Rn(),sg=Le();function Jd(e){e=unescape(encodeURIComponent(e));let r=new Uint8Array(e.length);for(let t=0;t{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.URL=Wr.DNS=void 0;var lg=Hd(),$s=Nn(),Qd=Nn();Object.defineProperty(Wr,"DNS",{enumerable:!0,get:function(){return Qd.DNS}});Object.defineProperty(Wr,"URL",{enumerable:!0,get:function(){return Qd.URL}});function Ws(e,r,t,n){return(0,$s.default)(48,lg.default,e,r,t,n)}Ws.DNS=$s.DNS;Ws.URL=$s.URL;Wr.default=Ws});var ef=d(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var dg=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);Bs.default={randomUUID:dg}});var tf=d(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var rf=ef(),fg=Ti(),vg=Le();function pg(e,r,t){var i,o,a;if(rf.default.randomUUID&&!r&&!e)return rf.default.randomUUID();e=e||{};let n=(a=(o=e.random)!=null?o:(i=e.rng)==null?void 0:i.call(e))!=null?a:(0,fg.default)();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,r){if(t=t||0,t<0||t+16>r.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let u=0;u<16;++u)r[t+u]=n[u];return r}return(0,vg.unsafeStringify)(n)}Gs.default=pg});var nf=d(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});function hg(e,r,t,n){switch(e){case 0:return r&t^~r&n;case 1:return r^t^n;case 2:return r&t^r&n^t&n;case 3:return r^t^n}}function Ys(e,r){return e<>>32-r}function mg(e){let r=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(e.length+1);n.set(e),n[e.length]=128,e=n;let i=e.length/4+2,o=Math.ceil(i/16),a=new Array(o);for(let u=0;u>>0;b=m,m=v,v=Ys(f,30)>>>0,f=s,s=_}t[0]=t[0]+s>>>0,t[1]=t[1]+f>>>0,t[2]=t[2]+v>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+b>>>0}return Uint8Array.of(t[0]>>24,t[0]>>16,t[0]>>8,t[0],t[1]>>24,t[1]>>16,t[1]>>8,t[1],t[2]>>24,t[2]>>16,t[2]>>8,t[2],t[3]>>24,t[3]>>16,t[3]>>8,t[3],t[4]>>24,t[4]>>16,t[4]>>8,t[4])}Hs.default=mg});var af=d(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.URL=Br.DNS=void 0;var yg=nf(),Ks=Nn(),of=Nn();Object.defineProperty(Br,"DNS",{enumerable:!0,get:function(){return of.DNS}});Object.defineProperty(Br,"URL",{enumerable:!0,get:function(){return of.URL}});function Js(e,r,t,n){return(0,Ks.default)(80,yg.default,e,r,t,n)}Js.DNS=Ks.DNS;Js.URL=Ks.URL;Br.default=Js});var uf=d(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var _g=Le(),bg=Ns(),gg=Ds();function Og(e,r,t){e!=null||(e={}),t!=null||(t=0);let n=(0,bg.default)({...e,_v6:!0},new Uint8Array(16));if(n=(0,gg.default)(n),r){for(let i=0;i<16;i++)r[t+i]=n[i];return r}return(0,_g.unsafeStringify)(n)}Qs.default=Og});var sf=d(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var wg=Rn(),Sg=Le();function Pg(e){let r=typeof e=="string"?(0,wg.default)(e):e,t=qg(r);return typeof e=="string"?(0,Sg.unsafeStringify)(t):t}Xs.default=Pg;function qg(e){return Uint8Array.of((e[3]&15)<<4|e[4]>>4&15,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|e[6]&15,e[7],(e[1]&15)<<4|(e[2]&240)>>4,(e[2]&15)<<4|(e[3]&240)>>4,16|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}});var ff=d(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.updateV7State=void 0;var cf=Ti(),jg=Le(),ec={};function Cg(e,r,t){var i,o,a;let n;if(e)n=lf((a=(o=e.random)!=null?o:(i=e.rng)==null?void 0:i.call(e))!=null?a:(0,cf.default)(),e.msecs,e.seq,r,t);else{let u=Date.now(),l=(0,cf.default)();df(ec,u,l),n=lf(l,ec.msecs,ec.seq,r,t)}return r!=null?r:(0,jg.unsafeStringify)(n)}function df(e,r,t){var n,i;return(n=e.msecs)!=null||(e.msecs=-1/0),(i=e.seq)!=null||(e.seq=0),r>e.msecs?(e.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],e.msecs=r):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}zn.updateV7State=df;function lf(e,r,t,n,i=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return r!=null||(r=Date.now()),t!=null||(t=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9]),n[i++]=r/1099511627776&255,n[i++]=r/4294967296&255,n[i++]=r/16777216&255,n[i++]=r/65536&255,n[i++]=r/256&255,n[i++]=r&255,n[i++]=112|t>>>28&15,n[i++]=t>>>20&255,n[i++]=128|t>>>14&63,n[i++]=t>>>6&255,n[i++]=t<<2&255|e[10]&3,n[i++]=e[11],n[i++]=e[12],n[i++]=e[13],n[i++]=e[14],n[i++]=e[15],n}zn.default=Cg});var vf=d(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var Ig=Fn();function Ag(e){if(!(0,Ig.default)(e))throw TypeError("Invalid UUID");return parseInt(e.slice(14,15),16)}rc.default=Ag});var tc=d(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.version=Z.validate=Z.v7=Z.v6ToV1=Z.v6=Z.v5=Z.v4=Z.v3=Z.v1ToV6=Z.v1=Z.stringify=Z.parse=Z.NIL=Z.MAX=void 0;var xg=zd();Object.defineProperty(Z,"MAX",{enumerable:!0,get:function(){return xg.default}});var Tg=Dd();Object.defineProperty(Z,"NIL",{enumerable:!0,get:function(){return Tg.default}});var Eg=Rn();Object.defineProperty(Z,"parse",{enumerable:!0,get:function(){return Eg.default}});var Mg=Le();Object.defineProperty(Z,"stringify",{enumerable:!0,get:function(){return Mg.default}});var kg=Ns();Object.defineProperty(Z,"v1",{enumerable:!0,get:function(){return kg.default}});var Fg=Ds();Object.defineProperty(Z,"v1ToV6",{enumerable:!0,get:function(){return Fg.default}});var Rg=Xd();Object.defineProperty(Z,"v3",{enumerable:!0,get:function(){return Rg.default}});var Zg=tf();Object.defineProperty(Z,"v4",{enumerable:!0,get:function(){return Zg.default}});var Ug=af();Object.defineProperty(Z,"v5",{enumerable:!0,get:function(){return Ug.default}});var Lg=uf();Object.defineProperty(Z,"v6",{enumerable:!0,get:function(){return Lg.default}});var Ng=sf();Object.defineProperty(Z,"v6ToV1",{enumerable:!0,get:function(){return Ng.default}});var zg=ff();Object.defineProperty(Z,"v7",{enumerable:!0,get:function(){return zg.default}});var Dg=Fn();Object.defineProperty(Z,"validate",{enumerable:!0,get:function(){return Dg.default}});var Vg=vf();Object.defineProperty(Z,"version",{enumerable:!0,get:function(){return Vg.default}})});var nc=d(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.entityZodSchema=void 0;var pf=N();Mi.entityZodSchema=pf.z.object({type:pf.z.string().min(1)}).passthrough()});var hf=d(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.semanticActionZodSchema=void 0;var Dn=N(),$g=nc(),Wg=As();ki.semanticActionZodSchema=Dn.z.object({id:Dn.z.string().min(1),state:Dn.z.union([Wg.semanticActionStateTypesZodSchema,Dn.z.string().min(1)]),entities:Dn.z.record($g.entityZodSchema)})});var mf=d(Fi=>{"use strict";Object.defineProperty(Fi,"__esModule",{value:!0});Fi.cardActionZodSchema=void 0;var je=N(),Bg=Is();Fi.cardActionZodSchema=je.z.object({type:je.z.union([Bg.actionTypesZodSchema,je.z.string().min(1)]),title:je.z.string().min(1),image:je.z.string().min(1).optional(),text:je.z.string().min(1).optional(),displayText:je.z.string().min(1).optional(),value:je.z.any().optional(),channelData:je.z.unknown().optional(),imageAltText:je.z.string().min(1).optional()})});var yf=d(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.suggestedActionsZodSchema=void 0;var Ri=N(),Gg=mf();Zi.suggestedActionsZodSchema=Ri.z.object({to:Ri.z.array(Ri.z.string().min(1)),actions:Ri.z.array(Gg.cardActionZodSchema)})});var ic=d(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.activityEventNamesZodSchema=Ct.ActivityEventNames=void 0;var Yg=N(),_f;(function(e){e.ContinueConversation="ContinueConversation",e.CreateConversation="CreateConversation"})(_f||(Ct.ActivityEventNames=_f={}));Ct.activityEventNamesZodSchema=Yg.z.enum(["ContinueConversation","CreateConversation"])});var oc=d(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.activityImportanceZodSchema=It.ActivityImportance=void 0;var Hg=N(),bf;(function(e){e.Low="low",e.Normal="normal",e.High="high"})(bf||(It.ActivityImportance=bf={}));It.activityImportanceZodSchema=Hg.z.enum(["low","normal","high"])});var ac=d(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.activityTypesZodSchema=At.ActivityTypes=void 0;var Kg=N(),gf;(function(e){e.Message="message",e.ContactRelationUpdate="contactRelationUpdate",e.ConversationUpdate="conversationUpdate",e.Typing="typing",e.EndOfConversation="endOfConversation",e.Event="event",e.Invoke="invoke",e.InvokeResponse="invokeResponse",e.DeleteUserData="deleteUserData",e.MessageUpdate="messageUpdate",e.MessageDelete="messageDelete",e.InstallationUpdate="installationUpdate",e.MessageReaction="messageReaction",e.Suggestion="suggestion",e.Trace="trace",e.Handoff="handoff",e.Command="command",e.CommandResult="commandResult",e.Delay="delay"})(gf||(At.ActivityTypes=gf={}));At.activityTypesZodSchema=Kg.z.enum(["message","contactRelationUpdate","conversationUpdate","typing","endOfConversation","event","invoke","invokeResponse","deleteUserData","messageUpdate","messageDelete","installationUpdate","messageReaction","suggestion","trace","handoff","command","commandResult","delay"])});var Of=d(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.attachmentZodSchema=void 0;var xt=N();Ui.attachmentZodSchema=xt.z.object({contentType:xt.z.string().min(1),contentUrl:xt.z.string().min(1).optional(),content:xt.z.unknown().optional(),name:xt.z.string().min(1).optional(),thumbnailUrl:xt.z.string().min(1).optional()})});var uc=d(Li=>{"use strict";Object.defineProperty(Li,"__esModule",{value:!0});Li.channelAccountZodSchema=void 0;var Gr=N(),Jg=Ii();Li.channelAccountZodSchema=Gr.z.object({id:Gr.z.string().min(1).optional(),name:Gr.z.string().optional(),aadObjectId:Gr.z.string().min(1).optional(),role:Gr.z.union([Jg.roleTypeZodSchema,Gr.z.string().min(1)]).optional(),properties:Gr.z.unknown().optional()})});var sc=d(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.conversationAccountZodSchema=void 0;var Ce=N(),Qg=Ii();Ni.conversationAccountZodSchema=Ce.z.object({isGroup:Ce.z.boolean().optional(),conversationType:Ce.z.string().min(1).optional(),tenantId:Ce.z.string().min(1).optional(),id:Ce.z.string().min(1),name:Ce.z.string().min(1).optional(),aadObjectId:Ce.z.string().min(1).optional(),role:Ce.z.union([Qg.roleTypeZodSchema,Ce.z.string().min(1)]).optional(),properties:Ce.z.unknown().optional()})});var Sf=d(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.conversationReferenceZodSchema=void 0;var Vn=N(),wf=uc(),Xg=sc();zi.conversationReferenceZodSchema=Vn.z.object({activityId:Vn.z.string().min(1).optional(),user:wf.channelAccountZodSchema.optional(),locale:Vn.z.string().min(1).optional(),agent:wf.channelAccountZodSchema.optional().nullable(),conversation:Xg.conversationAccountZodSchema,channelId:Vn.z.string().min(1),serviceUrl:Vn.z.string().min(1).optional()})});var cc=d(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.deliveryModesZodSchema=Tt.DeliveryModes=void 0;var e0=N(),Pf;(function(e){e.Normal="normal",e.Notification="notification",e.ExpectReplies="expectReplies",e.Ephemeral="ephemeral"})(Pf||(Tt.DeliveryModes=Pf={}));Tt.deliveryModesZodSchema=e0.z.enum(["normal","notification","expectReplies","ephemeral"])});var lc=d(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.inputHintsZodSchema=Et.InputHints=void 0;var r0=N(),qf;(function(e){e.AcceptingInput="acceptingInput",e.IgnoringInput="ignoringInput",e.ExpectingInput="expectingInput"})(qf||(Et.InputHints=qf={}));Et.inputHintsZodSchema=r0.z.enum(["acceptingInput","ignoringInput","expectingInput"])});var dc=d(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.messageReactionTypesZodSchema=Mt.MessageReactionTypes=void 0;var t0=N(),jf;(function(e){e.Like="like",e.PlusOne="plusOne"})(jf||(Mt.MessageReactionTypes=jf={}));Mt.messageReactionTypesZodSchema=t0.z.enum(["like","plusOne"])});var Cf=d(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.messageReactionZodSchema=void 0;var fc=N(),n0=dc();Di.messageReactionZodSchema=fc.z.object({type:fc.z.union([n0.messageReactionTypesZodSchema,fc.z.string().min(1)])})});var vc=d(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.textFormatTypesZodSchema=kt.TextFormatTypes=void 0;var i0=N(),If;(function(e){e.Markdown="markdown",e.Plain="plain",e.Xml="xml"})(If||(kt.TextFormatTypes=If={}));kt.textFormatTypesZodSchema=i0.z.enum(["markdown","plain","xml"])});var Af=d(Vi=>{"use strict";Object.defineProperty(Vi,"__esModule",{value:!0});Vi.textHighlightZodSchema=void 0;var pc=N();Vi.textHighlightZodSchema=pc.z.object({text:pc.z.string().min(1),occurrence:pc.z.number()})});var Mf=d(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.Activity=Yr.activityZodSchema=void 0;var o0=tc(),A=N(),a0=hf(),u0=yf(),Ef=ic(),s0=oc(),Wi=ac(),c0=Of(),l0=xs(),$i=uc(),xf=Ts(),d0=sc(),f0=Sf(),v0=Es(),p0=cc(),h0=nc(),m0=lc(),Tf=Cf(),y0=vc(),_0=Af();Yr.activityZodSchema=A.z.object({type:A.z.union([Wi.activityTypesZodSchema,A.z.string().min(1)]),text:A.z.string().optional(),id:A.z.string().min(1).optional(),channelId:A.z.string().min(1).optional(),from:$i.channelAccountZodSchema.optional(),timestamp:A.z.union([A.z.date(),A.z.string().min(1).datetime().optional(),A.z.string().min(1).transform(e=>new Date(e)).optional()]),localTimestamp:A.z.string().min(1).transform(e=>new Date(e)).optional().or(A.z.date()).optional(),localTimezone:A.z.string().min(1).optional(),callerId:A.z.string().min(1).optional(),serviceUrl:A.z.string().min(1).optional(),conversation:d0.conversationAccountZodSchema.optional(),recipient:$i.channelAccountZodSchema.optional(),textFormat:A.z.union([y0.textFormatTypesZodSchema,A.z.string().min(1)]).optional(),attachmentLayout:A.z.union([l0.attachmentLayoutTypesZodSchema,A.z.string().min(1)]).optional(),membersAdded:A.z.array($i.channelAccountZodSchema).optional(),membersRemoved:A.z.array($i.channelAccountZodSchema).optional(),reactionsAdded:A.z.array(Tf.messageReactionZodSchema).optional(),reactionsRemoved:A.z.array(Tf.messageReactionZodSchema).optional(),topicName:A.z.string().min(1).optional(),historyDisclosed:A.z.boolean().optional(),locale:A.z.string().min(1).optional(),speak:A.z.string().min(1).optional(),inputHint:A.z.union([m0.inputHintsZodSchema,A.z.string().min(1)]).optional(),summary:A.z.string().min(1).optional(),suggestedActions:u0.suggestedActionsZodSchema.optional(),attachments:A.z.array(c0.attachmentZodSchema).optional(),entities:A.z.array(h0.entityZodSchema.passthrough()).optional(),channelData:A.z.any().optional(),action:A.z.string().min(1).optional(),replyToId:A.z.string().min(1).optional(),label:A.z.string().min(1).optional(),valueType:A.z.string().min(1).optional(),value:A.z.unknown().optional(),name:A.z.union([Ef.activityEventNamesZodSchema,A.z.string().min(1)]).optional(),relatesTo:f0.conversationReferenceZodSchema.optional(),code:A.z.union([v0.endOfConversationCodesZodSchema,A.z.string().min(1)]).optional(),expiration:A.z.string().min(1).datetime().optional(),importance:A.z.union([s0.activityImportanceZodSchema,A.z.string().min(1)]).optional(),deliveryMode:A.z.union([p0.deliveryModesZodSchema,A.z.string().min(1)]).optional(),listenFor:A.z.array(A.z.string().min(1)).optional(),textHighlights:A.z.array(_0.textHighlightZodSchema).optional(),semanticAction:a0.semanticActionZodSchema.optional()});var hc=class e{constructor(r){if(r===void 0)throw new Error("Invalid ActivityType: undefined");if(r===null)throw new Error("Invalid ActivityType: null");if(typeof r=="string"&&r.length===0)throw new Error("Invalid ActivityType: empty string");this.type=r}static fromJson(r){return this.fromObject(JSON.parse(r))}static fromObject(r){let t=Yr.activityZodSchema.passthrough().parse(r),n=new e(t.type);return Object.assign(n,t),n}static getContinuationActivity(r){let t={type:Wi.ActivityTypes.Event,name:Ef.ActivityEventNames.ContinueConversation,id:(0,o0.v4)(),channelId:r.channelId,locale:r.locale,serviceUrl:r.serviceUrl,conversation:r.conversation,recipient:r.agent,from:r.user,relatesTo:r};return e.fromObject(t)}getAppropriateReplyToId(){if(this.type!==Wi.ActivityTypes.ConversationUpdate||this.channelId!==xf.Channels.Directline&&this.channelId!==xf.Channels.Webchat)return this.id}getConversationReference(){if(this.recipient===null||this.recipient===void 0)throw new Error("Activity Recipient undefined");if(this.conversation===null||this.conversation===void 0)throw new Error("Activity Conversation undefined");if(this.channelId===null||this.channelId===void 0)throw new Error("Activity ChannelId undefined");return{activityId:this.getAppropriateReplyToId(),user:this.from,agent:this.recipient,conversation:this.conversation,channelId:this.channelId,locale:this.locale,serviceUrl:this.serviceUrl}}applyConversationReference(r,t=!1){var n,i,o;return this.channelId=r.channelId,(n=this.locale)!==null&&n!==void 0||(this.locale=r.locale),this.serviceUrl=r.serviceUrl,this.conversation=r.conversation,t?(this.from=r.user,this.recipient=(i=r.agent)!==null&&i!==void 0?i:void 0,r.activityId&&(this.id=r.activityId)):(this.from=(o=r.agent)!==null&&o!==void 0?o:void 0,this.recipient=r.user,r.activityId&&(this.replyToId=r.activityId)),this}clone(){let r=JSON.parse(JSON.stringify(this));for(let t in r)typeof r[t]=="string"&&!isNaN(Date.parse(r[t]))&&(r[t]=new Date(r[t]));return Object.setPrototypeOf(r,e.prototype),r}getMentions(r){let t=[];if(r.entities!==void 0)for(let n=0;n{var o;return i.type.toLowerCase()==="mention"?i.mentioned.id!==((o=this.recipient)===null||o===void 0?void 0:o.id):!0}))),this.text&&(this.text=e.removeAt(this.text)),this.entities!==void 0)){let i=this.getMentions(this);for(let o of i)o.text&&(o.text=(n=e.removeAt(o.text))===null||n===void 0?void 0:n.trim())}}static removeAt(r){if(!r)return r;let t;do{t=!1;let n=r.toLowerCase().indexOf("=0){let i=r.indexOf(">",n);if(i>0){let o=r.toLowerCase().indexOf("",i);if(o>0){let a=r.substring(o+5);a.length>0&&!/\s/.test(a[0])&&(a=` ${a}`),r=r.substring(0,o)+a;let u=r.substring(i+1,o),l=r.substring(0,n);l.length>0&&!/\s$/.test(l)&&(l+=" "),r=l+u+a,t=!0}}}}while(t);return r}removeMentionText(r){let n=this.getMentions(this).filter(i=>i.mentioned.id===r);return n.length>0&&this.text&&(this.text=this.text.replace(n[0].text,"").trim()),this.text||""}removeRecipientMention(){return this.recipient!=null&&this.recipient.id?this.removeMentionText(this.recipient.id):""}getReplyConversationReference(r){let t=this.getConversationReference();return t.activityId=r,t}toJsonString(){return JSON.stringify(this)}};Yr.Activity=hc});var kf=d(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});Bi.CallerIdConstants=void 0;Bi.CallerIdConstants={PublicAzureChannel:"urn:botframework:azure",USGovChannel:"urn:botframework:azureusgov",AgentPrefix:"urn:botframework:aadappid:"}});var Ff=d(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.activityTreatments=Ft.ActivityTreatments=void 0;var b0=N(),mc;(function(e){e.Targeted="targeted"})(mc||(Ft.ActivityTreatments=mc={}));Ft.activityTreatments=b0.z.nativeEnum(mc)});var yc=d(x=>{"use strict";var g0=x&&x.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),Rf=x&&x.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&g0(r,e,t)};Object.defineProperty(x,"__esModule",{value:!0});x.Logger=x.debug=x.ActivityTreatments=x.TextFormatTypes=x.MessageReactionTypes=x.InputHints=x.DeliveryModes=x.CallerIdConstants=x.ActivityTypes=x.ActivityImportance=x.ActivityEventNames=x.activityZodSchema=x.Activity=x.RoleTypes=x.MembershipTypes=x.MembershipSourceTypes=x.EndOfConversationCodes=x.Channels=x.AttachmentLayoutTypes=x.SemanticActionStateTypes=x.ActionTypes=void 0;var O0=Is();Object.defineProperty(x,"ActionTypes",{enumerable:!0,get:function(){return O0.ActionTypes}});var w0=As();Object.defineProperty(x,"SemanticActionStateTypes",{enumerable:!0,get:function(){return w0.SemanticActionStateTypes}});var S0=xs();Object.defineProperty(x,"AttachmentLayoutTypes",{enumerable:!0,get:function(){return S0.AttachmentLayoutTypes}});var P0=Ts();Object.defineProperty(x,"Channels",{enumerable:!0,get:function(){return P0.Channels}});var q0=Es();Object.defineProperty(x,"EndOfConversationCodes",{enumerable:!0,get:function(){return q0.EndOfConversationCodes}});var j0=Fd();Object.defineProperty(x,"MembershipSourceTypes",{enumerable:!0,get:function(){return j0.MembershipSourceTypes}});var C0=Zd();Object.defineProperty(x,"MembershipTypes",{enumerable:!0,get:function(){return C0.MembershipTypes}});var I0=Ii();Object.defineProperty(x,"RoleTypes",{enumerable:!0,get:function(){return I0.RoleTypes}});Rf(Ld(),x);Rf(Nd(),x);var Zf=Mf();Object.defineProperty(x,"Activity",{enumerable:!0,get:function(){return Zf.Activity}});Object.defineProperty(x,"activityZodSchema",{enumerable:!0,get:function(){return Zf.activityZodSchema}});var A0=ic();Object.defineProperty(x,"ActivityEventNames",{enumerable:!0,get:function(){return A0.ActivityEventNames}});var x0=oc();Object.defineProperty(x,"ActivityImportance",{enumerable:!0,get:function(){return x0.ActivityImportance}});var T0=ac();Object.defineProperty(x,"ActivityTypes",{enumerable:!0,get:function(){return T0.ActivityTypes}});var E0=kf();Object.defineProperty(x,"CallerIdConstants",{enumerable:!0,get:function(){return E0.CallerIdConstants}});var M0=cc();Object.defineProperty(x,"DeliveryModes",{enumerable:!0,get:function(){return M0.DeliveryModes}});var k0=lc();Object.defineProperty(x,"InputHints",{enumerable:!0,get:function(){return k0.InputHints}});var F0=dc();Object.defineProperty(x,"MessageReactionTypes",{enumerable:!0,get:function(){return F0.MessageReactionTypes}});var R0=vc();Object.defineProperty(x,"TextFormatTypes",{enumerable:!0,get:function(){return R0.TextFormatTypes}});var Z0=Ff();Object.defineProperty(x,"ActivityTreatments",{enumerable:!0,get:function(){return Z0.ActivityTreatments}});var Uf=dt();Object.defineProperty(x,"debug",{enumerable:!0,get:function(){return Uf.debug}});Object.defineProperty(x,"Logger",{enumerable:!0,get:function(){return Uf.Logger}})});var Lf={};qr(Lf,{ExecuteTurnRequest:()=>_c});var _c,Nf=Pr(()=>{"use strict";_c=class{constructor(r){this.activity=r}}});var zf=d((kU,U0)=>{U0.exports={name:"@microsoft/agents-copilotstudio-client",version:"0.1.0",homepage:"https://github.com/microsoft/Agents-for-js",repository:{type:"git",url:"git+https://github.com/microsoft/Agents-for-js.git"},author:{name:"Microsoft",email:"agentssdk@microsoft.com",url:"https://aka.ms/Agents"},description:"Microsoft Copilot Studio Client for JavaScript. Copilot Studio Client.",keywords:["Agents","copilotstudio","powerplatform"],main:"dist/src/index.js",types:"dist/src/index.d.ts",browser:{os:"./src/browser/os.ts",crypto:"./src/browser/crypto.ts"},scripts:{"build:browser":"esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts"},dependencies:{"@microsoft/agents-activity":"file:../agents-activity","eventsource-client":"^1.2.0",rxjs:"7.8.2",uuid:"^11.1.0"},license:"MIT",files:["README.md","dist/src","src","package.json"],exports:{".":{types:"./dist/src/index.d.ts",import:{browser:"./dist/src/browser.mjs",default:"./dist/src/index.js"},require:{default:"./dist/src/index.js"}},"./package.json":"./package.json"},engines:{node:">=20.0.0"}}});var Df={};qr(Df,{default:()=>L0});var L0,Vf=Pr(()=>{"use strict";L0={}});var $f=d(Zt=>{"use strict";var N0=Zt&&Zt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Zt,"__esModule",{value:!0});Zt.CopilotStudioClient=void 0;var z0=Gl(),Oc=(od(),Fe(id)),bc=yc(),D0=(Nf(),Fe(Lf)),V0=dt(),$0=zf(),gc=N0((Vf(),Fe(Df))),he=(0,V0.debug)("copilot-studio:client"),Rt=class e{constructor(r,t){this.conversationId="",this.settings=r,this.token=t}async*postRequestAsync(r,t,n="POST"){var i,o;he.debug(`>>> SEND TO ${r}`);let a=(0,z0.createEventSource)({url:r,headers:{Authorization:`Bearer ${this.token}`,"User-Agent":e.getProductInfo(),"Content-Type":"application/json",Accept:"text/event-stream"},body:t?JSON.stringify(t):void 0,method:n,fetch:async(u,l)=>{let s=await fetch(u,l);return this.processResponseHeaders(s.headers),s}});try{for await(let{data:u,event:l}of a){if(u&&l==="activity")try{let s=bc.Activity.fromJson(u);switch(s.type){case bc.ActivityTypes.Message:this.conversationId.trim()||(this.conversationId=(o=(i=s.conversation)===null||i===void 0?void 0:i.id)!==null&&o!==void 0?o:"",he.debug(`Conversation ID: ${this.conversationId}`)),yield s;break;default:he.debug(`Activity type: ${s.type}`),yield s;break}}catch(s){he.error("Failed to parse activity:",s)}else if(l==="end"){he.debug("Stream complete");break}if(a.readyState==="closed"){he.debug("Connection closed");break}}}finally{a.close()}}static getProductInfo(){let r=`CopilotStudioClient.agents-sdk-js/${$0.version}`,t;return typeof window!="undefined"&&window.navigator?t=`${r} ${navigator.userAgent}`:t=`${r} nodejs/${process.version} ${gc.default.platform()}-${gc.default.arch()}/${gc.default.release()}`,he.debug(`User-Agent: ${t}`),t}processResponseHeaders(r){var t,n;if(this.settings.useExperimentalEndpoint&&!(!((t=this.settings.directConnectUrl)===null||t===void 0)&&t.trim())){let o=r==null?void 0:r.get(e.islandExperimentalUrlHeaderKey);o&&(this.settings.directConnectUrl=o,he.debug(`Island Experimental URL: ${o}`))}this.conversationId=(n=r==null?void 0:r.get(e.conversationIdHeaderKey))!==null&&n!==void 0?n:"",this.conversationId&&he.debug(`Conversation ID: ${this.conversationId}`);let i=new Headers;r.forEach((o,a)=>{a.toLowerCase()!=="authorization"&&a.toLowerCase()!==e.conversationIdHeaderKey.toLowerCase()&&i.set(a,o)}),he.debug("Headers received:",i)}async*startConversationAsync(r=!0){let t=(0,Oc.getCopilotStudioConnectionUrl)(this.settings),n={emitStartConversationEvent:r};he.info("Starting conversation ..."),yield*this.postRequestAsync(t,n,"POST")}async*askQuestionAsync(r,t=this.conversationId){let i={type:"message",text:r,conversation:{id:t}},o=bc.Activity.fromObject(i);yield*this.sendActivity(o)}async*sendActivity(r,t=this.conversationId){var n,i;let o=(i=(n=r.conversation)===null||n===void 0?void 0:n.id)!==null&&i!==void 0?i:t,a=(0,Oc.getCopilotStudioConnectionUrl)(this.settings,o),u=new D0.ExecuteTurnRequest(r);he.info("Sending activity...",r),yield*this.postRequestAsync(a,u,"POST")}};Zt.CopilotStudioClient=Rt;Rt.conversationIdHeaderKey="x-ms-conversationid";Rt.islandExperimentalUrlHeaderKey="x-ms-d2e-experimental";Rt.scopeFromSettings=Oc.getTokenAudience});var Bf=d(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0})});var L=d(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.isFunction=void 0;function W0(e){return typeof e=="function"}Gi.isFunction=W0});var Xe=d(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.createErrorClass=void 0;function B0(e){var r=function(n){Error.call(n),n.stack=new Error().stack},t=e(r);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}Yi.createErrorClass=B0});var wc=d(Hi=>{"use strict";Object.defineProperty(Hi,"__esModule",{value:!0});Hi.UnsubscriptionError=void 0;var G0=Xe();Hi.UnsubscriptionError=G0.createErrorClass(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription: +`+t.map(function(n,i){return i+1+") "+n.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=t}})});var ze=d(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.arrRemove=void 0;function Y0(e,r){if(e){var t=e.indexOf(r);0<=t&&e.splice(t,1)}}Ki.arrRemove=Y0});var de=d(ue=>{"use strict";var Gf=ue&&ue.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},Yf=ue&&ue.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Hf=ue&&ue.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.config=void 0;Ji.config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1}});var qc=d(Ie=>{"use strict";var Qf=Ie&&Ie.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Xf=Ie&&Ie.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.reportUnhandledError=void 0;var K0=Ut(),J0=qc();function Q0(e){J0.timeoutProvider.setTimeout(function(){var r=K0.config.onUnhandledError;if(r)r(e);else throw e})}Qi.reportUnhandledError=Q0});var H=d(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.noop=void 0;function X0(){}Xi.noop=X0});var ev=d(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.createNotification=Ae.nextNotification=Ae.errorNotification=Ae.COMPLETE_NOTIFICATION=void 0;Ae.COMPLETE_NOTIFICATION=(function(){return eo("C",void 0,void 0)})();function e1(e){return eo("E",void 0,e)}Ae.errorNotification=e1;function r1(e){return eo("N",e,void 0)}Ae.nextNotification=r1;function eo(e,r,t){return{kind:e,value:r,error:t}}Ae.createNotification=eo});var ro=d(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.captureError=Lt.errorContext=void 0;var rv=Ut(),Hr=null;function t1(e){if(rv.config.useDeprecatedSynchronousErrorHandling){var r=!Hr;if(r&&(Hr={errorThrown:!1,error:null}),e(),r){var t=Hr,n=t.errorThrown,i=t.error;if(Hr=null,n)throw i}}else e()}Lt.errorContext=t1;function n1(e){rv.config.useDeprecatedSynchronousErrorHandling&&Hr&&(Hr.errorThrown=!0,Hr.error=e)}Lt.captureError=n1});var Nt=d(be=>{"use strict";var iv=be&&be.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(be,"__esModule",{value:!0});be.EMPTY_OBSERVER=be.SafeSubscriber=be.Subscriber=void 0;var i1=L(),tv=de(),xc=Ut(),o1=jc(),nv=H(),Cc=ev(),a1=qc(),u1=ro(),ov=(function(e){iv(r,e);function r(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,tv.isSubscription(t)&&t.add(n)):n.destination=be.EMPTY_OBSERVER,n}return r.create=function(t,n,i){return new av(t,n,i)},r.prototype.next=function(t){this.isStopped?Ac(Cc.nextNotification(t),this):this._next(t)},r.prototype.error=function(t){this.isStopped?Ac(Cc.errorNotification(t),this):(this.isStopped=!0,this._error(t))},r.prototype.complete=function(){this.isStopped?Ac(Cc.COMPLETE_NOTIFICATION,this):(this.isStopped=!0,this._complete())},r.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},r.prototype._next=function(t){this.destination.next(t)},r.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},r.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},r})(tv.Subscription);be.Subscriber=ov;var s1=Function.prototype.bind;function Ic(e,r){return s1.call(e,r)}var c1=(function(){function e(r){this.partialObserver=r}return e.prototype.next=function(r){var t=this.partialObserver;if(t.next)try{t.next(r)}catch(n){to(n)}},e.prototype.error=function(r){var t=this.partialObserver;if(t.error)try{t.error(r)}catch(n){to(n)}else to(r)},e.prototype.complete=function(){var r=this.partialObserver;if(r.complete)try{r.complete()}catch(t){to(t)}},e})(),av=(function(e){iv(r,e);function r(t,n,i){var o=e.call(this)||this,a;if(i1.isFunction(t)||!t)a={next:t!=null?t:void 0,error:n!=null?n:void 0,complete:i!=null?i:void 0};else{var u;o&&xc.config.useDeprecatedNextContext?(u=Object.create(t),u.unsubscribe=function(){return o.unsubscribe()},a={next:t.next&&Ic(t.next,u),error:t.error&&Ic(t.error,u),complete:t.complete&&Ic(t.complete,u)}):a=t}return o.destination=new c1(a),o}return r})(ov);be.SafeSubscriber=av;function to(e){xc.config.useDeprecatedSynchronousErrorHandling?u1.captureError(e):o1.reportUnhandledError(e)}function l1(e){throw e}function Ac(e,r){var t=xc.config.onStoppedNotification;t&&a1.timeoutProvider.setTimeout(function(){return t(e,r)})}be.EMPTY_OBSERVER={closed:!0,next:nv.noop,error:l1,complete:nv.noop}});var Wn=d(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.observable=void 0;no.observable=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})()});var K=d(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.identity=void 0;function d1(e){return e}io.identity=d1});var Bn=d(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.pipeFromArray=zt.pipe=void 0;var f1=K();function v1(){for(var e=[],r=0;r{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.Observable=void 0;var Ec=Nt(),p1=de(),h1=Wn(),m1=Bn(),y1=Ut(),Tc=L(),_1=ro(),b1=(function(){function e(r){r&&(this._subscribe=r)}return e.prototype.lift=function(r){var t=new e;return t.source=this,t.operator=r,t},e.prototype.subscribe=function(r,t,n){var i=this,o=O1(r)?r:new Ec.SafeSubscriber(r,t,n);return _1.errorContext(function(){var a=i,u=a.operator,l=a.source;o.add(u?u.call(o,l):l?i._subscribe(o):i._trySubscribe(o))}),o},e.prototype._trySubscribe=function(r){try{return this._subscribe(r)}catch(t){r.error(t)}},e.prototype.forEach=function(r,t){var n=this;return t=sv(t),new t(function(i,o){var a=new Ec.SafeSubscriber({next:function(u){try{r(u)}catch(l){o(l),a.unsubscribe()}},error:o,complete:i});n.subscribe(a)})},e.prototype._subscribe=function(r){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(r)},e.prototype[h1.observable]=function(){return this},e.prototype.pipe=function(){for(var r=[],t=0;t{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.operate=Dt.hasLift=void 0;var w1=L();function cv(e){return w1.isFunction(e==null?void 0:e.lift)}Dt.hasLift=cv;function S1(e){return function(r){if(cv(r))return r.lift(function(t){try{return e(t,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}Dt.operate=S1});var C=d(er=>{"use strict";var P1=er&&er.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(er,"__esModule",{value:!0});er.OperatorSubscriber=er.createOperatorSubscriber=void 0;var q1=Nt();function j1(e,r,t,n,i){return new lv(e,r,t,n,i)}er.createOperatorSubscriber=j1;var lv=(function(e){P1(r,e);function r(t,n,i,o,a,u){var l=e.call(this,t)||this;return l.onFinalize=a,l.shouldUnsubscribe=u,l._next=n?function(s){try{n(s)}catch(f){t.error(f)}}:e.prototype._next,l._error=o?function(s){try{o(s)}catch(f){t.error(f)}finally{this.unsubscribe()}}:e.prototype._error,l._complete=i?function(){try{i()}catch(s){t.error(s)}finally{this.unsubscribe()}}:e.prototype._complete,l}return r.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},r})(q1.Subscriber);er.OperatorSubscriber=lv});var Mc=d(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.refCount=void 0;var C1=j(),I1=C();function A1(){return C1.operate(function(e,r){var t=null;e._refCount++;var n=I1.createOperatorSubscriber(r,void 0,void 0,void 0,function(){if(!e||e._refCount<=0||0<--e._refCount){t=null;return}var i=e._connection,o=t;t=null,i&&(!o||i===o)&&i.unsubscribe(),r.unsubscribe()});e.subscribe(n),n.closed||(t=e.connect())})}ao.refCount=A1});var Gn=d(Vt=>{"use strict";var x1=Vt&&Vt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Vt,"__esModule",{value:!0});Vt.ConnectableObservable=void 0;var T1=z(),dv=de(),E1=Mc(),M1=C(),k1=j(),F1=(function(e){x1(r,e);function r(t,n){var i=e.call(this)||this;return i.source=t,i.subjectFactory=n,i._subject=null,i._refCount=0,i._connection=null,k1.hasLift(t)&&(i.lift=t.lift),i}return r.prototype._subscribe=function(t){return this.getSubject().subscribe(t)},r.prototype.getSubject=function(){var t=this._subject;return(!t||t.isStopped)&&(this._subject=this.subjectFactory()),this._subject},r.prototype._teardown=function(){this._refCount=0;var t=this._connection;this._subject=this._connection=null,t==null||t.unsubscribe()},r.prototype.connect=function(){var t=this,n=this._connection;if(!n){n=this._connection=new dv.Subscription;var i=this.getSubject();n.add(this.source.subscribe(M1.createOperatorSubscriber(i,void 0,function(){t._teardown(),i.complete()},function(o){t._teardown(),i.error(o)},function(){return t._teardown()}))),n.closed&&(this._connection=null,n=dv.Subscription.EMPTY)}return n},r.prototype.refCount=function(){return E1.refCount()(this)},r})(T1.Observable);Vt.ConnectableObservable=F1});var fv=d(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.performanceTimestampProvider=void 0;Yn.performanceTimestampProvider={now:function(){return(Yn.performanceTimestampProvider.delegate||performance).now()},delegate:void 0}});var kc=d(ge=>{"use strict";var vv=ge&&ge.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},pv=ge&&ge.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.animationFrames=void 0;var Z1=z(),U1=fv(),hv=kc();function L1(e){return e?mv(e):N1}uo.animationFrames=L1;function mv(e){return new Z1.Observable(function(r){var t=e||U1.performanceTimestampProvider,n=t.now(),i=0,o=function(){r.closed||(i=hv.animationFrameProvider.requestAnimationFrame(function(a){i=0;var u=t.now();r.next({timestamp:e?u:a,elapsed:u-n}),o()}))};return o(),function(){i&&hv.animationFrameProvider.cancelAnimationFrame(i)}})}var N1=mv()});var Fc=d(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.ObjectUnsubscribedError=void 0;var z1=Xe();so.ObjectUnsubscribedError=z1.createErrorClass(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})});var J=d(xe=>{"use strict";var bv=xe&&xe.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),D1=xe&&xe.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(xe,"__esModule",{value:!0});xe.AnonymousSubject=xe.Subject=void 0;var _v=z(),Zc=de(),V1=Fc(),$1=ze(),Rc=ro(),gv=(function(e){bv(r,e);function r(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return r.prototype.lift=function(t){var n=new Uc(this,this);return n.operator=t,n},r.prototype._throwIfClosed=function(){if(this.closed)throw new V1.ObjectUnsubscribedError},r.prototype.next=function(t){var n=this;Rc.errorContext(function(){var i,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var a=D1(n.currentObservers),u=a.next();!u.done;u=a.next()){var l=u.value;l.next(t)}}catch(s){i={error:s}}finally{try{u&&!u.done&&(o=a.return)&&o.call(a)}finally{if(i)throw i.error}}}})},r.prototype.error=function(t){var n=this;Rc.errorContext(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=t;for(var i=n.observers;i.length;)i.shift().error(t)}})},r.prototype.complete=function(){var t=this;Rc.errorContext(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var n=t.observers;n.length;)n.shift().complete()}})},r.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(r.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),r.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},r.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},r.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,a=i.isStopped,u=i.observers;return o||a?Zc.EMPTY_SUBSCRIPTION:(this.currentObservers=null,u.push(t),new Zc.Subscription(function(){n.currentObservers=null,$1.arrRemove(u,t)}))},r.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,a=n.isStopped;i?t.error(o):a&&t.complete()},r.prototype.asObservable=function(){var t=new _v.Observable;return t.source=this,t},r.create=function(t,n){return new Uc(t,n)},r})(_v.Observable);xe.Subject=gv;var Uc=(function(e){bv(r,e);function r(t,n){var i=e.call(this)||this;return i.destination=t,i.source=n,i}return r.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},r.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},r.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},r.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:Zc.EMPTY_SUBSCRIPTION},r})(gv);xe.AnonymousSubject=Uc});var Lc=d($t=>{"use strict";var W1=$t&&$t.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty($t,"__esModule",{value:!0});$t.BehaviorSubject=void 0;var B1=J(),G1=(function(e){W1(r,e);function r(t){var n=e.call(this)||this;return n._value=t,n}return Object.defineProperty(r.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),r.prototype._subscribe=function(t){var n=e.prototype._subscribe.call(this,t);return!n.closed&&t.next(this._value),n},r.prototype.getValue=function(){var t=this,n=t.hasError,i=t.thrownError,o=t._value;if(n)throw i;return this._throwIfClosed(),o},r.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},r})(B1.Subject);$t.BehaviorSubject=G1});var co=d(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.dateTimestampProvider=void 0;Hn.dateTimestampProvider={now:function(){return(Hn.dateTimestampProvider.delegate||Date).now()},delegate:void 0}});var lo=d(Wt=>{"use strict";var Y1=Wt&&Wt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Wt,"__esModule",{value:!0});Wt.ReplaySubject=void 0;var H1=J(),K1=co(),J1=(function(e){Y1(r,e);function r(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=K1.dateTimestampProvider);var o=e.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return r.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,a=n._infiniteTimeWindow,u=n._timestampProvider,l=n._windowTime;i||(o.push(t),!a&&o.push(u.now()+l)),this._trimBuffer(),e.prototype.next.call(this,t)},r.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,a=i._buffer,u=a.slice(),l=0;l{"use strict";var Q1=Bt&&Bt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Bt,"__esModule",{value:!0});Bt.AsyncSubject=void 0;var X1=J(),eO=(function(e){Q1(r,e);function r(){var t=e!==null&&e.apply(this,arguments)||this;return t._value=null,t._hasValue=!1,t._isComplete=!1,t}return r.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n._hasValue,a=n._value,u=n.thrownError,l=n.isStopped,s=n._isComplete;i?t.error(u):(l||s)&&(o&&t.next(a),t.complete())},r.prototype.next=function(t){this.isStopped||(this._value=t,this._hasValue=!0)},r.prototype.complete=function(){var t=this,n=t._hasValue,i=t._value,o=t._isComplete;o||(this._isComplete=!0,n&&e.prototype.next.call(this,i),e.prototype.complete.call(this))},r})(X1.Subject);Bt.AsyncSubject=eO});var Ov=d(Gt=>{"use strict";var rO=Gt&&Gt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Gt,"__esModule",{value:!0});Gt.Action=void 0;var tO=de(),nO=(function(e){rO(r,e);function r(t,n){return e.call(this)||this}return r.prototype.schedule=function(t,n){return n===void 0&&(n=0),this},r})(tO.Subscription);Gt.Action=nO});var Pv=d(Te=>{"use strict";var wv=Te&&Te.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Sv=Te&&Te.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var iO=Yt&&Yt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Yt,"__esModule",{value:!0});Yt.AsyncAction=void 0;var oO=Ov(),qv=Pv(),aO=ze(),uO=(function(e){iO(r,e);function r(t,n){var i=e.call(this,t,n)||this;return i.scheduler=t,i.work=n,i.pending=!1,i}return r.prototype.schedule=function(t,n){var i;if(n===void 0&&(n=0),this.closed)return this;this.state=t;var o=this.id,a=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(a,o,n)),this.pending=!0,this.delay=n,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(a,this.id,n),this},r.prototype.requestAsyncId=function(t,n,i){return i===void 0&&(i=0),qv.intervalProvider.setInterval(t.flush.bind(t,this),i)},r.prototype.recycleAsyncId=function(t,n,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return n;n!=null&&qv.intervalProvider.clearInterval(n)},r.prototype.execute=function(t,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,n);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},r.prototype._execute=function(t,n){var i=!1,o;try{this.work(t)}catch(a){i=!0,o=a||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),o},r.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,i=t.scheduler,o=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,aO.arrRemove(o,this),n!=null&&(this.id=this.recycleAsyncId(i,n,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},r})(oO.Action);Yt.AsyncAction=uO});var Cv=d(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.TestTools=Kt.Immediate=void 0;var sO=1,Nc,vo={};function jv(e){return e in vo?(delete vo[e],!0):!1}Kt.Immediate={setImmediate:function(e){var r=sO++;return vo[r]=!0,Nc||(Nc=Promise.resolve()),Nc.then(function(){return jv(r)&&e()}),r},clearImmediate:function(e){jv(e)}};Kt.TestTools={pending:function(){return Object.keys(vo).length}}});var Av=d(Ee=>{"use strict";var cO=Ee&&Ee.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},lO=Ee&&Ee.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var vO=Jt&&Jt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Jt,"__esModule",{value:!0});Jt.AsapAction=void 0;var pO=Ht(),xv=Av(),hO=(function(e){vO(r,e);function r(t,n){var i=e.call(this,t,n)||this;return i.scheduler=t,i.work=n,i}return r.prototype.requestAsyncId=function(t,n,i){return i===void 0&&(i=0),i!==null&&i>0?e.prototype.requestAsyncId.call(this,t,n,i):(t.actions.push(this),t._scheduled||(t._scheduled=xv.immediateProvider.setImmediate(t.flush.bind(t,void 0))))},r.prototype.recycleAsyncId=function(t,n,i){var o;if(i===void 0&&(i=0),i!=null?i>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,t,n,i);var a=t.actions;n!=null&&((o=a[a.length-1])===null||o===void 0?void 0:o.id)!==n&&(xv.immediateProvider.clearImmediate(n),t._scheduled===n&&(t._scheduled=void 0))},r})(pO.AsyncAction);Jt.AsapAction=hO});var zc=d(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.Scheduler=void 0;var mO=co(),yO=(function(){function e(r,t){t===void 0&&(t=e.now),this.schedulerActionCtor=r,this.now=t}return e.prototype.schedule=function(r,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,r).schedule(n,t)},e.now=mO.dateTimestampProvider.now,e})();po.Scheduler=yO});var Xt=d(Qt=>{"use strict";var _O=Qt&&Qt.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(Qt,"__esModule",{value:!0});Qt.AsyncScheduler=void 0;var Ev=zc(),bO=(function(e){_O(r,e);function r(t,n){n===void 0&&(n=Ev.Scheduler.now);var i=e.call(this,t,n)||this;return i.actions=[],i._active=!1,i}return r.prototype.flush=function(t){var n=this.actions;if(this._active){n.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=n.shift());if(this._active=!1,i){for(;t=n.shift();)t.unsubscribe();throw i}},r})(Ev.Scheduler);Qt.AsyncScheduler=bO});var Mv=d(en=>{"use strict";var gO=en&&en.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(en,"__esModule",{value:!0});en.AsapScheduler=void 0;var OO=Xt(),wO=(function(e){gO(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype.flush=function(t){this._active=!0;var n=this._scheduled;this._scheduled=void 0;var i=this.actions,o;t=t||i.shift();do if(o=t.execute(t.state,t.delay))break;while((t=i[0])&&t.id===n&&i.shift());if(this._active=!1,o){for(;(t=i[0])&&t.id===n&&i.shift();)t.unsubscribe();throw o}},r})(OO.AsyncScheduler);en.AsapScheduler=wO});var kv=d(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.asap=Kr.asapScheduler=void 0;var SO=Tv(),PO=Mv();Kr.asapScheduler=new PO.AsapScheduler(SO.AsapAction);Kr.asap=Kr.asapScheduler});var se=d(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.async=Jr.asyncScheduler=void 0;var qO=Ht(),jO=Xt();Jr.asyncScheduler=new jO.AsyncScheduler(qO.AsyncAction);Jr.async=Jr.asyncScheduler});var Fv=d(rn=>{"use strict";var CO=rn&&rn.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(rn,"__esModule",{value:!0});rn.QueueAction=void 0;var IO=Ht(),AO=(function(e){CO(r,e);function r(t,n){var i=e.call(this,t,n)||this;return i.scheduler=t,i.work=n,i}return r.prototype.schedule=function(t,n){return n===void 0&&(n=0),n>0?e.prototype.schedule.call(this,t,n):(this.delay=n,this.state=t,this.scheduler.flush(this),this)},r.prototype.execute=function(t,n){return n>0||this.closed?e.prototype.execute.call(this,t,n):this._execute(t,n)},r.prototype.requestAsyncId=function(t,n,i){return i===void 0&&(i=0),i!=null&&i>0||i==null&&this.delay>0?e.prototype.requestAsyncId.call(this,t,n,i):(t.flush(this),0)},r})(IO.AsyncAction);rn.QueueAction=AO});var Rv=d(tn=>{"use strict";var xO=tn&&tn.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(tn,"__esModule",{value:!0});tn.QueueScheduler=void 0;var TO=Xt(),EO=(function(e){xO(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r})(TO.AsyncScheduler);tn.QueueScheduler=EO});var Zv=d(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.queue=Qr.queueScheduler=void 0;var MO=Fv(),kO=Rv();Qr.queueScheduler=new kO.QueueScheduler(MO.QueueAction);Qr.queue=Qr.queueScheduler});var Lv=d(nn=>{"use strict";var FO=nn&&nn.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(nn,"__esModule",{value:!0});nn.AnimationFrameAction=void 0;var RO=Ht(),Uv=kc(),ZO=(function(e){FO(r,e);function r(t,n){var i=e.call(this,t,n)||this;return i.scheduler=t,i.work=n,i}return r.prototype.requestAsyncId=function(t,n,i){return i===void 0&&(i=0),i!==null&&i>0?e.prototype.requestAsyncId.call(this,t,n,i):(t.actions.push(this),t._scheduled||(t._scheduled=Uv.animationFrameProvider.requestAnimationFrame(function(){return t.flush(void 0)})))},r.prototype.recycleAsyncId=function(t,n,i){var o;if(i===void 0&&(i=0),i!=null?i>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,t,n,i);var a=t.actions;n!=null&&n===t._scheduled&&((o=a[a.length-1])===null||o===void 0?void 0:o.id)!==n&&(Uv.animationFrameProvider.cancelAnimationFrame(n),t._scheduled=void 0)},r})(RO.AsyncAction);nn.AnimationFrameAction=ZO});var Nv=d(on=>{"use strict";var UO=on&&on.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(on,"__esModule",{value:!0});on.AnimationFrameScheduler=void 0;var LO=Xt(),NO=(function(e){UO(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype.flush=function(t){this._active=!0;var n;t?n=t.id:(n=this._scheduled,this._scheduled=void 0);var i=this.actions,o;t=t||i.shift();do if(o=t.execute(t.state,t.delay))break;while((t=i[0])&&t.id===n&&i.shift());if(this._active=!1,o){for(;(t=i[0])&&t.id===n&&i.shift();)t.unsubscribe();throw o}},r})(LO.AsyncScheduler);on.AnimationFrameScheduler=NO});var zv=d(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.animationFrame=Xr.animationFrameScheduler=void 0;var zO=Lv(),DO=Nv();Xr.animationFrameScheduler=new DO.AnimationFrameScheduler(zO.AnimationFrameAction);Xr.animationFrame=Xr.animationFrameScheduler});var $v=d(rr=>{"use strict";var Dv=rr&&rr.__extends||(function(){var e=function(r,t){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(n[o]=i[o])},e(r,t)};return function(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");e(r,t);function n(){this.constructor=r}r.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})();Object.defineProperty(rr,"__esModule",{value:!0});rr.VirtualAction=rr.VirtualTimeScheduler=void 0;var VO=Ht(),$O=de(),WO=Xt(),BO=(function(e){Dv(r,e);function r(t,n){t===void 0&&(t=Vv),n===void 0&&(n=1/0);var i=e.call(this,t,function(){return i.frame})||this;return i.maxFrames=n,i.frame=0,i.index=-1,i}return r.prototype.flush=function(){for(var t=this,n=t.actions,i=t.maxFrames,o,a;(a=n[0])&&a.delay<=i&&(n.shift(),this.frame=a.delay,!(o=a.execute(a.state,a.delay))););if(o){for(;a=n.shift();)a.unsubscribe();throw o}},r.frameTimeFactor=10,r})(WO.AsyncScheduler);rr.VirtualTimeScheduler=BO;var Vv=(function(e){Dv(r,e);function r(t,n,i){i===void 0&&(i=t.index+=1);var o=e.call(this,t,n)||this;return o.scheduler=t,o.work=n,o.index=i,o.active=!0,o.index=t.index=i,o}return r.prototype.schedule=function(t,n){if(n===void 0&&(n=0),Number.isFinite(n)){if(!this.id)return e.prototype.schedule.call(this,t,n);this.active=!1;var i=new r(this.scheduler,this.work);return this.add(i),i.schedule(t,n)}else return $O.Subscription.EMPTY},r.prototype.requestAsyncId=function(t,n,i){i===void 0&&(i=0),this.delay=t.frame+i;var o=t.actions;return o.push(this),o.sort(r.sortActions),1},r.prototype.recycleAsyncId=function(t,n,i){i===void 0&&(i=0)},r.prototype._execute=function(t,n){if(this.active===!0)return e.prototype._execute.call(this,t,n)},r.sortActions=function(t,n){return t.delay===n.delay?t.index===n.index?0:t.index>n.index?1:-1:t.delay>n.delay?1:-1},r})(VO.AsyncAction);rr.VirtualAction=Vv});var Oe=d(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.empty=et.EMPTY=void 0;var Wv=z();et.EMPTY=new Wv.Observable(function(e){return e.complete()});function GO(e){return e?YO(e):et.EMPTY}et.empty=GO;function YO(e){return new Wv.Observable(function(r){return e.schedule(function(){return r.complete()})})}});var Kn=d(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.isScheduler=void 0;var HO=L();function KO(e){return e&&HO.isFunction(e.schedule)}ho.isScheduler=KO});var ce=d(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.popNumber=tr.popScheduler=tr.popResultSelector=void 0;var JO=L(),QO=Kn();function Dc(e){return e[e.length-1]}function XO(e){return JO.isFunction(Dc(e))?e.pop():void 0}tr.popResultSelector=XO;function ew(e){return QO.isScheduler(Dc(e))?e.pop():void 0}tr.popScheduler=ew;function rw(e,r){return typeof Dc(e)=="number"?e.pop():r}tr.popNumber=rw});var yo=d(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.isArrayLike=void 0;mo.isArrayLike=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"})});var Vc=d(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.isPromise=void 0;var tw=L();function nw(e){return tw.isFunction(e==null?void 0:e.then)}_o.isPromise=nw});var $c=d(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.isInteropObservable=void 0;var iw=Wn(),ow=L();function aw(e){return ow.isFunction(e[iw.observable])}bo.isInteropObservable=aw});var Wc=d(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.isAsyncIterable=void 0;var uw=L();function sw(e){return Symbol.asyncIterator&&uw.isFunction(e==null?void 0:e[Symbol.asyncIterator])}go.isAsyncIterable=sw});var Bc=d(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.createInvalidObservableTypeError=void 0;function cw(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}Oo.createInvalidObservableTypeError=cw});var Gc=d(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.iterator=an.getSymbolIterator=void 0;function Bv(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}an.getSymbolIterator=Bv;an.iterator=Bv()});var Yc=d(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.isIterable=void 0;var lw=Gc(),dw=L();function fw(e){return dw.isFunction(e==null?void 0:e[lw.iterator])}wo.isIterable=fw});var So=d(me=>{"use strict";var vw=me&&me.__generator||function(e,r){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(s){return function(f){return l([s,f])}}function l(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(o=s[0]&2?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[s[0]&2,o.value]),s[0]){case 0:case 1:o=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,i=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!o||s[1]>o[0]&&s[1]1||u(m,b)})})}function u(m,b){try{l(n[m](b))}catch(g){v(o[0][3],g)}}function l(m){m.value instanceof un?Promise.resolve(m.value.v).then(s,f):v(o[0][2],m)}function s(m){u("next",m)}function f(m){u("throw",m)}function v(m,b){m(b),o.shift(),o.length&&u(o[0][0],o[0][1])}};Object.defineProperty(me,"__esModule",{value:!0});me.isReadableStreamLike=me.readableStreamLikeToAsyncGenerator=void 0;var hw=L();function mw(e){return pw(this,arguments,function(){var t,n,i,o;return vw(this,function(a){switch(a.label){case 0:t=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,un(t.read())];case 3:return n=a.sent(),i=n.value,o=n.done,o?[4,un(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,un(i)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}me.readableStreamLikeToAsyncGenerator=mw;function yw(e){return hw.isFunction(e==null?void 0:e.getReader)}me.isReadableStreamLike=yw});var F=d($=>{"use strict";var _w=$&&$.__awaiter||function(e,r,t,n){function i(o){return o instanceof t?o:new t(function(a){a(o)})}return new(t||(t=Promise))(function(o,a){function u(f){try{s(n.next(f))}catch(v){a(v)}}function l(f){try{s(n.throw(f))}catch(v){a(v)}}function s(f){f.done?o(f.value):i(f.value).then(u,l)}s((n=n.apply(e,r||[])).next())})},bw=$&&$.__generator||function(e,r){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(s){return function(f){return l([s,f])}}function l(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(o=s[0]&2?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[s[0]&2,o.value]),s[0]){case 0:case 1:o=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,i=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!o||s[1]>o[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty($,"__esModule",{value:!0});$.fromReadableStreamLike=$.fromAsyncIterable=$.fromIterable=$.fromPromise=$.fromArrayLike=$.fromInteropObservable=$.innerFrom=void 0;var Ow=yo(),ww=Vc(),sn=z(),Sw=$c(),Pw=Wc(),qw=Bc(),jw=Yc(),Gv=So(),Cw=L(),Iw=jc(),Aw=Wn();function xw(e){if(e instanceof sn.Observable)return e;if(e!=null){if(Sw.isInteropObservable(e))return Yv(e);if(Ow.isArrayLike(e))return Hv(e);if(ww.isPromise(e))return Kv(e);if(Pw.isAsyncIterable(e))return Kc(e);if(jw.isIterable(e))return Jv(e);if(Gv.isReadableStreamLike(e))return Qv(e)}throw qw.createInvalidObservableTypeError(e)}$.innerFrom=xw;function Yv(e){return new sn.Observable(function(r){var t=e[Aw.observable]();if(Cw.isFunction(t.subscribe))return t.subscribe(r);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}$.fromInteropObservable=Yv;function Hv(e){return new sn.Observable(function(r){for(var t=0;t{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.executeSchedule=void 0;function Ew(e,r,t,n,i){n===void 0&&(n=0),i===void 0&&(i=!1);var o=r.schedule(function(){t(),i?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(o),!i)return o}Po.executeSchedule=Ew});var Jn=d(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.observeOn=void 0;var Jc=De(),Mw=j(),kw=C();function Fw(e,r){return r===void 0&&(r=0),Mw.operate(function(t,n){t.subscribe(kw.createOperatorSubscriber(n,function(i){return Jc.executeSchedule(n,e,function(){return n.next(i)},r)},function(){return Jc.executeSchedule(n,e,function(){return n.complete()},r)},function(i){return Jc.executeSchedule(n,e,function(){return n.error(i)},r)}))})}qo.observeOn=Fw});var Qn=d(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.subscribeOn=void 0;var Rw=j();function Zw(e,r){return r===void 0&&(r=0),Rw.operate(function(t,n){n.add(e.schedule(function(){return t.subscribe(n)},r))})}jo.subscribeOn=Zw});var Xv=d(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.scheduleObservable=void 0;var Uw=F(),Lw=Jn(),Nw=Qn();function zw(e,r){return Uw.innerFrom(e).pipe(Nw.subscribeOn(r),Lw.observeOn(r))}Co.scheduleObservable=zw});var ep=d(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.schedulePromise=void 0;var Dw=F(),Vw=Jn(),$w=Qn();function Ww(e,r){return Dw.innerFrom(e).pipe($w.subscribeOn(r),Vw.observeOn(r))}Io.schedulePromise=Ww});var rp=d(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.scheduleArray=void 0;var Bw=z();function Gw(e,r){return new Bw.Observable(function(t){var n=0;return r.schedule(function(){n===e.length?t.complete():(t.next(e[n++]),t.closed||this.schedule())})})}Ao.scheduleArray=Gw});var Qc=d(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.scheduleIterable=void 0;var Yw=z(),Hw=Gc(),Kw=L(),tp=De();function Jw(e,r){return new Yw.Observable(function(t){var n;return tp.executeSchedule(t,r,function(){n=e[Hw.iterator](),tp.executeSchedule(t,r,function(){var i,o,a;try{i=n.next(),o=i.value,a=i.done}catch(u){t.error(u);return}a?t.complete():t.next(o)},0,!0)}),function(){return Kw.isFunction(n==null?void 0:n.return)&&n.return()}})}xo.scheduleIterable=Jw});var Xc=d(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.scheduleAsyncIterable=void 0;var Qw=z(),np=De();function Xw(e,r){if(!e)throw new Error("Iterable cannot be null");return new Qw.Observable(function(t){np.executeSchedule(t,r,function(){var n=e[Symbol.asyncIterator]();np.executeSchedule(t,r,function(){n.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}To.scheduleAsyncIterable=Xw});var ip=d(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.scheduleReadableStreamLike=void 0;var eS=Xc(),rS=So();function tS(e,r){return eS.scheduleAsyncIterable(rS.readableStreamLikeToAsyncGenerator(e),r)}Eo.scheduleReadableStreamLike=tS});var el=d(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.scheduled=void 0;var nS=Xv(),iS=ep(),oS=rp(),aS=Qc(),uS=Xc(),sS=$c(),cS=Vc(),lS=yo(),dS=Yc(),fS=Wc(),vS=Bc(),pS=So(),hS=ip();function mS(e,r){if(e!=null){if(sS.isInteropObservable(e))return nS.scheduleObservable(e,r);if(lS.isArrayLike(e))return oS.scheduleArray(e,r);if(cS.isPromise(e))return iS.schedulePromise(e,r);if(fS.isAsyncIterable(e))return uS.scheduleAsyncIterable(e,r);if(dS.isIterable(e))return aS.scheduleIterable(e,r);if(pS.isReadableStreamLike(e))return hS.scheduleReadableStreamLike(e,r)}throw vS.createInvalidObservableTypeError(e)}Mo.scheduled=mS});var Ve=d(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.from=void 0;var yS=el(),_S=F();function bS(e,r){return r?yS.scheduled(e,r):_S.innerFrom(e)}ko.from=bS});var Ro=d(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.of=void 0;var gS=ce(),OS=Ve();function wS(){for(var e=[],r=0;r{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.throwError=void 0;var SS=z(),PS=L();function qS(e,r){var t=PS.isFunction(e)?e:function(){return e},n=function(i){return i.error(t())};return new SS.Observable(r?function(i){return r.schedule(n,0,i)}:n)}Zo.throwError=qS});var Uo=d($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.observeNotification=$e.Notification=$e.NotificationKind=void 0;var jS=Oe(),CS=Ro(),IS=rl(),AS=L(),xS;(function(e){e.NEXT="N",e.ERROR="E",e.COMPLETE="C"})(xS=$e.NotificationKind||($e.NotificationKind={}));var TS=(function(){function e(r,t,n){this.kind=r,this.value=t,this.error=n,this.hasValue=r==="N"}return e.prototype.observe=function(r){return op(this,r)},e.prototype.do=function(r,t,n){var i=this,o=i.kind,a=i.value,u=i.error;return o==="N"?r==null?void 0:r(a):o==="E"?t==null?void 0:t(u):n==null?void 0:n()},e.prototype.accept=function(r,t,n){var i;return AS.isFunction((i=r)===null||i===void 0?void 0:i.next)?this.observe(r):this.do(r,t,n)},e.prototype.toObservable=function(){var r=this,t=r.kind,n=r.value,i=r.error,o=t==="N"?CS.of(n):t==="E"?IS.throwError(function(){return i}):t==="C"?jS.EMPTY:0;if(!o)throw new TypeError("Unexpected notification kind "+t);return o},e.createNext=function(r){return new e("N",r)},e.createError=function(r){return new e("E",void 0,r)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e})();$e.Notification=TS;function op(e,r){var t,n,i,o=e,a=o.kind,u=o.value,l=o.error;if(typeof a!="string")throw new TypeError('Invalid notification, missing "kind"');a==="N"?(t=r.next)===null||t===void 0||t.call(r,u):a==="E"?(n=r.error)===null||n===void 0||n.call(r,l):(i=r.complete)===null||i===void 0||i.call(r)}$e.observeNotification=op});var up=d(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.isObservable=void 0;var ES=z(),ap=L();function MS(e){return!!e&&(e instanceof ES.Observable||ap.isFunction(e.lift)&&ap.isFunction(e.subscribe))}Lo.isObservable=MS});var nr=d(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.EmptyError=void 0;var kS=Xe();No.EmptyError=kS.createErrorClass(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}})});var sp=d(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.lastValueFrom=void 0;var FS=nr();function RS(e,r){var t=typeof r=="object";return new Promise(function(n,i){var o=!1,a;e.subscribe({next:function(u){a=u,o=!0},error:i,complete:function(){o?n(a):t?n(r.defaultValue):i(new FS.EmptyError)}})})}zo.lastValueFrom=RS});var cp=d(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.firstValueFrom=void 0;var ZS=nr(),US=Nt();function LS(e,r){var t=typeof r=="object";return new Promise(function(n,i){var o=new US.SafeSubscriber({next:function(a){n(a),o.unsubscribe()},error:i,complete:function(){t?n(r.defaultValue):i(new ZS.EmptyError)}});e.subscribe(o)})}Do.firstValueFrom=LS});var tl=d(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.ArgumentOutOfRangeError=void 0;var NS=Xe();Vo.ArgumentOutOfRangeError=NS.createErrorClass(function(e){return function(){e(this),this.name="ArgumentOutOfRangeError",this.message="argument out of range"}})});var nl=d($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.NotFoundError=void 0;var zS=Xe();$o.NotFoundError=zS.createErrorClass(function(e){return function(t){e(this),this.name="NotFoundError",this.message=t}})});var il=d(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.SequenceError=void 0;var DS=Xe();Wo.SequenceError=DS.createErrorClass(function(e){return function(t){e(this),this.name="SequenceError",this.message=t}})});var Go=d(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.isValidDate=void 0;function VS(e){return e instanceof Date&&!isNaN(e)}Bo.isValidDate=VS});var Yo=d(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.timeout=rt.TimeoutError=void 0;var $S=se(),WS=Go(),BS=j(),GS=F(),YS=Xe(),HS=C(),KS=De();rt.TimeoutError=YS.createErrorClass(function(e){return function(t){t===void 0&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function JS(e,r){var t=WS.isValidDate(e)?{first:e}:typeof e=="number"?{each:e}:e,n=t.first,i=t.each,o=t.with,a=o===void 0?QS:o,u=t.scheduler,l=u===void 0?r!=null?r:$S.asyncScheduler:u,s=t.meta,f=s===void 0?null:s;if(n==null&&i==null)throw new TypeError("No timeout provided.");return BS.operate(function(v,m){var b,g,y=null,_=0,O=function(R){g=KS.executeSchedule(m,l,function(){try{b.unsubscribe(),GS.innerFrom(a({meta:f,lastValue:y,seen:_})).subscribe(m)}catch(V){m.error(V)}},R)};b=v.subscribe(HS.createOperatorSubscriber(m,function(R){g==null||g.unsubscribe(),_++,m.next(y=R),i>0&&O(i)},void 0,void 0,function(){g!=null&&g.closed||g==null||g.unsubscribe(),y=null})),!_&&O(n!=null?typeof n=="number"?n:+n-l.now():i)})}rt.timeout=JS;function QS(e){throw new rt.TimeoutError(e)}});var ir=d(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.map=void 0;var XS=j(),eP=C();function rP(e,r){return XS.operate(function(t,n){var i=0;t.subscribe(eP.createOperatorSubscriber(n,function(o){n.next(e.call(r,o,i++))}))})}Ho.map=rP});var ar=d(or=>{"use strict";var tP=or&&or.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},nP=or&&or.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var sP=ur&&ur.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},lp=ur&&ur.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.bindCallback=void 0;var hP=al();function mP(e,r,t){return hP.bindCallbackInternals(!1,e,r,t)}Ko.bindCallback=mP});var fp=d(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.bindNodeCallback=void 0;var yP=al();function _P(e,r,t){return yP.bindCallbackInternals(!0,e,r,t)}Jo.bindNodeCallback=_P});var ul=d(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.argsArgArrayOrObject=void 0;var bP=Array.isArray,gP=Object.getPrototypeOf,OP=Object.prototype,wP=Object.keys;function SP(e){if(e.length===1){var r=e[0];if(bP(r))return{args:r,keys:null};if(PP(r)){var t=wP(r);return{args:t.map(function(n){return r[n]}),keys:t}}}return{args:e,keys:null}}Qo.argsArgArrayOrObject=SP;function PP(e){return e&&typeof e=="object"&&gP(e)===OP}});var sl=d(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.createObject=void 0;function qP(e,r){return e.reduce(function(t,n,i){return t[n]=r[i],t},{})}Xo.createObject=qP});var ea=d(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.combineLatestInit=cn.combineLatest=void 0;var jP=z(),CP=ul(),hp=Ve(),mp=K(),IP=ar(),vp=ce(),AP=sl(),xP=C(),TP=De();function EP(){for(var e=[],r=0;r{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.mergeInternals=void 0;var MP=F(),kP=De(),_p=C();function FP(e,r,t,n,i,o,a,u){var l=[],s=0,f=0,v=!1,m=function(){v&&!l.length&&!s&&r.complete()},b=function(y){return s{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.mergeMap=void 0;var RP=ir(),ZP=F(),UP=j(),LP=ta(),NP=L();function bp(e,r,t){return t===void 0&&(t=1/0),NP.isFunction(r)?bp(function(n,i){return RP.map(function(o,a){return r(n,o,i,a)})(ZP.innerFrom(e(n,i)))},t):(typeof r=="number"&&(t=r),UP.operate(function(n,i){return LP.mergeInternals(n,i,e,t)}))}na.mergeMap=bp});var Xn=d(ia=>{"use strict";Object.defineProperty(ia,"__esModule",{value:!0});ia.mergeAll=void 0;var zP=We(),DP=K();function VP(e){return e===void 0&&(e=1/0),zP.mergeMap(DP.identity,e)}ia.mergeAll=VP});var aa=d(oa=>{"use strict";Object.defineProperty(oa,"__esModule",{value:!0});oa.concatAll=void 0;var $P=Xn();function WP(){return $P.mergeAll(1)}oa.concatAll=WP});var ei=d(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.concat=void 0;var BP=aa(),GP=ce(),YP=Ve();function HP(){for(var e=[],r=0;r{"use strict";Object.defineProperty(sa,"__esModule",{value:!0});sa.defer=void 0;var KP=z(),JP=F();function QP(e){return new KP.Observable(function(r){JP.innerFrom(e()).subscribe(r)})}sa.defer=QP});var gp=d(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.connectable=void 0;var XP=J(),eq=z(),rq=ri(),tq={connector:function(){return new XP.Subject},resetOnDisconnect:!0};function nq(e,r){r===void 0&&(r=tq);var t=null,n=r.connector,i=r.resetOnDisconnect,o=i===void 0?!0:i,a=n(),u=new eq.Observable(function(l){return a.subscribe(l)});return u.connect=function(){return(!t||t.closed)&&(t=rq.defer(function(){return e}).subscribe(a),o&&t.add(function(){return a=n()})),t},u}ca.connectable=nq});var Op=d(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.forkJoin=void 0;var iq=z(),oq=ul(),aq=F(),uq=ce(),sq=C(),cq=ar(),lq=sl();function dq(){for(var e=[],r=0;r{"use strict";var fq=ln&&ln.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o};Object.defineProperty(ln,"__esModule",{value:!0});ln.fromEvent=void 0;var vq=F(),pq=z(),hq=We(),mq=yo(),tt=L(),yq=ar(),_q=["addListener","removeListener"],bq=["addEventListener","removeEventListener"],gq=["on","off"];function cl(e,r,t,n){if(tt.isFunction(t)&&(n=t,t=void 0),n)return cl(e,r,t).pipe(yq.mapOneOrManyArgs(n));var i=fq(Sq(e)?bq.map(function(u){return function(l){return e[u](r,l,t)}}):Oq(e)?_q.map(wp(e,r)):wq(e)?gq.map(wp(e,r)):[],2),o=i[0],a=i[1];if(!o&&mq.isArrayLike(e))return hq.mergeMap(function(u){return cl(u,r,t)})(vq.innerFrom(e));if(!o)throw new TypeError("Invalid event target");return new pq.Observable(function(u){var l=function(){for(var s=[],f=0;f{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.fromEventPattern=void 0;var Pq=z(),qq=L(),jq=ar();function Pp(e,r,t){return t?Pp(e,r).pipe(jq.mapOneOrManyArgs(t)):new Pq.Observable(function(n){var i=function(){for(var a=[],u=0;u{"use strict";var Cq=dn&&dn.__generator||function(e,r){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,a;return a={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function u(s){return function(f){return l([s,f])}}function l(s){if(n)throw new TypeError("Generator is already executing.");for(;t;)try{if(n=1,i&&(o=s[0]&2?i.return:s[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,s[1])).done)return o;switch(i=0,o&&(s=[s[0]&2,o.value]),s[0]){case 0:case 1:o=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,i=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!o||s[1]>o[0]&&s[1]{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.iif=void 0;var Eq=ri();function Mq(e,r,t){return Eq.defer(function(){return e()?r:t})}fa.iif=Mq});var sr=d(va=>{"use strict";Object.defineProperty(va,"__esModule",{value:!0});va.timer=void 0;var kq=z(),Fq=se(),Rq=Kn(),Zq=Go();function Uq(e,r,t){e===void 0&&(e=0),t===void 0&&(t=Fq.async);var n=-1;return r!=null&&(Rq.isScheduler(r)?t=r:n=r),new kq.Observable(function(i){var o=Zq.isValidDate(e)?+e-t.now():e;o<0&&(o=0);var a=0;return t.schedule(function(){i.closed||(i.next(a++),0<=n?this.schedule(void 0,n):i.complete())},o)})}va.timer=Uq});var ll=d(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.interval=void 0;var Lq=se(),Nq=sr();function zq(e,r){return e===void 0&&(e=0),r===void 0&&(r=Lq.asyncScheduler),e<0&&(e=0),Nq.timer(e,e,r)}pa.interval=zq});var xp=d(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.merge=void 0;var Dq=Xn(),Vq=F(),$q=Oe(),Ap=ce(),Wq=Ve();function Bq(){for(var e=[],r=0;r{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.never=nt.NEVER=void 0;var Gq=z(),Yq=H();nt.NEVER=new Gq.Observable(Yq.noop);function Hq(){return nt.NEVER}nt.never=Hq});var fn=d(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.argsOrArgArray=void 0;var Kq=Array.isArray;function Jq(e){return e.length===1&&Kq(e[0])?e[0]:e}ma.argsOrArgArray=Jq});var fl=d(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});ya.onErrorResumeNext=void 0;var Qq=z(),Xq=fn(),ej=C(),Tp=H(),rj=F();function tj(){for(var e=[],r=0;r{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.pairs=void 0;var nj=Ve();function ij(e,r){return nj.from(Object.entries(e),r)}_a.pairs=ij});var Mp=d(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.not=void 0;function oj(e,r){return function(t,n){return!e.call(r,t,n)}}ba.not=oj});var it=d(ga=>{"use strict";Object.defineProperty(ga,"__esModule",{value:!0});ga.filter=void 0;var aj=j(),uj=C();function sj(e,r){return aj.operate(function(t,n){var i=0;t.subscribe(uj.createOperatorSubscriber(n,function(o){return e.call(r,o,i++)&&n.next(o)}))})}ga.filter=sj});var Rp=d(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});Oa.partition=void 0;var cj=Mp(),kp=it(),Fp=F();function lj(e,r,t){return[kp.filter(r,t)(Fp.innerFrom(e)),kp.filter(cj.not(r,t))(Fp.innerFrom(e))]}Oa.partition=lj});var vl=d(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.raceInit=vn.race=void 0;var dj=z(),Zp=F(),fj=fn(),vj=C();function pj(){for(var e=[],r=0;r{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.range=void 0;var hj=z(),mj=Oe();function yj(e,r,t){if(r==null&&(r=e,e=0),r<=0)return mj.EMPTY;var n=r+e;return new hj.Observable(t?function(i){var o=e;return t.schedule(function(){o{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.using=void 0;var _j=z(),bj=F(),gj=Oe();function Oj(e,r){return new _j.Observable(function(t){var n=e(),i=r(n),o=i?bj.innerFrom(i):gj.EMPTY;return o.subscribe(t),function(){n&&n.unsubscribe()}})}Sa.using=Oj});var Pa=d(cr=>{"use strict";var wj=cr&&cr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Sj=cr&&cr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(zp,"__esModule",{value:!0})});var pl=d(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.audit=void 0;var Tj=j(),Ej=F(),Vp=C();function Mj(e){return Tj.operate(function(r,t){var n=!1,i=null,o=null,a=!1,u=function(){if(o==null||o.unsubscribe(),o=null,n){n=!1;var s=i;i=null,t.next(s)}a&&t.complete()},l=function(){o=null,a&&t.complete()};r.subscribe(Vp.createOperatorSubscriber(t,function(s){n=!0,i=s,o||Ej.innerFrom(e(s)).subscribe(o=Vp.createOperatorSubscriber(t,u,l))},function(){a=!0,(!n||!o||o.closed)&&t.complete()}))})}qa.audit=Mj});var $p=d(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.auditTime=void 0;var kj=se(),Fj=pl(),Rj=sr();function Zj(e,r){return r===void 0&&(r=kj.asyncScheduler),Fj.audit(function(){return Rj.timer(e,r)})}ja.auditTime=Zj});var Bp=d(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.buffer=void 0;var Uj=j(),Lj=H(),Wp=C(),Nj=F();function zj(e){return Uj.operate(function(r,t){var n=[];return r.subscribe(Wp.createOperatorSubscriber(t,function(i){return n.push(i)},function(){t.next(n),t.complete()})),Nj.innerFrom(e).subscribe(Wp.createOperatorSubscriber(t,function(){var i=n;n=[],t.next(i)},Lj.noop)),function(){n=null}})}Ca.buffer=zj});var Gp=d(pn=>{"use strict";var hl=pn&&pn.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(pn,"__esModule",{value:!0});pn.bufferCount=void 0;var Dj=j(),Vj=C(),$j=ze();function Wj(e,r){return r===void 0&&(r=null),r=r!=null?r:e,Dj.operate(function(t,n){var i=[],o=0;t.subscribe(Vj.createOperatorSubscriber(n,function(a){var u,l,s,f,v=null;o++%r===0&&i.push([]);try{for(var m=hl(i),b=m.next();!b.done;b=m.next()){var g=b.value;g.push(a),e<=g.length&&(v=v!=null?v:[],v.push(g))}}catch(O){u={error:O}}finally{try{b&&!b.done&&(l=m.return)&&l.call(m)}finally{if(u)throw u.error}}if(v)try{for(var y=hl(v),_=y.next();!_.done;_=y.next()){var g=_.value;$j.arrRemove(i,g),n.next(g)}}catch(O){s={error:O}}finally{try{_&&!_.done&&(f=y.return)&&f.call(y)}finally{if(s)throw s.error}}},function(){var a,u;try{for(var l=hl(i),s=l.next();!s.done;s=l.next()){var f=s.value;n.next(f)}}catch(v){a={error:v}}finally{try{s&&!s.done&&(u=l.return)&&u.call(l)}finally{if(a)throw a.error}}n.complete()},void 0,function(){i=null}))})}pn.bufferCount=Wj});var Hp=d(hn=>{"use strict";var Bj=hn&&hn.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(hn,"__esModule",{value:!0});hn.bufferTime=void 0;var Gj=de(),Yj=j(),Hj=C(),Kj=ze(),Jj=se(),Qj=ce(),Yp=De();function Xj(e){for(var r,t,n=[],i=1;i=0?Yp.executeSchedule(s,o,b,a,!0):v=!0,b();var g=Hj.createOperatorSubscriber(s,function(y){var _,O,R=f.slice();try{for(var V=Bj(R),G=V.next();!G.done;G=V.next()){var ye=G.value,B=ye.buffer;B.push(y),u<=B.length&&m(ye)}}catch(wr){_={error:wr}}finally{try{G&&!G.done&&(O=V.return)&&O.call(V)}finally{if(_)throw _.error}}},function(){for(;f!=null&&f.length;)s.next(f.shift().buffer);g==null||g.unsubscribe(),s.complete(),s.unsubscribe()},void 0,function(){return f=null});l.subscribe(g)})}hn.bufferTime=Xj});var Qp=d(mn=>{"use strict";var eC=mn&&mn.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(mn,"__esModule",{value:!0});mn.bufferToggle=void 0;var rC=de(),tC=j(),Kp=F(),ml=C(),Jp=H(),nC=ze();function iC(e,r){return tC.operate(function(t,n){var i=[];Kp.innerFrom(e).subscribe(ml.createOperatorSubscriber(n,function(o){var a=[];i.push(a);var u=new rC.Subscription,l=function(){nC.arrRemove(i,a),n.next(a),u.unsubscribe()};u.add(Kp.innerFrom(r(o)).subscribe(ml.createOperatorSubscriber(n,l,Jp.noop)))},Jp.noop)),t.subscribe(ml.createOperatorSubscriber(n,function(o){var a,u;try{for(var l=eC(i),s=l.next();!s.done;s=l.next()){var f=s.value;f.push(o)}}catch(v){a={error:v}}finally{try{s&&!s.done&&(u=l.return)&&u.call(l)}finally{if(a)throw a.error}}},function(){for(;i.length>0;)n.next(i.shift());n.complete()}))})}mn.bufferToggle=iC});var eh=d(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.bufferWhen=void 0;var oC=j(),aC=H(),Xp=C(),uC=F();function sC(e){return oC.operate(function(r,t){var n=null,i=null,o=function(){i==null||i.unsubscribe();var a=n;n=[],a&&t.next(a),uC.innerFrom(e()).subscribe(i=Xp.createOperatorSubscriber(t,o,aC.noop))};o(),r.subscribe(Xp.createOperatorSubscriber(t,function(a){return n==null?void 0:n.push(a)},function(){n&&t.next(n),t.complete()},void 0,function(){return n=i=null}))})}Ia.bufferWhen=sC});var th=d(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.catchError=void 0;var cC=F(),lC=C(),dC=j();function rh(e){return dC.operate(function(r,t){var n=null,i=!1,o;n=r.subscribe(lC.createOperatorSubscriber(t,void 0,void 0,function(a){o=cC.innerFrom(e(a,rh(e)(r))),n?(n.unsubscribe(),n=null,o.subscribe(t)):i=!0})),i&&(n.unsubscribe(),n=null,o.subscribe(t))})}Aa.catchError=rh});var yl=d(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.scanInternals=void 0;var fC=C();function vC(e,r,t,n,i){return function(o,a){var u=t,l=r,s=0;o.subscribe(fC.createOperatorSubscriber(a,function(f){var v=s++;l=u?e(l,f,v):(u=!0,f),n&&a.next(l)},i&&(function(){u&&a.next(l),a.complete()})))}}xa.scanInternals=vC});var yn=d(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.reduce=void 0;var pC=yl(),hC=j();function mC(e,r){return hC.operate(pC.scanInternals(e,r,arguments.length>=2,!1,!0))}Ta.reduce=mC});var _l=d(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.toArray=void 0;var yC=yn(),_C=j(),bC=function(e,r){return e.push(r),e};function gC(){return _C.operate(function(e,r){yC.reduce(bC,[])(e).subscribe(r)})}Ea.toArray=gC});var bl=d(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.joinAllInternals=void 0;var OC=K(),wC=ar(),SC=Bn(),PC=We(),qC=_l();function jC(e,r){return SC.pipe(qC.toArray(),PC.mergeMap(function(t){return e(t)}),r?wC.mapOneOrManyArgs(r):OC.identity)}Ma.joinAllInternals=jC});var gl=d(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.combineLatestAll=void 0;var CC=ea(),IC=bl();function AC(e){return IC.joinAllInternals(CC.combineLatest,e)}ka.combineLatestAll=AC});var nh=d(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.combineAll=void 0;var xC=gl();Fa.combineAll=xC.combineLatestAll});var uh=d(lr=>{"use strict";var ih=lr&&lr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},oh=lr&&lr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var ZC=dr&&dr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},UC=dr&&dr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Ra,"__esModule",{value:!0});Ra.concatMap=void 0;var ch=We(),zC=L();function DC(e,r){return zC.isFunction(r)?ch.mergeMap(e,r,1):ch.mergeMap(e,1)}Ra.concatMap=DC});var dh=d(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.concatMapTo=void 0;var lh=Ol(),VC=L();function $C(e,r){return VC.isFunction(r)?lh.concatMap(function(){return e},r):lh.concatMap(function(){return e})}Za.concatMapTo=$C});var fh=d(fr=>{"use strict";var WC=fr&&fr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},BC=fr&&fr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var QC=vr&&vr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},XC=vr&&vr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.fromSubscribable=void 0;var tI=z();function nI(e){return new tI.Observable(function(r){return e.subscribe(r)})}Ua.fromSubscribable=nI});var Na=d(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.connect=void 0;var iI=J(),oI=F(),aI=j(),uI=ph(),sI={connector:function(){return new iI.Subject}};function cI(e,r){r===void 0&&(r=sI);var t=r.connector;return aI.operate(function(n,i){var o=t();oI.innerFrom(e(uI.fromSubscribable(o))).subscribe(i),i.add(n.subscribe(o))})}La.connect=cI});var hh=d(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.count=void 0;var lI=yn();function dI(e){return lI.reduce(function(r,t,n){return!e||e(t,n)?r+1:r},0)}za.count=dI});var yh=d(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.debounce=void 0;var fI=j(),vI=H(),mh=C(),pI=F();function hI(e){return fI.operate(function(r,t){var n=!1,i=null,o=null,a=function(){if(o==null||o.unsubscribe(),o=null,n){n=!1;var u=i;i=null,t.next(u)}};r.subscribe(mh.createOperatorSubscriber(t,function(u){o==null||o.unsubscribe(),n=!0,i=u,o=mh.createOperatorSubscriber(t,a,vI.noop),pI.innerFrom(e(u)).subscribe(o)},function(){a(),t.complete()},void 0,function(){i=o=null}))})}Da.debounce=hI});var _h=d(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.debounceTime=void 0;var mI=se(),yI=j(),_I=C();function bI(e,r){return r===void 0&&(r=mI.asyncScheduler),yI.operate(function(t,n){var i=null,o=null,a=null,u=function(){if(i){i.unsubscribe(),i=null;var s=o;o=null,n.next(s)}};function l(){var s=a+e,f=r.now();if(f{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.defaultIfEmpty=void 0;var gI=j(),OI=C();function wI(e){return gI.operate(function(r,t){var n=!1;r.subscribe(OI.createOperatorSubscriber(t,function(i){n=!0,t.next(i)},function(){n||t.next(e),t.complete()}))})}$a.defaultIfEmpty=wI});var ni=d(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});Wa.take=void 0;var SI=Oe(),PI=j(),qI=C();function jI(e){return e<=0?function(){return SI.EMPTY}:PI.operate(function(r,t){var n=0;r.subscribe(qI.createOperatorSubscriber(t,function(i){++n<=e&&(t.next(i),e<=n&&t.complete())}))})}Wa.take=jI});var wl=d(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.ignoreElements=void 0;var CI=j(),II=C(),AI=H();function xI(){return CI.operate(function(e,r){e.subscribe(II.createOperatorSubscriber(r,AI.noop))})}Ba.ignoreElements=xI});var Sl=d(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.mapTo=void 0;var TI=ir();function EI(e){return TI.map(function(){return e})}Ga.mapTo=EI});var Pl=d(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.delayWhen=void 0;var MI=ei(),bh=ni(),kI=wl(),FI=Sl(),RI=We(),ZI=F();function gh(e,r){return r?function(t){return MI.concat(r.pipe(bh.take(1),kI.ignoreElements()),t.pipe(gh(e)))}:RI.mergeMap(function(t,n){return ZI.innerFrom(e(t,n)).pipe(bh.take(1),FI.mapTo(t))})}Ya.delayWhen=gh});var Oh=d(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.delay=void 0;var UI=se(),LI=Pl(),NI=sr();function zI(e,r){r===void 0&&(r=UI.asyncScheduler);var t=NI.timer(e,r);return LI.delayWhen(function(){return t})}Ha.delay=zI});var wh=d(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.dematerialize=void 0;var DI=Uo(),VI=j(),$I=C();function WI(){return VI.operate(function(e,r){e.subscribe($I.createOperatorSubscriber(r,function(t){return DI.observeNotification(t,r)}))})}Ka.dematerialize=WI});var Ph=d(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.distinct=void 0;var BI=j(),Sh=C(),GI=H(),YI=F();function HI(e,r){return BI.operate(function(t,n){var i=new Set;t.subscribe(Sh.createOperatorSubscriber(n,function(o){var a=e?e(o):o;i.has(a)||(i.add(a),n.next(o))})),r&&YI.innerFrom(r).subscribe(Sh.createOperatorSubscriber(n,function(){return i.clear()},GI.noop))})}Ja.distinct=HI});var ql=d(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.distinctUntilChanged=void 0;var KI=K(),JI=j(),QI=C();function XI(e,r){return r===void 0&&(r=KI.identity),e=e!=null?e:eA,JI.operate(function(t,n){var i,o=!0;t.subscribe(QI.createOperatorSubscriber(n,function(a){var u=r(a);(o||!e(i,u))&&(o=!1,i=u,n.next(a))}))})}Qa.distinctUntilChanged=XI;function eA(e,r){return e===r}});var qh=d(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});Xa.distinctUntilKeyChanged=void 0;var rA=ql();function tA(e,r){return rA.distinctUntilChanged(function(t,n){return r?r(t[e],n[e]):t[e]===n[e]})}Xa.distinctUntilKeyChanged=tA});var ii=d(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});eu.throwIfEmpty=void 0;var nA=nr(),iA=j(),oA=C();function aA(e){return e===void 0&&(e=uA),iA.operate(function(r,t){var n=!1;r.subscribe(oA.createOperatorSubscriber(t,function(i){n=!0,t.next(i)},function(){return n?t.complete():t.error(e())}))})}eu.throwIfEmpty=aA;function uA(){return new nA.EmptyError}});var Ch=d(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});ru.elementAt=void 0;var jh=tl(),sA=it(),cA=ii(),lA=ti(),dA=ni();function fA(e,r){if(e<0)throw new jh.ArgumentOutOfRangeError;var t=arguments.length>=2;return function(n){return n.pipe(sA.filter(function(i,o){return o===e}),dA.take(1),t?lA.defaultIfEmpty(r):cA.throwIfEmpty(function(){return new jh.ArgumentOutOfRangeError}))}}ru.elementAt=fA});var Ih=d(pr=>{"use strict";var vA=pr&&pr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},pA=pr&&pr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.every=void 0;var _A=j(),bA=C();function gA(e,r){return _A.operate(function(t,n){var i=0;t.subscribe(bA.createOperatorSubscriber(n,function(o){e.call(r,o,i++,t)||(n.next(!1),n.complete())},function(){n.next(!0),n.complete()}))})}tu.every=gA});var jl=d(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.exhaustMap=void 0;var OA=ir(),xh=F(),wA=j(),Th=C();function Eh(e,r){return r?function(t){return t.pipe(Eh(function(n,i){return xh.innerFrom(e(n,i)).pipe(OA.map(function(o,a){return r(n,o,i,a)}))}))}:wA.operate(function(t,n){var i=0,o=null,a=!1;t.subscribe(Th.createOperatorSubscriber(n,function(u){o||(o=Th.createOperatorSubscriber(n,void 0,function(){o=null,a&&n.complete()}),xh.innerFrom(e(u,i++)).subscribe(o))},function(){a=!0,!o&&n.complete()}))})}nu.exhaustMap=Eh});var Cl=d(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});iu.exhaustAll=void 0;var SA=jl(),PA=K();function qA(){return SA.exhaustMap(PA.identity)}iu.exhaustAll=qA});var Mh=d(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.exhaust=void 0;var jA=Cl();ou.exhaust=jA.exhaustAll});var kh=d(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.expand=void 0;var CA=j(),IA=ta();function AA(e,r,t){return r===void 0&&(r=1/0),r=(r||0)<1?1/0:r,CA.operate(function(n,i){return IA.mergeInternals(n,i,e,r,void 0,!0,t)})}au.expand=AA});var Fh=d(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});uu.finalize=void 0;var xA=j();function TA(e){return xA.operate(function(r,t){try{r.subscribe(t)}finally{t.add(e)}})}uu.finalize=TA});var Il=d(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.createFind=_n.find=void 0;var EA=j(),MA=C();function kA(e,r){return EA.operate(Rh(e,r,"value"))}_n.find=kA;function Rh(e,r,t){var n=t==="index";return function(i,o){var a=0;i.subscribe(MA.createOperatorSubscriber(o,function(u){var l=a++;e.call(r,u,l,i)&&(o.next(n?l:u),o.complete())},function(){o.next(n?-1:void 0),o.complete()}))}}_n.createFind=Rh});var Zh=d(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});su.findIndex=void 0;var FA=j(),RA=Il();function ZA(e,r){return FA.operate(RA.createFind(e,r,"index"))}su.findIndex=ZA});var Uh=d(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});cu.first=void 0;var UA=nr(),LA=it(),NA=ni(),zA=ti(),DA=ii(),VA=K();function $A(e,r){var t=arguments.length>=2;return function(n){return n.pipe(e?LA.filter(function(i,o){return e(i,o,n)}):VA.identity,NA.take(1),t?zA.defaultIfEmpty(r):DA.throwIfEmpty(function(){return new UA.EmptyError}))}}cu.first=$A});var Nh=d(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});lu.groupBy=void 0;var WA=z(),BA=F(),GA=J(),YA=j(),Lh=C();function HA(e,r,t,n){return YA.operate(function(i,o){var a;!r||typeof r=="function"?a=r:(t=r.duration,a=r.element,n=r.connector);var u=new Map,l=function(g){u.forEach(g),g(o)},s=function(g){return l(function(y){return y.error(g)})},f=0,v=!1,m=new Lh.OperatorSubscriber(o,function(g){try{var y=e(g),_=u.get(y);if(!_){u.set(y,_=n?n():new GA.Subject);var O=b(y,_);if(o.next(O),t){var R=Lh.createOperatorSubscriber(_,function(){_.complete(),R==null||R.unsubscribe()},void 0,void 0,function(){return u.delete(y)});m.add(BA.innerFrom(t(O)).subscribe(R))}}_.next(a?a(g):g)}catch(V){s(V)}},function(){return l(function(g){return g.complete()})},s,function(){return u.clear()},function(){return v=!0,f===0});i.subscribe(m);function b(g,y){var _=new WA.Observable(function(O){f++;var R=y.subscribe(O);return function(){R.unsubscribe(),--f===0&&v&&m.unsubscribe()}});return _.key=g,_}})}lu.groupBy=HA});var zh=d(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});du.isEmpty=void 0;var KA=j(),JA=C();function QA(){return KA.operate(function(e,r){e.subscribe(JA.createOperatorSubscriber(r,function(){r.next(!1),r.complete()},function(){r.next(!0),r.complete()}))})}du.isEmpty=QA});var Al=d(bn=>{"use strict";var XA=bn&&bn.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(bn,"__esModule",{value:!0});bn.takeLast=void 0;var ex=Oe(),rx=j(),tx=C();function nx(e){return e<=0?function(){return ex.EMPTY}:rx.operate(function(r,t){var n=[];r.subscribe(tx.createOperatorSubscriber(t,function(i){n.push(i),e{"use strict";Object.defineProperty(fu,"__esModule",{value:!0});fu.last=void 0;var ix=nr(),ox=it(),ax=Al(),ux=ii(),sx=ti(),cx=K();function lx(e,r){var t=arguments.length>=2;return function(n){return n.pipe(e?ox.filter(function(i,o){return e(i,o,n)}):cx.identity,ax.takeLast(1),t?sx.defaultIfEmpty(r):ux.throwIfEmpty(function(){return new ix.EmptyError}))}}fu.last=lx});var Vh=d(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});vu.materialize=void 0;var xl=Uo(),dx=j(),fx=C();function vx(){return dx.operate(function(e,r){e.subscribe(fx.createOperatorSubscriber(r,function(t){r.next(xl.Notification.createNext(t))},function(){r.next(xl.Notification.createComplete()),r.complete()},function(t){r.next(xl.Notification.createError(t)),r.complete()}))})}vu.materialize=vx});var $h=d(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.max=void 0;var px=yn(),hx=L();function mx(e){return px.reduce(hx.isFunction(e)?function(r,t){return e(r,t)>0?r:t}:function(r,t){return r>t?r:t})}pu.max=mx});var Wh=d(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.flatMap=void 0;var yx=We();hu.flatMap=yx.mergeMap});var Gh=d(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});mu.mergeMapTo=void 0;var Bh=We(),_x=L();function bx(e,r,t){return t===void 0&&(t=1/0),_x.isFunction(r)?Bh.mergeMap(function(){return e},r,t):(typeof r=="number"&&(t=r),Bh.mergeMap(function(){return e},t))}mu.mergeMapTo=bx});var Yh=d(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.mergeScan=void 0;var gx=j(),Ox=ta();function wx(e,r,t){return t===void 0&&(t=1/0),gx.operate(function(n,i){var o=r;return Ox.mergeInternals(n,i,function(a,u){return e(o,a,u)},t,function(a){o=a},!1,void 0,function(){return o=null})})}yu.mergeScan=wx});var Kh=d(hr=>{"use strict";var Sx=hr&&hr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Px=hr&&hr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var Ax=mr&&mr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},xx=mr&&mr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.min=void 0;var Mx=yn(),kx=L();function Fx(e){return Mx.reduce(kx.isFunction(e)?function(r,t){return e(r,t)<0?r:t}:function(r,t){return r{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});bu.multicast=void 0;var Rx=Gn(),Xh=L(),Zx=Na();function Ux(e,r){var t=Xh.isFunction(e)?e:function(){return e};return Xh.isFunction(r)?Zx.connect(r,{connector:t}):function(n){return new Rx.ConnectableObservable(n,t)}}bu.multicast=Ux});var rm=d(Me=>{"use strict";var Lx=Me&&Me.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},Nx=Me&&Me.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});Ou.pairwise=void 0;var Vx=j(),$x=C();function Wx(){return Vx.operate(function(e,r){var t,n=!1;e.subscribe($x.createOperatorSubscriber(r,function(i){var o=t;t=i,n&&r.next([o,i]),n=!0}))})}Ou.pairwise=Wx});var nm=d(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});wu.pluck=void 0;var Bx=ir();function Gx(){for(var e=[],r=0;r{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});Su.publish=void 0;var Yx=J(),Hx=gu(),Kx=Na();function Jx(e){return e?function(r){return Kx.connect(e)(r)}:function(r){return Hx.multicast(new Yx.Subject)(r)}}Su.publish=Jx});var om=d(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.publishBehavior=void 0;var Qx=Lc(),Xx=Gn();function eT(e){return function(r){var t=new Qx.BehaviorSubject(e);return new Xx.ConnectableObservable(r,function(){return t})}}Pu.publishBehavior=eT});var am=d(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.publishLast=void 0;var rT=fo(),tT=Gn();function nT(){return function(e){var r=new rT.AsyncSubject;return new tT.ConnectableObservable(e,function(){return r})}}qu.publishLast=nT});var sm=d(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});ju.publishReplay=void 0;var iT=lo(),oT=gu(),um=L();function aT(e,r,t,n){t&&!um.isFunction(t)&&(n=t);var i=um.isFunction(t)?t:void 0;return function(o){return oT.multicast(new iT.ReplaySubject(e,r,n),i)(o)}}ju.publishReplay=aT});var cm=d(yr=>{"use strict";var uT=yr&&yr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},sT=yr&&yr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});Cu.repeat=void 0;var vT=Oe(),pT=j(),lm=C(),hT=F(),mT=sr();function yT(e){var r,t=1/0,n;return e!=null&&(typeof e=="object"?(r=e.count,t=r===void 0?1/0:r,n=e.delay):t=e),t<=0?function(){return vT.EMPTY}:pT.operate(function(i,o){var a=0,u,l=function(){if(u==null||u.unsubscribe(),u=null,n!=null){var f=typeof n=="number"?mT.timer(n):hT.innerFrom(n(a)),v=lm.createOperatorSubscriber(o,function(){v.unsubscribe(),s()});f.subscribe(v)}else s()},s=function(){var f=!1;u=i.subscribe(lm.createOperatorSubscriber(o,void 0,function(){++a{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.repeatWhen=void 0;var _T=F(),bT=J(),gT=j(),fm=C();function OT(e){return gT.operate(function(r,t){var n,i=!1,o,a=!1,u=!1,l=function(){return u&&a&&(t.complete(),!0)},s=function(){return o||(o=new bT.Subject,_T.innerFrom(e(o)).subscribe(fm.createOperatorSubscriber(t,function(){n?f():i=!0},function(){a=!0,l()}))),o},f=function(){u=!1,n=r.subscribe(fm.createOperatorSubscriber(t,void 0,function(){u=!0,!l()&&s().next()})),i&&(n.unsubscribe(),n=null,i=!1,f())};f()})}Iu.repeatWhen=OT});var hm=d(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.retry=void 0;var wT=j(),pm=C(),ST=K(),PT=sr(),qT=F();function jT(e){e===void 0&&(e=1/0);var r;e&&typeof e=="object"?r=e:r={count:e};var t=r.count,n=t===void 0?1/0:t,i=r.delay,o=r.resetOnSuccess,a=o===void 0?!1:o;return n<=0?ST.identity:wT.operate(function(u,l){var s=0,f,v=function(){var m=!1;f=u.subscribe(pm.createOperatorSubscriber(l,function(b){a&&(s=0),l.next(b)},void 0,function(b){if(s++{"use strict";Object.defineProperty(xu,"__esModule",{value:!0});xu.retryWhen=void 0;var CT=F(),IT=J(),AT=j(),mm=C();function xT(e){return AT.operate(function(r,t){var n,i=!1,o,a=function(){n=r.subscribe(mm.createOperatorSubscriber(t,void 0,void 0,function(u){o||(o=new IT.Subject,CT.innerFrom(e(o)).subscribe(mm.createOperatorSubscriber(t,function(){return n?a():i=!0}))),o&&o.next(u)})),i&&(n.unsubscribe(),n=null,i=!1,a())};a()})}xu.retryWhen=xT});var Tl=d(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});Tu.sample=void 0;var TT=F(),ET=j(),MT=H(),_m=C();function kT(e){return ET.operate(function(r,t){var n=!1,i=null;r.subscribe(_m.createOperatorSubscriber(t,function(o){n=!0,i=o})),TT.innerFrom(e).subscribe(_m.createOperatorSubscriber(t,function(){if(n){n=!1;var o=i;i=null,t.next(o)}},MT.noop))})}Tu.sample=kT});var bm=d(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.sampleTime=void 0;var FT=se(),RT=Tl(),ZT=ll();function UT(e,r){return r===void 0&&(r=FT.asyncScheduler),RT.sample(ZT.interval(e,r))}Eu.sampleTime=UT});var gm=d(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.scan=void 0;var LT=j(),NT=yl();function zT(e,r){return LT.operate(NT.scanInternals(e,r,arguments.length>=2,!0))}Mu.scan=zT});var wm=d(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.sequenceEqual=void 0;var DT=j(),VT=C(),$T=F();function WT(e,r){return r===void 0&&(r=function(t,n){return t===n}),DT.operate(function(t,n){var i=Om(),o=Om(),a=function(l){n.next(l),n.complete()},u=function(l,s){var f=VT.createOperatorSubscriber(n,function(v){var m=s.buffer,b=s.complete;m.length===0?b?a(!1):l.buffer.push(v):!r(v,m.shift())&&a(!1)},function(){l.complete=!0;var v=s.complete,m=s.buffer;v&&a(m.length===0),f==null||f.unsubscribe()});return f};t.subscribe(u(i,o)),$T.innerFrom(e).subscribe(u(o,i))})}ku.sequenceEqual=WT;function Om(){return{buffer:[],complete:!1}}});var Ml=d(_r=>{"use strict";var BT=_r&&_r.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},GT=_r&&_r.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t0&&(f=new Pm.SafeSubscriber({next:function(B){return ye.next(B)},error:function(B){y=!0,_(),v=El(O,i,B),ye.error(B)},complete:function(){g=!0,_(),v=El(O,a),ye.complete()}}),Sm.innerFrom(V).subscribe(f))})(s)}}_r.share=KT;function El(e,r){for(var t=[],n=2;n{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.shareReplay=void 0;var JT=lo(),QT=Ml();function XT(e,r,t){var n,i,o,a,u=!1;return e&&typeof e=="object"?(n=e.bufferSize,a=n===void 0?1/0:n,i=e.windowTime,r=i===void 0?1/0:i,o=e.refCount,u=o===void 0?!1:o,t=e.scheduler):a=e!=null?e:1/0,QT.share({connector:function(){return new JT.ReplaySubject(a,r,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:u})}Fu.shareReplay=XT});var jm=d(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.single=void 0;var eE=nr(),rE=il(),tE=nl(),nE=j(),iE=C();function oE(e){return nE.operate(function(r,t){var n=!1,i,o=!1,a=0;r.subscribe(iE.createOperatorSubscriber(t,function(u){o=!0,(!e||e(u,a++,r))&&(n&&t.error(new rE.SequenceError("Too many matching values")),n=!0,i=u)},function(){n?(t.next(i),t.complete()):t.error(o?new tE.NotFoundError("No matching values"):new eE.EmptyError)}))})}Ru.single=oE});var Cm=d(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});Zu.skip=void 0;var aE=it();function uE(e){return aE.filter(function(r,t){return e<=t})}Zu.skip=uE});var Im=d(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});Uu.skipLast=void 0;var sE=K(),cE=j(),lE=C();function dE(e){return e<=0?sE.identity:cE.operate(function(r,t){var n=new Array(e),i=0;return r.subscribe(lE.createOperatorSubscriber(t,function(o){var a=i++;if(a{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});Lu.skipUntil=void 0;var fE=j(),Am=C(),vE=F(),pE=H();function hE(e){return fE.operate(function(r,t){var n=!1,i=Am.createOperatorSubscriber(t,function(){i==null||i.unsubscribe(),n=!0},pE.noop);vE.innerFrom(e).subscribe(i),r.subscribe(Am.createOperatorSubscriber(t,function(o){return n&&t.next(o)}))})}Lu.skipUntil=hE});var Tm=d(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});Nu.skipWhile=void 0;var mE=j(),yE=C();function _E(e){return mE.operate(function(r,t){var n=!1,i=0;r.subscribe(yE.createOperatorSubscriber(t,function(o){return(n||(n=!e(o,i++)))&&t.next(o)}))})}Nu.skipWhile=_E});var Mm=d(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.startWith=void 0;var Em=ei(),bE=ce(),gE=j();function OE(){for(var e=[],r=0;r{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.switchMap=void 0;var wE=F(),SE=j(),km=C();function PE(e,r){return SE.operate(function(t,n){var i=null,o=0,a=!1,u=function(){return a&&!i&&n.complete()};t.subscribe(km.createOperatorSubscriber(n,function(l){i==null||i.unsubscribe();var s=0,f=o++;wE.innerFrom(e(l,f)).subscribe(i=km.createOperatorSubscriber(n,function(v){return n.next(r?r(l,v,f,s++):v)},function(){i=null,u()}))},function(){a=!0,u()}))})}Du.switchMap=PE});var Fm=d(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.switchAll=void 0;var qE=oi(),jE=K();function CE(){return qE.switchMap(jE.identity)}Vu.switchAll=CE});var Zm=d($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});$u.switchMapTo=void 0;var Rm=oi(),IE=L();function AE(e,r){return IE.isFunction(r)?Rm.switchMap(function(){return e},r):Rm.switchMap(function(){return e})}$u.switchMapTo=AE});var Um=d(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});Wu.switchScan=void 0;var xE=oi(),TE=j();function EE(e,r){return TE.operate(function(t,n){var i=r;return xE.switchMap(function(o,a){return e(i,o,a)},function(o,a){return i=a,a})(t).subscribe(n),function(){i=null}})}Wu.switchScan=EE});var Lm=d(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.takeUntil=void 0;var ME=j(),kE=C(),FE=F(),RE=H();function ZE(e){return ME.operate(function(r,t){FE.innerFrom(e).subscribe(kE.createOperatorSubscriber(t,function(){return t.complete()},RE.noop)),!t.closed&&r.subscribe(t)})}Bu.takeUntil=ZE});var Nm=d(Gu=>{"use strict";Object.defineProperty(Gu,"__esModule",{value:!0});Gu.takeWhile=void 0;var UE=j(),LE=C();function NE(e,r){return r===void 0&&(r=!1),UE.operate(function(t,n){var i=0;t.subscribe(LE.createOperatorSubscriber(n,function(o){var a=e(o,i++);(a||r)&&n.next(o),!a&&n.complete()}))})}Gu.takeWhile=NE});var zm=d(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.tap=void 0;var zE=L(),DE=j(),VE=C(),$E=K();function WE(e,r,t){var n=zE.isFunction(e)||r||t?{next:e,error:r,complete:t}:e;return n?DE.operate(function(i,o){var a;(a=n.subscribe)===null||a===void 0||a.call(n);var u=!0;i.subscribe(VE.createOperatorSubscriber(o,function(l){var s;(s=n.next)===null||s===void 0||s.call(n,l),o.next(l)},function(){var l;u=!1,(l=n.complete)===null||l===void 0||l.call(n),o.complete()},function(l){var s;u=!1,(s=n.error)===null||s===void 0||s.call(n,l),o.error(l)},function(){var l,s;u&&((l=n.unsubscribe)===null||l===void 0||l.call(n)),(s=n.finalize)===null||s===void 0||s.call(n)}))}):$E.identity}Yu.tap=WE});var kl=d(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});Hu.throttle=void 0;var BE=j(),Dm=C(),GE=F();function YE(e,r){return BE.operate(function(t,n){var i=r!=null?r:{},o=i.leading,a=o===void 0?!0:o,u=i.trailing,l=u===void 0?!1:u,s=!1,f=null,v=null,m=!1,b=function(){v==null||v.unsubscribe(),v=null,l&&(_(),m&&n.complete())},g=function(){v=null,m&&n.complete()},y=function(O){return v=GE.innerFrom(e(O)).subscribe(Dm.createOperatorSubscriber(n,b,g))},_=function(){if(s){s=!1;var O=f;f=null,n.next(O),!m&&y(O)}};t.subscribe(Dm.createOperatorSubscriber(n,function(O){s=!0,f=O,!(v&&!v.closed)&&(a?_():y(O))},function(){m=!0,!(l&&s&&v&&!v.closed)&&n.complete()}))})}Hu.throttle=YE});var Vm=d(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});Ku.throttleTime=void 0;var HE=se(),KE=kl(),JE=sr();function QE(e,r,t){r===void 0&&(r=HE.asyncScheduler);var n=JE.timer(e,r);return KE.throttle(function(){return n},t)}Ku.throttleTime=QE});var Wm=d(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.TimeInterval=gn.timeInterval=void 0;var XE=se(),eM=j(),rM=C();function tM(e){return e===void 0&&(e=XE.asyncScheduler),eM.operate(function(r,t){var n=e.now();r.subscribe(rM.createOperatorSubscriber(t,function(i){var o=e.now(),a=o-n;n=o,t.next(new $m(i,a))}))})}gn.timeInterval=tM;var $m=(function(){function e(r,t){this.value=r,this.interval=t}return e})();gn.TimeInterval=$m});var Bm=d(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});Ju.timeoutWith=void 0;var nM=se(),iM=Go(),oM=Yo();function aM(e,r,t){var n,i,o;if(t=t!=null?t:nM.async,iM.isValidDate(e)?n=e:typeof e=="number"&&(i=e),r)o=function(){return r};else throw new TypeError("No observable provided to switch to");if(n==null&&i==null)throw new TypeError("No timeout provided.");return oM.timeout({first:n,each:i,scheduler:t,with:o})}Ju.timeoutWith=aM});var Gm=d(Qu=>{"use strict";Object.defineProperty(Qu,"__esModule",{value:!0});Qu.timestamp=void 0;var uM=co(),sM=ir();function cM(e){return e===void 0&&(e=uM.dateTimestampProvider),sM.map(function(r){return{value:r,timestamp:e.now()}})}Qu.timestamp=cM});var Km=d(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});Xu.window=void 0;var Ym=J(),lM=j(),Hm=C(),dM=H(),fM=F();function vM(e){return lM.operate(function(r,t){var n=new Ym.Subject;t.next(n.asObservable());var i=function(o){n.error(o),t.error(o)};return r.subscribe(Hm.createOperatorSubscriber(t,function(o){return n==null?void 0:n.next(o)},function(){n.complete(),t.complete()},i)),fM.innerFrom(e).subscribe(Hm.createOperatorSubscriber(t,function(){n.complete(),t.next(n=new Ym.Subject)},dM.noop,i)),function(){n==null||n.unsubscribe(),n=null}})}Xu.window=vM});var Qm=d(On=>{"use strict";var pM=On&&On.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(On,"__esModule",{value:!0});On.windowCount=void 0;var Jm=J(),hM=j(),mM=C();function yM(e,r){r===void 0&&(r=0);var t=r>0?r:e;return hM.operate(function(n,i){var o=[new Jm.Subject],a=[],u=0;i.next(o[0].asObservable()),n.subscribe(mM.createOperatorSubscriber(i,function(l){var s,f;try{for(var v=pM(o),m=v.next();!m.done;m=v.next()){var b=m.value;b.next(l)}}catch(_){s={error:_}}finally{try{m&&!m.done&&(f=v.return)&&f.call(v)}finally{if(s)throw s.error}}var g=u-e+1;if(g>=0&&g%t===0&&o.shift().complete(),++u%t===0){var y=new Jm.Subject;o.push(y),i.next(y.asObservable())}},function(){for(;o.length>0;)o.shift().complete();i.complete()},function(l){for(;o.length>0;)o.shift().error(l);i.error(l)},function(){a=null,o=null}))})}On.windowCount=yM});var ey=d(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.windowTime=void 0;var _M=J(),bM=se(),gM=de(),OM=j(),wM=C(),SM=ze(),PM=ce(),Xm=De();function qM(e){for(var r,t,n=[],i=1;i=0?Xm.executeSchedule(s,o,b,a,!0):v=!0,b();var g=function(_){return f.slice().forEach(_)},y=function(_){g(function(O){var R=O.window;return _(R)}),_(s),s.unsubscribe()};return l.subscribe(wM.createOperatorSubscriber(s,function(_){g(function(O){O.window.next(_),u<=++O.seen&&m(O)})},function(){return y(function(_){return _.complete()})},function(_){return y(function(O){return O.error(_)})})),function(){f=null}})}es.windowTime=qM});var ny=d(wn=>{"use strict";var jM=wn&&wn.__values||function(e){var r=typeof Symbol=="function"&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(wn,"__esModule",{value:!0});wn.windowToggle=void 0;var CM=J(),IM=de(),AM=j(),ry=F(),Fl=C(),ty=H(),xM=ze();function TM(e,r){return AM.operate(function(t,n){var i=[],o=function(a){for(;0{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.windowWhen=void 0;var EM=J(),MM=j(),iy=C(),kM=F();function FM(e){return MM.operate(function(r,t){var n,i,o=function(u){n.error(u),t.error(u)},a=function(){i==null||i.unsubscribe(),n==null||n.complete(),n=new EM.Subject,t.next(n.asObservable());var u;try{u=kM.innerFrom(e())}catch(l){o(l);return}u.subscribe(i=iy.createOperatorSubscriber(t,a,a,o))};a(),r.subscribe(iy.createOperatorSubscriber(t,function(u){return n.next(u)},function(){n.complete(),t.complete()},o,function(){i==null||i.unsubscribe(),n=null}))})}rs.windowWhen=FM});var cy=d(br=>{"use strict";var ay=br&&br.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},uy=br&&br.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.zipAll=void 0;var DM=Pa(),VM=bl();function $M(e){return VM.joinAllInternals(DM.zip,e)}ts.zipAll=$M});var dy=d(gr=>{"use strict";var WM=gr&&gr.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},BM=gr&&gr.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var KM=Or&&Or.__read||function(e,r){var t=typeof Symbol=="function"&&e[Symbol.iterator];if(!t)return e;var n=t.call(e),i,o=[],a;try{for(;(r===void 0||r-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){a={error:u}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(a)throw a.error}}return o},JM=Or&&Or.__spreadArray||function(e,r){for(var t=0,n=r.length,i=e.length;t{"use strict";var ek=c&&c.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t),Object.defineProperty(e,n,{enumerable:!0,get:function(){return r[t]}})}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),rk=c&&c.__exportStar||function(e,r){for(var t in e)t!=="default"&&!Object.prototype.hasOwnProperty.call(r,t)&&ek(r,e,t)};Object.defineProperty(c,"__esModule",{value:!0});c.interval=c.iif=c.generate=c.fromEventPattern=c.fromEvent=c.from=c.forkJoin=c.empty=c.defer=c.connectable=c.concat=c.combineLatest=c.bindNodeCallback=c.bindCallback=c.UnsubscriptionError=c.TimeoutError=c.SequenceError=c.ObjectUnsubscribedError=c.NotFoundError=c.EmptyError=c.ArgumentOutOfRangeError=c.firstValueFrom=c.lastValueFrom=c.isObservable=c.identity=c.noop=c.pipe=c.NotificationKind=c.Notification=c.Subscriber=c.Subscription=c.Scheduler=c.VirtualAction=c.VirtualTimeScheduler=c.animationFrameScheduler=c.animationFrame=c.queueScheduler=c.queue=c.asyncScheduler=c.async=c.asapScheduler=c.asap=c.AsyncSubject=c.ReplaySubject=c.BehaviorSubject=c.Subject=c.animationFrames=c.observable=c.ConnectableObservable=c.Observable=void 0;c.filter=c.expand=c.exhaustMap=c.exhaustAll=c.exhaust=c.every=c.endWith=c.elementAt=c.distinctUntilKeyChanged=c.distinctUntilChanged=c.distinct=c.dematerialize=c.delayWhen=c.delay=c.defaultIfEmpty=c.debounceTime=c.debounce=c.count=c.connect=c.concatWith=c.concatMapTo=c.concatMap=c.concatAll=c.combineLatestWith=c.combineLatestAll=c.combineAll=c.catchError=c.bufferWhen=c.bufferToggle=c.bufferTime=c.bufferCount=c.buffer=c.auditTime=c.audit=c.config=c.NEVER=c.EMPTY=c.scheduled=c.zip=c.using=c.timer=c.throwError=c.range=c.race=c.partition=c.pairs=c.onErrorResumeNext=c.of=c.never=c.merge=void 0;c.switchMap=c.switchAll=c.subscribeOn=c.startWith=c.skipWhile=c.skipUntil=c.skipLast=c.skip=c.single=c.shareReplay=c.share=c.sequenceEqual=c.scan=c.sampleTime=c.sample=c.refCount=c.retryWhen=c.retry=c.repeatWhen=c.repeat=c.reduce=c.raceWith=c.publishReplay=c.publishLast=c.publishBehavior=c.publish=c.pluck=c.pairwise=c.onErrorResumeNextWith=c.observeOn=c.multicast=c.min=c.mergeWith=c.mergeScan=c.mergeMapTo=c.mergeMap=c.flatMap=c.mergeAll=c.max=c.materialize=c.mapTo=c.map=c.last=c.isEmpty=c.ignoreElements=c.groupBy=c.first=c.findIndex=c.find=c.finalize=void 0;c.zipWith=c.zipAll=c.withLatestFrom=c.windowWhen=c.windowToggle=c.windowTime=c.windowCount=c.window=c.toArray=c.timestamp=c.timeoutWith=c.timeout=c.timeInterval=c.throwIfEmpty=c.throttleTime=c.throttle=c.tap=c.takeWhile=c.takeUntil=c.takeLast=c.take=c.switchScan=c.switchMapTo=void 0;var tk=z();Object.defineProperty(c,"Observable",{enumerable:!0,get:function(){return tk.Observable}});var nk=Gn();Object.defineProperty(c,"ConnectableObservable",{enumerable:!0,get:function(){return nk.ConnectableObservable}});var ik=Wn();Object.defineProperty(c,"observable",{enumerable:!0,get:function(){return ik.observable}});var ok=yv();Object.defineProperty(c,"animationFrames",{enumerable:!0,get:function(){return ok.animationFrames}});var ak=J();Object.defineProperty(c,"Subject",{enumerable:!0,get:function(){return ak.Subject}});var uk=Lc();Object.defineProperty(c,"BehaviorSubject",{enumerable:!0,get:function(){return uk.BehaviorSubject}});var sk=lo();Object.defineProperty(c,"ReplaySubject",{enumerable:!0,get:function(){return sk.ReplaySubject}});var ck=fo();Object.defineProperty(c,"AsyncSubject",{enumerable:!0,get:function(){return ck.AsyncSubject}});var vy=kv();Object.defineProperty(c,"asap",{enumerable:!0,get:function(){return vy.asap}});Object.defineProperty(c,"asapScheduler",{enumerable:!0,get:function(){return vy.asapScheduler}});var py=se();Object.defineProperty(c,"async",{enumerable:!0,get:function(){return py.async}});Object.defineProperty(c,"asyncScheduler",{enumerable:!0,get:function(){return py.asyncScheduler}});var hy=Zv();Object.defineProperty(c,"queue",{enumerable:!0,get:function(){return hy.queue}});Object.defineProperty(c,"queueScheduler",{enumerable:!0,get:function(){return hy.queueScheduler}});var my=zv();Object.defineProperty(c,"animationFrame",{enumerable:!0,get:function(){return my.animationFrame}});Object.defineProperty(c,"animationFrameScheduler",{enumerable:!0,get:function(){return my.animationFrameScheduler}});var yy=$v();Object.defineProperty(c,"VirtualTimeScheduler",{enumerable:!0,get:function(){return yy.VirtualTimeScheduler}});Object.defineProperty(c,"VirtualAction",{enumerable:!0,get:function(){return yy.VirtualAction}});var lk=zc();Object.defineProperty(c,"Scheduler",{enumerable:!0,get:function(){return lk.Scheduler}});var dk=de();Object.defineProperty(c,"Subscription",{enumerable:!0,get:function(){return dk.Subscription}});var fk=Nt();Object.defineProperty(c,"Subscriber",{enumerable:!0,get:function(){return fk.Subscriber}});var _y=Uo();Object.defineProperty(c,"Notification",{enumerable:!0,get:function(){return _y.Notification}});Object.defineProperty(c,"NotificationKind",{enumerable:!0,get:function(){return _y.NotificationKind}});var vk=Bn();Object.defineProperty(c,"pipe",{enumerable:!0,get:function(){return vk.pipe}});var pk=H();Object.defineProperty(c,"noop",{enumerable:!0,get:function(){return pk.noop}});var hk=K();Object.defineProperty(c,"identity",{enumerable:!0,get:function(){return hk.identity}});var mk=up();Object.defineProperty(c,"isObservable",{enumerable:!0,get:function(){return mk.isObservable}});var yk=sp();Object.defineProperty(c,"lastValueFrom",{enumerable:!0,get:function(){return yk.lastValueFrom}});var _k=cp();Object.defineProperty(c,"firstValueFrom",{enumerable:!0,get:function(){return _k.firstValueFrom}});var bk=tl();Object.defineProperty(c,"ArgumentOutOfRangeError",{enumerable:!0,get:function(){return bk.ArgumentOutOfRangeError}});var gk=nr();Object.defineProperty(c,"EmptyError",{enumerable:!0,get:function(){return gk.EmptyError}});var Ok=nl();Object.defineProperty(c,"NotFoundError",{enumerable:!0,get:function(){return Ok.NotFoundError}});var wk=Fc();Object.defineProperty(c,"ObjectUnsubscribedError",{enumerable:!0,get:function(){return wk.ObjectUnsubscribedError}});var Sk=il();Object.defineProperty(c,"SequenceError",{enumerable:!0,get:function(){return Sk.SequenceError}});var Pk=Yo();Object.defineProperty(c,"TimeoutError",{enumerable:!0,get:function(){return Pk.TimeoutError}});var qk=wc();Object.defineProperty(c,"UnsubscriptionError",{enumerable:!0,get:function(){return qk.UnsubscriptionError}});var jk=dp();Object.defineProperty(c,"bindCallback",{enumerable:!0,get:function(){return jk.bindCallback}});var Ck=fp();Object.defineProperty(c,"bindNodeCallback",{enumerable:!0,get:function(){return Ck.bindNodeCallback}});var Ik=ea();Object.defineProperty(c,"combineLatest",{enumerable:!0,get:function(){return Ik.combineLatest}});var Ak=ei();Object.defineProperty(c,"concat",{enumerable:!0,get:function(){return Ak.concat}});var xk=gp();Object.defineProperty(c,"connectable",{enumerable:!0,get:function(){return xk.connectable}});var Tk=ri();Object.defineProperty(c,"defer",{enumerable:!0,get:function(){return Tk.defer}});var Ek=Oe();Object.defineProperty(c,"empty",{enumerable:!0,get:function(){return Ek.empty}});var Mk=Op();Object.defineProperty(c,"forkJoin",{enumerable:!0,get:function(){return Mk.forkJoin}});var kk=Ve();Object.defineProperty(c,"from",{enumerable:!0,get:function(){return kk.from}});var Fk=Sp();Object.defineProperty(c,"fromEvent",{enumerable:!0,get:function(){return Fk.fromEvent}});var Rk=qp();Object.defineProperty(c,"fromEventPattern",{enumerable:!0,get:function(){return Rk.fromEventPattern}});var Zk=Cp();Object.defineProperty(c,"generate",{enumerable:!0,get:function(){return Zk.generate}});var Uk=Ip();Object.defineProperty(c,"iif",{enumerable:!0,get:function(){return Uk.iif}});var Lk=ll();Object.defineProperty(c,"interval",{enumerable:!0,get:function(){return Lk.interval}});var Nk=xp();Object.defineProperty(c,"merge",{enumerable:!0,get:function(){return Nk.merge}});var zk=dl();Object.defineProperty(c,"never",{enumerable:!0,get:function(){return zk.never}});var Dk=Ro();Object.defineProperty(c,"of",{enumerable:!0,get:function(){return Dk.of}});var Vk=fl();Object.defineProperty(c,"onErrorResumeNext",{enumerable:!0,get:function(){return Vk.onErrorResumeNext}});var $k=Ep();Object.defineProperty(c,"pairs",{enumerable:!0,get:function(){return $k.pairs}});var Wk=Rp();Object.defineProperty(c,"partition",{enumerable:!0,get:function(){return Wk.partition}});var Bk=vl();Object.defineProperty(c,"race",{enumerable:!0,get:function(){return Bk.race}});var Gk=Lp();Object.defineProperty(c,"range",{enumerable:!0,get:function(){return Gk.range}});var Yk=rl();Object.defineProperty(c,"throwError",{enumerable:!0,get:function(){return Yk.throwError}});var Hk=sr();Object.defineProperty(c,"timer",{enumerable:!0,get:function(){return Hk.timer}});var Kk=Np();Object.defineProperty(c,"using",{enumerable:!0,get:function(){return Kk.using}});var Jk=Pa();Object.defineProperty(c,"zip",{enumerable:!0,get:function(){return Jk.zip}});var Qk=el();Object.defineProperty(c,"scheduled",{enumerable:!0,get:function(){return Qk.scheduled}});var Xk=Oe();Object.defineProperty(c,"EMPTY",{enumerable:!0,get:function(){return Xk.EMPTY}});var eF=dl();Object.defineProperty(c,"NEVER",{enumerable:!0,get:function(){return eF.NEVER}});rk(Dp(),c);var rF=Ut();Object.defineProperty(c,"config",{enumerable:!0,get:function(){return rF.config}});var tF=pl();Object.defineProperty(c,"audit",{enumerable:!0,get:function(){return tF.audit}});var nF=$p();Object.defineProperty(c,"auditTime",{enumerable:!0,get:function(){return nF.auditTime}});var iF=Bp();Object.defineProperty(c,"buffer",{enumerable:!0,get:function(){return iF.buffer}});var oF=Gp();Object.defineProperty(c,"bufferCount",{enumerable:!0,get:function(){return oF.bufferCount}});var aF=Hp();Object.defineProperty(c,"bufferTime",{enumerable:!0,get:function(){return aF.bufferTime}});var uF=Qp();Object.defineProperty(c,"bufferToggle",{enumerable:!0,get:function(){return uF.bufferToggle}});var sF=eh();Object.defineProperty(c,"bufferWhen",{enumerable:!0,get:function(){return sF.bufferWhen}});var cF=th();Object.defineProperty(c,"catchError",{enumerable:!0,get:function(){return cF.catchError}});var lF=nh();Object.defineProperty(c,"combineAll",{enumerable:!0,get:function(){return lF.combineAll}});var dF=gl();Object.defineProperty(c,"combineLatestAll",{enumerable:!0,get:function(){return dF.combineLatestAll}});var fF=sh();Object.defineProperty(c,"combineLatestWith",{enumerable:!0,get:function(){return fF.combineLatestWith}});var vF=aa();Object.defineProperty(c,"concatAll",{enumerable:!0,get:function(){return vF.concatAll}});var pF=Ol();Object.defineProperty(c,"concatMap",{enumerable:!0,get:function(){return pF.concatMap}});var hF=dh();Object.defineProperty(c,"concatMapTo",{enumerable:!0,get:function(){return hF.concatMapTo}});var mF=vh();Object.defineProperty(c,"concatWith",{enumerable:!0,get:function(){return mF.concatWith}});var yF=Na();Object.defineProperty(c,"connect",{enumerable:!0,get:function(){return yF.connect}});var _F=hh();Object.defineProperty(c,"count",{enumerable:!0,get:function(){return _F.count}});var bF=yh();Object.defineProperty(c,"debounce",{enumerable:!0,get:function(){return bF.debounce}});var gF=_h();Object.defineProperty(c,"debounceTime",{enumerable:!0,get:function(){return gF.debounceTime}});var OF=ti();Object.defineProperty(c,"defaultIfEmpty",{enumerable:!0,get:function(){return OF.defaultIfEmpty}});var wF=Oh();Object.defineProperty(c,"delay",{enumerable:!0,get:function(){return wF.delay}});var SF=Pl();Object.defineProperty(c,"delayWhen",{enumerable:!0,get:function(){return SF.delayWhen}});var PF=wh();Object.defineProperty(c,"dematerialize",{enumerable:!0,get:function(){return PF.dematerialize}});var qF=Ph();Object.defineProperty(c,"distinct",{enumerable:!0,get:function(){return qF.distinct}});var jF=ql();Object.defineProperty(c,"distinctUntilChanged",{enumerable:!0,get:function(){return jF.distinctUntilChanged}});var CF=qh();Object.defineProperty(c,"distinctUntilKeyChanged",{enumerable:!0,get:function(){return CF.distinctUntilKeyChanged}});var IF=Ch();Object.defineProperty(c,"elementAt",{enumerable:!0,get:function(){return IF.elementAt}});var AF=Ih();Object.defineProperty(c,"endWith",{enumerable:!0,get:function(){return AF.endWith}});var xF=Ah();Object.defineProperty(c,"every",{enumerable:!0,get:function(){return xF.every}});var TF=Mh();Object.defineProperty(c,"exhaust",{enumerable:!0,get:function(){return TF.exhaust}});var EF=Cl();Object.defineProperty(c,"exhaustAll",{enumerable:!0,get:function(){return EF.exhaustAll}});var MF=jl();Object.defineProperty(c,"exhaustMap",{enumerable:!0,get:function(){return MF.exhaustMap}});var kF=kh();Object.defineProperty(c,"expand",{enumerable:!0,get:function(){return kF.expand}});var FF=it();Object.defineProperty(c,"filter",{enumerable:!0,get:function(){return FF.filter}});var RF=Fh();Object.defineProperty(c,"finalize",{enumerable:!0,get:function(){return RF.finalize}});var ZF=Il();Object.defineProperty(c,"find",{enumerable:!0,get:function(){return ZF.find}});var UF=Zh();Object.defineProperty(c,"findIndex",{enumerable:!0,get:function(){return UF.findIndex}});var LF=Uh();Object.defineProperty(c,"first",{enumerable:!0,get:function(){return LF.first}});var NF=Nh();Object.defineProperty(c,"groupBy",{enumerable:!0,get:function(){return NF.groupBy}});var zF=wl();Object.defineProperty(c,"ignoreElements",{enumerable:!0,get:function(){return zF.ignoreElements}});var DF=zh();Object.defineProperty(c,"isEmpty",{enumerable:!0,get:function(){return DF.isEmpty}});var VF=Dh();Object.defineProperty(c,"last",{enumerable:!0,get:function(){return VF.last}});var $F=ir();Object.defineProperty(c,"map",{enumerable:!0,get:function(){return $F.map}});var WF=Sl();Object.defineProperty(c,"mapTo",{enumerable:!0,get:function(){return WF.mapTo}});var BF=Vh();Object.defineProperty(c,"materialize",{enumerable:!0,get:function(){return BF.materialize}});var GF=$h();Object.defineProperty(c,"max",{enumerable:!0,get:function(){return GF.max}});var YF=Xn();Object.defineProperty(c,"mergeAll",{enumerable:!0,get:function(){return YF.mergeAll}});var HF=Wh();Object.defineProperty(c,"flatMap",{enumerable:!0,get:function(){return HF.flatMap}});var KF=We();Object.defineProperty(c,"mergeMap",{enumerable:!0,get:function(){return KF.mergeMap}});var JF=Gh();Object.defineProperty(c,"mergeMapTo",{enumerable:!0,get:function(){return JF.mergeMapTo}});var QF=Yh();Object.defineProperty(c,"mergeScan",{enumerable:!0,get:function(){return QF.mergeScan}});var XF=Jh();Object.defineProperty(c,"mergeWith",{enumerable:!0,get:function(){return XF.mergeWith}});var eR=Qh();Object.defineProperty(c,"min",{enumerable:!0,get:function(){return eR.min}});var rR=gu();Object.defineProperty(c,"multicast",{enumerable:!0,get:function(){return rR.multicast}});var tR=Jn();Object.defineProperty(c,"observeOn",{enumerable:!0,get:function(){return tR.observeOn}});var nR=rm();Object.defineProperty(c,"onErrorResumeNextWith",{enumerable:!0,get:function(){return nR.onErrorResumeNextWith}});var iR=tm();Object.defineProperty(c,"pairwise",{enumerable:!0,get:function(){return iR.pairwise}});var oR=nm();Object.defineProperty(c,"pluck",{enumerable:!0,get:function(){return oR.pluck}});var aR=im();Object.defineProperty(c,"publish",{enumerable:!0,get:function(){return aR.publish}});var uR=om();Object.defineProperty(c,"publishBehavior",{enumerable:!0,get:function(){return uR.publishBehavior}});var sR=am();Object.defineProperty(c,"publishLast",{enumerable:!0,get:function(){return sR.publishLast}});var cR=sm();Object.defineProperty(c,"publishReplay",{enumerable:!0,get:function(){return cR.publishReplay}});var lR=cm();Object.defineProperty(c,"raceWith",{enumerable:!0,get:function(){return lR.raceWith}});var dR=yn();Object.defineProperty(c,"reduce",{enumerable:!0,get:function(){return dR.reduce}});var fR=dm();Object.defineProperty(c,"repeat",{enumerable:!0,get:function(){return fR.repeat}});var vR=vm();Object.defineProperty(c,"repeatWhen",{enumerable:!0,get:function(){return vR.repeatWhen}});var pR=hm();Object.defineProperty(c,"retry",{enumerable:!0,get:function(){return pR.retry}});var hR=ym();Object.defineProperty(c,"retryWhen",{enumerable:!0,get:function(){return hR.retryWhen}});var mR=Mc();Object.defineProperty(c,"refCount",{enumerable:!0,get:function(){return mR.refCount}});var yR=Tl();Object.defineProperty(c,"sample",{enumerable:!0,get:function(){return yR.sample}});var _R=bm();Object.defineProperty(c,"sampleTime",{enumerable:!0,get:function(){return _R.sampleTime}});var bR=gm();Object.defineProperty(c,"scan",{enumerable:!0,get:function(){return bR.scan}});var gR=wm();Object.defineProperty(c,"sequenceEqual",{enumerable:!0,get:function(){return gR.sequenceEqual}});var OR=Ml();Object.defineProperty(c,"share",{enumerable:!0,get:function(){return OR.share}});var wR=qm();Object.defineProperty(c,"shareReplay",{enumerable:!0,get:function(){return wR.shareReplay}});var SR=jm();Object.defineProperty(c,"single",{enumerable:!0,get:function(){return SR.single}});var PR=Cm();Object.defineProperty(c,"skip",{enumerable:!0,get:function(){return PR.skip}});var qR=Im();Object.defineProperty(c,"skipLast",{enumerable:!0,get:function(){return qR.skipLast}});var jR=xm();Object.defineProperty(c,"skipUntil",{enumerable:!0,get:function(){return jR.skipUntil}});var CR=Tm();Object.defineProperty(c,"skipWhile",{enumerable:!0,get:function(){return CR.skipWhile}});var IR=Mm();Object.defineProperty(c,"startWith",{enumerable:!0,get:function(){return IR.startWith}});var AR=Qn();Object.defineProperty(c,"subscribeOn",{enumerable:!0,get:function(){return AR.subscribeOn}});var xR=Fm();Object.defineProperty(c,"switchAll",{enumerable:!0,get:function(){return xR.switchAll}});var TR=oi();Object.defineProperty(c,"switchMap",{enumerable:!0,get:function(){return TR.switchMap}});var ER=Zm();Object.defineProperty(c,"switchMapTo",{enumerable:!0,get:function(){return ER.switchMapTo}});var MR=Um();Object.defineProperty(c,"switchScan",{enumerable:!0,get:function(){return MR.switchScan}});var kR=ni();Object.defineProperty(c,"take",{enumerable:!0,get:function(){return kR.take}});var FR=Al();Object.defineProperty(c,"takeLast",{enumerable:!0,get:function(){return FR.takeLast}});var RR=Lm();Object.defineProperty(c,"takeUntil",{enumerable:!0,get:function(){return RR.takeUntil}});var ZR=Nm();Object.defineProperty(c,"takeWhile",{enumerable:!0,get:function(){return ZR.takeWhile}});var UR=zm();Object.defineProperty(c,"tap",{enumerable:!0,get:function(){return UR.tap}});var LR=kl();Object.defineProperty(c,"throttle",{enumerable:!0,get:function(){return LR.throttle}});var NR=Vm();Object.defineProperty(c,"throttleTime",{enumerable:!0,get:function(){return NR.throttleTime}});var zR=ii();Object.defineProperty(c,"throwIfEmpty",{enumerable:!0,get:function(){return zR.throwIfEmpty}});var DR=Wm();Object.defineProperty(c,"timeInterval",{enumerable:!0,get:function(){return DR.timeInterval}});var VR=Yo();Object.defineProperty(c,"timeout",{enumerable:!0,get:function(){return VR.timeout}});var $R=Bm();Object.defineProperty(c,"timeoutWith",{enumerable:!0,get:function(){return $R.timeoutWith}});var WR=Gm();Object.defineProperty(c,"timestamp",{enumerable:!0,get:function(){return WR.timestamp}});var BR=_l();Object.defineProperty(c,"toArray",{enumerable:!0,get:function(){return BR.toArray}});var GR=Km();Object.defineProperty(c,"window",{enumerable:!0,get:function(){return GR.window}});var YR=Qm();Object.defineProperty(c,"windowCount",{enumerable:!0,get:function(){return YR.windowCount}});var HR=ey();Object.defineProperty(c,"windowTime",{enumerable:!0,get:function(){return HR.windowTime}});var KR=ny();Object.defineProperty(c,"windowToggle",{enumerable:!0,get:function(){return KR.windowToggle}});var JR=oy();Object.defineProperty(c,"windowWhen",{enumerable:!0,get:function(){return JR.windowWhen}});var QR=cy();Object.defineProperty(c,"withLatestFrom",{enumerable:!0,get:function(){return QR.withLatestFrom}});var XR=ly();Object.defineProperty(c,"zipAll",{enumerable:!0,get:function(){return XR.zipAll}});var eZ=fy();Object.defineProperty(c,"zipWith",{enumerable:!0,get:function(){return eZ.zipWith}})});var wy=d(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.CopilotStudioWebChat=void 0;var rZ=tc(),tZ=yc(),Oy=by(),nZ=dt(),Be=(0,nZ.debug)("copilot-studio:webchat"),Rl=class{static createConnection(r,t){Be.info("--> Creating connection between Copilot Studio and WebChat ...");let n=0,i,o,a=new Oy.BehaviorSubject(0),u=gy(async f=>{if(i=f,a.value<2){a.next(2);return}Be.debug("--> Connection established."),s();for await(let v of r.startConversationAsync())delete v.replyToId,o=v.conversation,l(v)}),l=f=>{let v={...f,timestamp:new Date().toISOString(),channelData:{...f.channelData,"webchat:sequence-id":n}};n++,Be.debug(`Notify '${v.type}' activity to WebChat:`,v),i==null||i.next(v)},s=()=>{if(!(t!=null&&t.showTyping))return;let f=o?{id:o.id,name:o.name}:{id:"agent",name:"Agent"};l({type:"typing",from:f})};return{connectionStatus$:a,activity$:u,postActivity(f){if(Be.info("--> Preparing to send activity to Copilot Studio ..."),!f)throw new Error("Activity cannot be null.");if(!i)throw new Error("Activity subscriber is not initialized.");return gy(async v=>{try{Be.info("--> Sending activity to Copilot Studio ...");let m=tZ.Activity.fromObject({...f,id:(0,rZ.v4)(),attachments:await iZ(f)});l(m),s(),v.next(m.id);for await(let b of r.sendActivity(m))l(b),Be.info("<-- Activity received correctly from Copilot Studio.");v.complete()}catch(m){Be.error("Error sending Activity to Copilot Studio:",m),v.error(m)}})},end(){Be.info("--> Ending connection between Copilot Studio and WebChat ..."),a.complete(),i&&(i.complete(),i=void 0)}}}};ns.CopilotStudioWebChat=Rl;async function iZ(e){var r;if(e.type!=="message"||!(!((r=e.attachments)===null||r===void 0)&&r.length))return e.attachments||[];let t=[];for(let n of e.attachments){let i=await oZ(n);t.push(i)}return t}async function oZ(e){let r=e.contentUrl;if(!(r!=null&&r.startsWith("blob:")))return e;try{let t=await fetch(r);if(!t.ok)throw new Error(`Failed to fetch blob URL: ${t.status} ${t.statusText}`);let n=await t.blob(),i=await n.arrayBuffer(),o=aZ(i);r=`data:${n.type};base64,${o}`}catch(t){r=e.contentUrl,Be.error("Error processing blob attachment:",r,t)}return{...e,contentUrl:r}}function aZ(e){let r=typeof globalThis.Buffer=="function"?globalThis.Buffer:void 0;if(r&&typeof r.from=="function")return r.from(e).toString("base64");let t="";for(let n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t)}function gy(e){return new Oy.Observable(r=>{Promise.resolve(e(r)).catch(t=>r.error(t))})}});var Sy=d(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.ExecuteTurnRequest=void 0;var Zl=class{constructor(r){this.activity=r}};is.ExecuteTurnRequest=Zl});var qy=d(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.PowerPlatformCloud=void 0;var Py;(function(e){e.Unknown="Unknown",e.Exp="Exp",e.Dev="Dev",e.Test="Test",e.Preprod="Preprod",e.FirstRelease="FirstRelease",e.Prod="Prod",e.Gov="Gov",e.High="High",e.DoD="DoD",e.Mooncake="Mooncake",e.Ex="Ex",e.Rx="Rx",e.Prv="Prv",e.Local="Local",e.GovFR="GovFR",e.Other="Other"})(Py||(os.PowerPlatformCloud=Py={}))});var Iy=d(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.getCopilotStudioConnectionUrl=Cy;us.getTokenAudience=lZ;var Ul=(li(),Fe(ls)),uZ=dt(),E=(di(),Fe(fs)),sZ=(_s(),Fe(Xl)),cZ=(bs(),Fe(ed)),Sn=(0,uZ.debug)("copilot-studio:power-platform");function Cy(e,r){var t,n,i,o,a,u;if(!((t=e.directConnectUrl)===null||t===void 0)&&t.trim()){if(Sn.debug(`Using direct connection: ${e.directConnectUrl}`),!ai(e.directConnectUrl))throw new Error("directConnectUrl must be a valid URL");return e.directConnectUrl.toLowerCase().includes("tenants/00000000-0000-0000-0000-000000000000")?(Sn.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${e.directConnectUrl}`),Cy({...e,directConnectUrl:""},r)):dZ(e.directConnectUrl,r).href}let l=(n=e.cloud)!==null&&n!==void 0?n:E.PowerPlatformCloud.Prod,s=(i=e.copilotAgentType)!==null&&i!==void 0?i:Ul.AgentType.Published;if(Sn.debug(`Using cloud setting: ${l}`),Sn.debug(`Using agent type: ${s}`),!(!((o=e.environmentId)===null||o===void 0)&&o.trim()))throw new Error("EnvironmentId must be provided");if(!(!((a=e.agentIdentifier)===null||a===void 0)&&a.trim()))throw new Error("AgentIdentifier must be provided");if(l===E.PowerPlatformCloud.Other)if(!((u=e.customPowerPlatformCloud)===null||u===void 0)&&u.trim())if(ai(e.customPowerPlatformCloud))Sn.debug(`Using custom Power Platform cloud: ${e.customPowerPlatformCloud}`);else throw new Error("customPowerPlatformCloud must be a valid URL");else throw new Error("customPowerPlatformCloud must be provided when PowerPlatformCloud is Other");let f=fZ(l,e.environmentId,e.customPowerPlatformCloud),m={[Ul.AgentType.Published]:()=>new cZ.PublishedBotStrategy({host:f,schema:e.agentIdentifier}),[Ul.AgentType.Prebuilt]:()=>new sZ.PrebuiltBotStrategy({host:f,identifier:e.agentIdentifier})}[s]().getConversationUrl(r);return Sn.debug(`Generated Copilot Studio connection URL: ${m}`),m}function lZ(e,r=E.PowerPlatformCloud.Unknown,t="",n=""){var i,o;if(!n&&!(e!=null&&e.directConnectUrl)){if(r===E.PowerPlatformCloud.Other&&!t)throw new Error("cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");if(!e&&r===E.PowerPlatformCloud.Unknown)throw new Error("Either settings or cloud must be provided");if(e&&e.cloud&&e.cloud!==E.PowerPlatformCloud.Unknown&&(r=e.cloud),r===E.PowerPlatformCloud.Other)if(t&&ai(t))r=E.PowerPlatformCloud.Other;else if(e!=null&&e.customPowerPlatformCloud&&ai(e.customPowerPlatformCloud))r=E.PowerPlatformCloud.Other,t=e.customPowerPlatformCloud;else throw new Error("Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other");return t!=null||(t="api.unknown.powerplatform.com"),`https://${as(r,t)}/.default`}else if(n||(n=(i=e==null?void 0:e.directConnectUrl)!==null&&i!==void 0?i:""),n&&ai(n)){if(jy(new URL(n))===E.PowerPlatformCloud.Unknown){let a=(o=e==null?void 0:e.cloud)!==null&&o!==void 0?o:r;if(a===E.PowerPlatformCloud.Other||a===E.PowerPlatformCloud.Unknown)throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.");if(a!==E.PowerPlatformCloud.Unknown)return`https://${as(a,"")}/.default`;throw new Error("Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.")}return`https://${as(jy(new URL(n)),"")}/.default`}else throw new Error("DirectConnectUrl must be provided when DirectConnectUrl is set")}function ai(e){try{let r=e.startsWith("http")?e:`https://${e}`;return!!new URL(r)}catch{return!1}}function dZ(e,r){let t=new URL(e);return t.searchParams.has("api-version")||t.searchParams.append("api-version","2022-03-01-preview"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.pathname.includes("/conversations")&&(t.pathname=t.pathname.substring(0,t.pathname.indexOf("/conversations"))),t.pathname=`${t.pathname}/conversations`,r&&(t.pathname=`${t.pathname}/${r}`),t}function fZ(e,r,t){if(e===E.PowerPlatformCloud.Other&&(!t||!t.trim()))throw new Error("cloudBaseAddress must be provided when PowerPlatformCloud is Other");t=t!=null?t:"api.unknown.powerplatform.com";let n=r.toLowerCase().replaceAll("-",""),i=vZ(e),o=n.substring(0,n.length-i),a=n.substring(n.length-i);return new URL(`https://${o}.${a}.environment.${as(e,t)}`)}function as(e,r){switch(e){case E.PowerPlatformCloud.Local:return"api.powerplatform.localhost";case E.PowerPlatformCloud.Exp:return"api.exp.powerplatform.com";case E.PowerPlatformCloud.Dev:return"api.dev.powerplatform.com";case E.PowerPlatformCloud.Prv:return"api.prv.powerplatform.com";case E.PowerPlatformCloud.Test:return"api.test.powerplatform.com";case E.PowerPlatformCloud.Preprod:return"api.preprod.powerplatform.com";case E.PowerPlatformCloud.FirstRelease:case E.PowerPlatformCloud.Prod:return"api.powerplatform.com";case E.PowerPlatformCloud.GovFR:return"api.gov.powerplatform.microsoft.us";case E.PowerPlatformCloud.Gov:return"api.gov.powerplatform.microsoft.us";case E.PowerPlatformCloud.High:return"api.high.powerplatform.microsoft.us";case E.PowerPlatformCloud.DoD:return"api.appsplatform.us";case E.PowerPlatformCloud.Mooncake:return"api.powerplatform.partner.microsoftonline.cn";case E.PowerPlatformCloud.Ex:return"api.powerplatform.eaglex.ic.gov";case E.PowerPlatformCloud.Rx:return"api.powerplatform.microsoft.scloud";case E.PowerPlatformCloud.Other:return r;default:throw new Error(`Invalid cluster category value: ${e}`)}}function vZ(e){switch(e){case E.PowerPlatformCloud.FirstRelease:case E.PowerPlatformCloud.Prod:return 2;default:return 1}}function jy(e){switch(e.host.toLowerCase()){case"api.powerplatform.localhost":return E.PowerPlatformCloud.Local;case"api.exp.powerplatform.com":return E.PowerPlatformCloud.Exp;case"api.dev.powerplatform.com":return E.PowerPlatformCloud.Dev;case"api.prv.powerplatform.com":return E.PowerPlatformCloud.Prv;case"api.test.powerplatform.com":return E.PowerPlatformCloud.Test;case"api.preprod.powerplatform.com":return E.PowerPlatformCloud.Preprod;case"api.powerplatform.com":return E.PowerPlatformCloud.Prod;case"api.gov.powerplatform.microsoft.us":return E.PowerPlatformCloud.GovFR;case"api.high.powerplatform.microsoft.us":return E.PowerPlatformCloud.High;case"api.appsplatform.us":return E.PowerPlatformCloud.DoD;case"api.powerplatform.partner.microsoftonline.cn":return E.PowerPlatformCloud.Mooncake;default:return E.PowerPlatformCloud.Unknown}}});var P={};q(P,ke(Vl()));q(P,ke($l()));q(P,ke($f()));q(P,ke(Bf()));q(P,ke(wy()));q(P,ke(Sy()));q(P,ke(qy()));q(P,ke(Iy())); +//# sourceMappingURL=browser.mjs.map diff --git a/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs.map b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs.map new file mode 100644 index 00000000..1bfdd34a --- /dev/null +++ b/ShowReasoningSample/pkg/agents-copilotstudio-client/dist/src/browser.mjs.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../src/agentType.ts", "../../src/agentType.ts", "../../src/powerPlatformCloud.ts", "../../src/connectionSettings.ts", "../../../../node_modules/eventsource-parser/src/errors.ts", "../../../../node_modules/eventsource-parser/src/parse.ts", "../../../../node_modules/eventsource-client/src/constants.ts", "../../../../node_modules/eventsource-client/src/client.ts", "../../../../node_modules/eventsource-client/src/default.ts", "../../../../node_modules/ms/index.js", "../../../../node_modules/debug/src/common.js", "../../../../node_modules/debug/src/browser.js", "../../../agents-activity/src/logger.ts", "../../src/strategies/prebuiltBotStrategy.ts", "../../src/strategies/publishedBotStrategy.ts", "../../src/powerPlatformEnvironment.ts", "../../../../node_modules/zod/v3/helpers/util.cjs", "../../../../node_modules/zod/v3/ZodError.cjs", "../../../../node_modules/zod/v3/locales/en.cjs", "../../../../node_modules/zod/v3/errors.cjs", "../../../../node_modules/zod/v3/helpers/parseUtil.cjs", "../../../../node_modules/zod/v3/helpers/typeAliases.cjs", "../../../../node_modules/zod/v3/helpers/errorUtil.cjs", "../../../../node_modules/zod/v3/types.cjs", "../../../../node_modules/zod/v3/external.cjs", "../../../../node_modules/zod/index.cjs", "../../../agents-activity/src/action/actionTypes.ts", "../../../agents-activity/src/action/semanticActionStateTypes.ts", "../../../agents-activity/src/attachment/attachmentLayoutTypes.ts", "../../../agents-activity/src/conversation/channels.ts", "../../../agents-activity/src/conversation/endOfConversationCodes.ts", "../../../agents-activity/src/conversation/membershipSourceTypes.ts", "../../../agents-activity/src/conversation/membershipTypes.ts", "../../../agents-activity/src/conversation/roleTypes.ts", "../../../agents-activity/src/entity/AIEntity.ts", "../../../agents-activity/src/invoke/adaptiveCardInvokeAction.ts", "../../../../node_modules/uuid/dist/cjs-browser/max.js", "../../../../node_modules/uuid/dist/cjs-browser/nil.js", "../../../../node_modules/uuid/dist/cjs-browser/regex.js", "../../../../node_modules/uuid/dist/cjs-browser/validate.js", "../../../../node_modules/uuid/dist/cjs-browser/parse.js", "../../../../node_modules/uuid/dist/cjs-browser/stringify.js", "../../../../node_modules/uuid/dist/cjs-browser/rng.js", "../../../../node_modules/uuid/dist/cjs-browser/v1.js", "../../../../node_modules/uuid/dist/cjs-browser/v1ToV6.js", "../../../../node_modules/uuid/dist/cjs-browser/md5.js", "../../../../node_modules/uuid/dist/cjs-browser/v35.js", "../../../../node_modules/uuid/dist/cjs-browser/v3.js", "../../../../node_modules/uuid/dist/cjs-browser/native.js", "../../../../node_modules/uuid/dist/cjs-browser/v4.js", "../../../../node_modules/uuid/dist/cjs-browser/sha1.js", "../../../../node_modules/uuid/dist/cjs-browser/v5.js", "../../../../node_modules/uuid/dist/cjs-browser/v6.js", "../../../../node_modules/uuid/dist/cjs-browser/v6ToV1.js", "../../../../node_modules/uuid/dist/cjs-browser/v7.js", "../../../../node_modules/uuid/dist/cjs-browser/version.js", "../../../../node_modules/uuid/dist/cjs-browser/index.js", "../../../agents-activity/src/entity/entity.ts", "../../../agents-activity/src/action/semanticAction.ts", "../../../agents-activity/src/action/cardAction.ts", "../../../agents-activity/src/action/suggestedActions.ts", "../../../agents-activity/src/activityEventNames.ts", "../../../agents-activity/src/activityImportance.ts", "../../../agents-activity/src/activityTypes.ts", "../../../agents-activity/src/attachment/attachment.ts", "../../../agents-activity/src/conversation/channelAccount.ts", "../../../agents-activity/src/conversation/conversationAccount.ts", "../../../agents-activity/src/conversation/conversationReference.ts", "../../../agents-activity/src/deliveryModes.ts", "../../../agents-activity/src/inputHints.ts", "../../../agents-activity/src/messageReactionTypes.ts", "../../../agents-activity/src/messageReaction.ts", "../../../agents-activity/src/textFormatTypes.ts", "../../../agents-activity/src/textHighlight.ts", "../../../agents-activity/src/activity.ts", "../../../agents-activity/src/callerIdConstants.ts", "../../../agents-activity/src/activityTreatments.ts", "../../../agents-activity/src/index.ts", "../../src/executeTurnRequest.ts", "../../package.json", "../../src/browser/os.ts", "../../src/copilotStudioClient.ts", "../../../../node_modules/rxjs/src/internal/util/isFunction.ts", "../../../../node_modules/rxjs/src/internal/util/createErrorClass.ts", "../../../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts", "../../../../node_modules/rxjs/src/internal/util/arrRemove.ts", "../../../../node_modules/rxjs/src/internal/Subscription.ts", "../../../../node_modules/rxjs/src/internal/config.ts", "../../../../node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts", "../../../../node_modules/rxjs/src/internal/util/reportUnhandledError.ts", "../../../../node_modules/rxjs/src/internal/util/noop.ts", "../../../../node_modules/rxjs/src/internal/NotificationFactories.ts", "../../../../node_modules/rxjs/src/internal/util/errorContext.ts", "../../../../node_modules/rxjs/src/internal/Subscriber.ts", "../../../../node_modules/rxjs/src/internal/symbol/observable.ts", "../../../../node_modules/rxjs/src/internal/util/identity.ts", "../../../../node_modules/rxjs/src/internal/util/pipe.ts", "../../../../node_modules/rxjs/src/internal/Observable.ts", "../../../../node_modules/rxjs/src/internal/util/lift.ts", "../../../../node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts", "../../../../node_modules/rxjs/src/internal/operators/refCount.ts", "../../../../node_modules/rxjs/src/internal/observable/ConnectableObservable.ts", "../../../../node_modules/rxjs/src/internal/scheduler/performanceTimestampProvider.ts", "../../../../node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts", "../../../../node_modules/rxjs/src/internal/observable/dom/animationFrames.ts", "../../../../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts", "../../../../node_modules/rxjs/src/internal/Subject.ts", "../../../../node_modules/rxjs/src/internal/BehaviorSubject.ts", "../../../../node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts", "../../../../node_modules/rxjs/src/internal/ReplaySubject.ts", "../../../../node_modules/rxjs/src/internal/AsyncSubject.ts", "../../../../node_modules/rxjs/src/internal/scheduler/Action.ts", "../../../../node_modules/rxjs/src/internal/scheduler/intervalProvider.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AsyncAction.ts", "../../../../node_modules/rxjs/src/internal/util/Immediate.ts", "../../../../node_modules/rxjs/src/internal/scheduler/immediateProvider.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AsapAction.ts", "../../../../node_modules/rxjs/src/internal/Scheduler.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AsapScheduler.ts", "../../../../node_modules/rxjs/src/internal/scheduler/asap.ts", "../../../../node_modules/rxjs/src/internal/scheduler/async.ts", "../../../../node_modules/rxjs/src/internal/scheduler/QueueAction.ts", "../../../../node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts", "../../../../node_modules/rxjs/src/internal/scheduler/queue.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts", "../../../../node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts", "../../../../node_modules/rxjs/src/internal/scheduler/animationFrame.ts", "../../../../node_modules/rxjs/src/internal/scheduler/VirtualTimeScheduler.ts", "../../../../node_modules/rxjs/src/internal/observable/empty.ts", "../../../../node_modules/rxjs/src/internal/util/isScheduler.ts", "../../../../node_modules/rxjs/src/internal/util/args.ts", "../../../../node_modules/rxjs/src/internal/util/isArrayLike.ts", "../../../../node_modules/rxjs/src/internal/util/isPromise.ts", "../../../../node_modules/rxjs/src/internal/util/isInteropObservable.ts", "../../../../node_modules/rxjs/src/internal/util/isAsyncIterable.ts", "../../../../node_modules/rxjs/src/internal/util/throwUnobservableError.ts", "../../../../node_modules/rxjs/src/internal/symbol/iterator.ts", "../../../../node_modules/rxjs/src/internal/util/isIterable.ts", "../../../../node_modules/rxjs/src/internal/util/isReadableStreamLike.ts", "../../../../node_modules/rxjs/src/internal/observable/innerFrom.ts", "../../../../node_modules/rxjs/src/internal/util/executeSchedule.ts", "../../../../node_modules/rxjs/src/internal/operators/observeOn.ts", "../../../../node_modules/rxjs/src/internal/operators/subscribeOn.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts", "../../../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "../../../../node_modules/rxjs/src/internal/scheduled/scheduled.ts", "../../../../node_modules/rxjs/src/internal/observable/from.ts", "../../../../node_modules/rxjs/src/internal/observable/of.ts", "../../../../node_modules/rxjs/src/internal/observable/throwError.ts", "../../../../node_modules/rxjs/src/internal/Notification.ts", "../../../../node_modules/rxjs/src/internal/util/isObservable.ts", "../../../../node_modules/rxjs/src/internal/util/EmptyError.ts", "../../../../node_modules/rxjs/src/internal/lastValueFrom.ts", "../../../../node_modules/rxjs/src/internal/firstValueFrom.ts", "../../../../node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts", "../../../../node_modules/rxjs/src/internal/util/NotFoundError.ts", "../../../../node_modules/rxjs/src/internal/util/SequenceError.ts", "../../../../node_modules/rxjs/src/internal/util/isDate.ts", "../../../../node_modules/rxjs/src/internal/operators/timeout.ts", "../../../../node_modules/rxjs/src/internal/operators/map.ts", "../../../../node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts", "../../../../node_modules/rxjs/src/internal/observable/bindCallbackInternals.ts", "../../../../node_modules/rxjs/src/internal/observable/bindCallback.ts", "../../../../node_modules/rxjs/src/internal/observable/bindNodeCallback.ts", "../../../../node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts", "../../../../node_modules/rxjs/src/internal/util/createObject.ts", "../../../../node_modules/rxjs/src/internal/observable/combineLatest.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeInternals.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeMap.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeAll.ts", "../../../../node_modules/rxjs/src/internal/operators/concatAll.ts", "../../../../node_modules/rxjs/src/internal/observable/concat.ts", "../../../../node_modules/rxjs/src/internal/observable/defer.ts", "../../../../node_modules/rxjs/src/internal/observable/connectable.ts", "../../../../node_modules/rxjs/src/internal/observable/forkJoin.ts", "../../../../node_modules/rxjs/src/internal/observable/fromEvent.ts", "../../../../node_modules/rxjs/src/internal/observable/fromEventPattern.ts", "../../../../node_modules/rxjs/src/internal/observable/generate.ts", "../../../../node_modules/rxjs/src/internal/observable/iif.ts", "../../../../node_modules/rxjs/src/internal/observable/timer.ts", "../../../../node_modules/rxjs/src/internal/observable/interval.ts", "../../../../node_modules/rxjs/src/internal/observable/merge.ts", "../../../../node_modules/rxjs/src/internal/observable/never.ts", "../../../../node_modules/rxjs/src/internal/util/argsOrArgArray.ts", "../../../../node_modules/rxjs/src/internal/observable/onErrorResumeNext.ts", "../../../../node_modules/rxjs/src/internal/observable/pairs.ts", "../../../../node_modules/rxjs/src/internal/util/not.ts", "../../../../node_modules/rxjs/src/internal/operators/filter.ts", "../../../../node_modules/rxjs/src/internal/observable/partition.ts", "../../../../node_modules/rxjs/src/internal/observable/race.ts", "../../../../node_modules/rxjs/src/internal/observable/range.ts", "../../../../node_modules/rxjs/src/internal/observable/using.ts", "../../../../node_modules/rxjs/src/internal/observable/zip.ts", "../../../../node_modules/rxjs/dist/cjs/internal/types.js", "../../../../node_modules/rxjs/src/internal/operators/audit.ts", "../../../../node_modules/rxjs/src/internal/operators/auditTime.ts", "../../../../node_modules/rxjs/src/internal/operators/buffer.ts", "../../../../node_modules/rxjs/src/internal/operators/bufferCount.ts", "../../../../node_modules/rxjs/src/internal/operators/bufferTime.ts", "../../../../node_modules/rxjs/src/internal/operators/bufferToggle.ts", "../../../../node_modules/rxjs/src/internal/operators/bufferWhen.ts", "../../../../node_modules/rxjs/src/internal/operators/catchError.ts", "../../../../node_modules/rxjs/src/internal/operators/scanInternals.ts", "../../../../node_modules/rxjs/src/internal/operators/reduce.ts", "../../../../node_modules/rxjs/src/internal/operators/toArray.ts", "../../../../node_modules/rxjs/src/internal/operators/joinAllInternals.ts", "../../../../node_modules/rxjs/src/internal/operators/combineLatestAll.ts", "../../../../node_modules/rxjs/src/internal/operators/combineAll.ts", "../../../../node_modules/rxjs/src/internal/operators/combineLatest.ts", "../../../../node_modules/rxjs/src/internal/operators/combineLatestWith.ts", "../../../../node_modules/rxjs/src/internal/operators/concatMap.ts", "../../../../node_modules/rxjs/src/internal/operators/concatMapTo.ts", "../../../../node_modules/rxjs/src/internal/operators/concat.ts", "../../../../node_modules/rxjs/src/internal/operators/concatWith.ts", "../../../../node_modules/rxjs/src/internal/observable/fromSubscribable.ts", "../../../../node_modules/rxjs/src/internal/operators/connect.ts", "../../../../node_modules/rxjs/src/internal/operators/count.ts", "../../../../node_modules/rxjs/src/internal/operators/debounce.ts", "../../../../node_modules/rxjs/src/internal/operators/debounceTime.ts", "../../../../node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts", "../../../../node_modules/rxjs/src/internal/operators/take.ts", "../../../../node_modules/rxjs/src/internal/operators/ignoreElements.ts", "../../../../node_modules/rxjs/src/internal/operators/mapTo.ts", "../../../../node_modules/rxjs/src/internal/operators/delayWhen.ts", "../../../../node_modules/rxjs/src/internal/operators/delay.ts", "../../../../node_modules/rxjs/src/internal/operators/dematerialize.ts", "../../../../node_modules/rxjs/src/internal/operators/distinct.ts", "../../../../node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts", "../../../../node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts", "../../../../node_modules/rxjs/src/internal/operators/throwIfEmpty.ts", "../../../../node_modules/rxjs/src/internal/operators/elementAt.ts", "../../../../node_modules/rxjs/src/internal/operators/endWith.ts", "../../../../node_modules/rxjs/src/internal/operators/every.ts", "../../../../node_modules/rxjs/src/internal/operators/exhaustMap.ts", "../../../../node_modules/rxjs/src/internal/operators/exhaustAll.ts", "../../../../node_modules/rxjs/src/internal/operators/exhaust.ts", "../../../../node_modules/rxjs/src/internal/operators/expand.ts", "../../../../node_modules/rxjs/src/internal/operators/finalize.ts", "../../../../node_modules/rxjs/src/internal/operators/find.ts", "../../../../node_modules/rxjs/src/internal/operators/findIndex.ts", "../../../../node_modules/rxjs/src/internal/operators/first.ts", "../../../../node_modules/rxjs/src/internal/operators/groupBy.ts", "../../../../node_modules/rxjs/src/internal/operators/isEmpty.ts", "../../../../node_modules/rxjs/src/internal/operators/takeLast.ts", "../../../../node_modules/rxjs/src/internal/operators/last.ts", "../../../../node_modules/rxjs/src/internal/operators/materialize.ts", "../../../../node_modules/rxjs/src/internal/operators/max.ts", "../../../../node_modules/rxjs/src/internal/operators/flatMap.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeMapTo.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeScan.ts", "../../../../node_modules/rxjs/src/internal/operators/merge.ts", "../../../../node_modules/rxjs/src/internal/operators/mergeWith.ts", "../../../../node_modules/rxjs/src/internal/operators/min.ts", "../../../../node_modules/rxjs/src/internal/operators/multicast.ts", "../../../../node_modules/rxjs/src/internal/operators/onErrorResumeNextWith.ts", "../../../../node_modules/rxjs/src/internal/operators/pairwise.ts", "../../../../node_modules/rxjs/src/internal/operators/pluck.ts", "../../../../node_modules/rxjs/src/internal/operators/publish.ts", "../../../../node_modules/rxjs/src/internal/operators/publishBehavior.ts", "../../../../node_modules/rxjs/src/internal/operators/publishLast.ts", "../../../../node_modules/rxjs/src/internal/operators/publishReplay.ts", "../../../../node_modules/rxjs/src/internal/operators/raceWith.ts", "../../../../node_modules/rxjs/src/internal/operators/repeat.ts", "../../../../node_modules/rxjs/src/internal/operators/repeatWhen.ts", "../../../../node_modules/rxjs/src/internal/operators/retry.ts", "../../../../node_modules/rxjs/src/internal/operators/retryWhen.ts", "../../../../node_modules/rxjs/src/internal/operators/sample.ts", "../../../../node_modules/rxjs/src/internal/operators/sampleTime.ts", "../../../../node_modules/rxjs/src/internal/operators/scan.ts", "../../../../node_modules/rxjs/src/internal/operators/sequenceEqual.ts", "../../../../node_modules/rxjs/src/internal/operators/share.ts", "../../../../node_modules/rxjs/src/internal/operators/shareReplay.ts", "../../../../node_modules/rxjs/src/internal/operators/single.ts", "../../../../node_modules/rxjs/src/internal/operators/skip.ts", "../../../../node_modules/rxjs/src/internal/operators/skipLast.ts", "../../../../node_modules/rxjs/src/internal/operators/skipUntil.ts", "../../../../node_modules/rxjs/src/internal/operators/skipWhile.ts", "../../../../node_modules/rxjs/src/internal/operators/startWith.ts", "../../../../node_modules/rxjs/src/internal/operators/switchMap.ts", "../../../../node_modules/rxjs/src/internal/operators/switchAll.ts", "../../../../node_modules/rxjs/src/internal/operators/switchMapTo.ts", "../../../../node_modules/rxjs/src/internal/operators/switchScan.ts", "../../../../node_modules/rxjs/src/internal/operators/takeUntil.ts", "../../../../node_modules/rxjs/src/internal/operators/takeWhile.ts", "../../../../node_modules/rxjs/src/internal/operators/tap.ts", "../../../../node_modules/rxjs/src/internal/operators/throttle.ts", "../../../../node_modules/rxjs/src/internal/operators/throttleTime.ts", "../../../../node_modules/rxjs/src/internal/operators/timeInterval.ts", "../../../../node_modules/rxjs/src/internal/operators/timeoutWith.ts", "../../../../node_modules/rxjs/src/internal/operators/timestamp.ts", "../../../../node_modules/rxjs/src/internal/operators/window.ts", "../../../../node_modules/rxjs/src/internal/operators/windowCount.ts", "../../../../node_modules/rxjs/src/internal/operators/windowTime.ts", "../../../../node_modules/rxjs/src/internal/operators/windowToggle.ts", "../../../../node_modules/rxjs/src/internal/operators/windowWhen.ts", "../../../../node_modules/rxjs/src/internal/operators/withLatestFrom.ts", "../../../../node_modules/rxjs/src/internal/operators/zipAll.ts", "../../../../node_modules/rxjs/src/internal/operators/zip.ts", "../../../../node_modules/rxjs/src/internal/operators/zipWith.ts", "../../../../node_modules/rxjs/src/index.ts", "../../src/copilotStudioWebChat.ts", "../../src/executeTurnRequest.ts", "../../src/powerPlatformCloud.ts", "../../src/powerPlatformEnvironment.ts", "../../src/index.ts"], + "sourcesContent": ["/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Enum representing the type of agent.\r\n */\r\nexport enum AgentType {\r\n /**\r\n * Represents a published agent.\r\n */\r\n Published = 'Published',\r\n /**\r\n * Represents a prebuilt agent.\r\n */\r\n Prebuilt = 'Prebuilt',\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Enum representing the type of agent.\r\n */\r\nexport enum AgentType {\r\n /**\r\n * Represents a published agent.\r\n */\r\n Published = 'Published',\r\n /**\r\n * Represents a prebuilt agent.\r\n */\r\n Prebuilt = 'Prebuilt',\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Enum representing different Power Platform cloud environments.\r\n */\r\nexport enum PowerPlatformCloud {\r\n /**\r\n * Unknown cloud environment.\r\n */\r\n Unknown = 'Unknown',\r\n /**\r\n * Experimental cloud environment.\r\n */\r\n Exp = 'Exp',\r\n /**\r\n * Development cloud environment.\r\n */\r\n Dev = 'Dev',\r\n /**\r\n * Test cloud environment.\r\n */\r\n Test = 'Test',\r\n /**\r\n * Pre-production cloud environment.\r\n */\r\n Preprod = 'Preprod',\r\n /**\r\n * First release cloud environment.\r\n */\r\n FirstRelease = 'FirstRelease',\r\n /**\r\n * Production cloud environment.\r\n */\r\n Prod = 'Prod',\r\n /**\r\n * Government cloud environment.\r\n */\r\n Gov = 'Gov',\r\n /**\r\n * High security cloud environment.\r\n */\r\n High = 'High',\r\n /**\r\n * Department of Defense cloud environment.\r\n */\r\n DoD = 'DoD',\r\n /**\r\n * Mooncake cloud environment.\r\n */\r\n Mooncake = 'Mooncake',\r\n /**\r\n * Ex cloud environment.\r\n */\r\n Ex = 'Ex',\r\n /**\r\n * Rx cloud environment.\r\n */\r\n Rx = 'Rx',\r\n /**\r\n * Private cloud environment.\r\n */\r\n Prv = 'Prv',\r\n /**\r\n * Local cloud environment.\r\n */\r\n Local = 'Local',\r\n /**\r\n * French government cloud environment.\r\n */\r\n GovFR = 'GovFR',\r\n /**\r\n * Other cloud environment.\r\n */\r\n Other = 'Other',\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { AgentType } from './agentType'\r\nimport { CopilotStudioConnectionSettings } from './copilotStudioConnectionSettings'\r\nimport { PowerPlatformCloud } from './powerPlatformCloud'\r\n\r\n/**\r\n * Configuration options for establishing a connection to Copilot Studio.\r\n */\r\nabstract class ConnectionOptions implements Omit {\r\n /** The client ID of the application. */\r\n public appClientId: string = ''\r\n /** The tenant ID of the application. */\r\n public tenantId: string = ''\r\n /** The login authority to use for the connection */\r\n public authority?: string = ''\r\n /** The environment ID of the application. */\r\n public environmentId: string = ''\r\n /** The identifier of the agent. */\r\n public agentIdentifier: string = ''\r\n /** The cloud environment of the application. */\r\n public cloud?: PowerPlatformCloud | keyof typeof PowerPlatformCloud\r\n /** The custom Power Platform cloud URL, if any. */\r\n public customPowerPlatformCloud?: string\r\n /** The type of the Copilot agent. */\r\n public copilotAgentType?: AgentType | keyof typeof AgentType\r\n /** The URL to connect directly to Copilot Studio endpoint */\r\n public directConnectUrl?: string\r\n /** Flag to use the experimental endpoint if available */\r\n public useExperimentalEndpoint?: boolean = false\r\n}\r\n\r\n/**\r\n * Represents the settings required to establish a connection to Copilot Studio.\r\n */\r\nexport class ConnectionSettings extends ConnectionOptions {\r\n /** The cloud environment of the application. */\r\n public cloud?: PowerPlatformCloud\r\n /** The type of the Copilot agent. */\r\n public copilotAgentType?: AgentType\r\n\r\n /**\r\n * Default constructor for the ConnectionSettings class.\r\n */\r\n constructor ()\r\n\r\n /**\r\n * Creates an instance of ConnectionSettings.\r\n * @param options Represents the settings required to establish a direct connection to the engine.\r\n */\r\n constructor (options: ConnectionOptions)\r\n\r\n /**\r\n * @private\r\n */\r\n constructor (options?: ConnectionOptions) {\r\n super()\r\n\r\n if (!options) {\r\n return\r\n }\r\n\r\n const cloud = options.cloud ?? PowerPlatformCloud.Prod\r\n const copilotAgentType = options.copilotAgentType ?? AgentType.Published\r\n const authority = options.authority && options.authority.trim() !== ''\r\n ? options.authority\r\n : 'https://login.microsoftonline.com'\r\n\r\n if (!Object.values(PowerPlatformCloud).includes(cloud as PowerPlatformCloud)) {\r\n throw new Error(`Invalid PowerPlatformCloud: '${cloud}'. Supported values: ${Object.values(PowerPlatformCloud).join(', ')}`)\r\n }\r\n\r\n if (!Object.values(AgentType).includes(copilotAgentType as AgentType)) {\r\n throw new Error(`Invalid AgentType: '${copilotAgentType}'. Supported values: ${Object.values(AgentType).join(', ')}`)\r\n }\r\n\r\n Object.assign(this, { ...options, cloud, copilotAgentType, authority })\r\n }\r\n}\r\n\r\n/**\r\n * Loads the connection settings for Copilot Studio from environment variables.\r\n * @returns The connection settings.\r\n */\r\nexport const loadCopilotStudioConnectionSettingsFromEnv: () => ConnectionSettings = () => {\r\n return new ConnectionSettings({\r\n appClientId: process.env.appClientId ?? '',\r\n tenantId: process.env.tenantId ?? '',\r\n authority: process.env.authorityEndpoint ?? 'https://login.microsoftonline.com',\r\n environmentId: process.env.environmentId ?? '',\r\n agentIdentifier: process.env.agentIdentifier ?? '',\r\n cloud: process.env.cloud as PowerPlatformCloud,\r\n customPowerPlatformCloud: process.env.customPowerPlatformCloud,\r\n copilotAgentType: process.env.copilotAgentType as AgentType,\r\n directConnectUrl: process.env.directConnectUrl,\r\n useExperimentalEndpoint: process.env.useExperimentalEndpoint?.toLowerCase() === 'true'\r\n })\r\n}\r\n", "/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n /**\n * The type of error that occurred.\n */\n type: ErrorType\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the field name.\n */\n field?: string | undefined\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the value of the field.\n */\n value?: string | undefined\n\n /**\n * The line that caused the error, if available.\n */\n line?: string | undefined\n\n constructor(\n message: string,\n options: {type: ErrorType; field?: string; value?: string; line?: string},\n ) {\n super(message)\n this.name = 'ParseError'\n this.type = options.type\n this.field = options.field\n this.value = options.value\n this.line = options.line\n }\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserCallbacks} from './types.ts'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction noop(_arg: unknown) {\n // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param callbacks - Callbacks to invoke on different parsing events:\n * - `onEvent` when a new event is parsed\n * - `onError` when an error occurs\n * - `onRetry` when a new reconnection interval has been sent from the server\n * - `onComment` when a comment is encountered in the stream\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(callbacks: ParserCallbacks): EventSourceParser {\n if (typeof callbacks === 'function') {\n throw new TypeError(\n '`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?',\n )\n }\n\n const {onEvent = noop, onError = noop, onRetry = noop, onComment} = callbacks\n\n let incompleteLine = ''\n\n let isFirstChunk = true\n let id: string | undefined\n let data = ''\n let eventType = ''\n\n function feed(newChunk: string) {\n // Strip any UTF8 byte order mark (BOM) at the start of the stream\n const chunk = isFirstChunk ? newChunk.replace(/^\\xEF\\xBB\\xBF/, '') : newChunk\n\n // If there was a previous incomplete line, append it to the new chunk,\n // so we may process it together as a new (hopefully complete) chunk.\n const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`)\n\n for (const line of complete) {\n parseLine(line)\n }\n\n incompleteLine = incomplete\n isFirstChunk = false\n }\n\n function parseLine(line: string) {\n // If the line is empty (a blank line), dispatch the event\n if (line === '') {\n dispatchEvent()\n return\n }\n\n // If the line starts with a U+003A COLON character (:), ignore the line.\n if (line.startsWith(':')) {\n if (onComment) {\n onComment(line.slice(line.startsWith(': ') ? 2 : 1))\n }\n return\n }\n\n // If the line contains a U+003A COLON character (:)\n const fieldSeparatorIndex = line.indexOf(':')\n if (fieldSeparatorIndex !== -1) {\n // Collect the characters on the line before the first U+003A COLON character (:),\n // and let `field` be that string.\n const field = line.slice(0, fieldSeparatorIndex)\n\n // Collect the characters on the line after the first U+003A COLON character (:),\n // and let `value` be that string. If value starts with a U+0020 SPACE character,\n // remove it from value.\n const offset = line[fieldSeparatorIndex + 1] === ' ' ? 2 : 1\n const value = line.slice(fieldSeparatorIndex + offset)\n\n processField(field, value, line)\n return\n }\n\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (:)\n // Process the field using the whole line as the field name, and an empty string as the field value.\n // 👆 This is according to spec. That means that a line that has the value `data` will result in\n // a newline being added to the current `data` buffer, for instance.\n processField(line, '', line)\n }\n\n function processField(field: string, value: string, line: string) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value\n break\n case 'data':\n // Append the field value to the `data` buffer, then append a single U+000A LINE FEED(LF)\n // character to the `data` buffer.\n data = `${data}${value}\\n`\n break\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n id = value.includes('\\0') ? undefined : value\n break\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry(parseInt(value, 10))\n } else {\n onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }),\n )\n }\n break\n default:\n // Otherwise, the field is ignored.\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n {type: 'unknown-field', field, value, line},\n ),\n )\n break\n }\n }\n\n function dispatchEvent() {\n const shouldDispatch = data.length > 0\n if (shouldDispatch) {\n onEvent({\n id,\n event: eventType || undefined,\n // If the data buffer's last character is a U+000A LINE FEED (LF) character,\n // then remove the last character from the data buffer.\n data: data.endsWith('\\n') ? data.slice(0, -1) : data,\n })\n }\n\n // Reset for the next event\n id = undefined\n data = ''\n eventType = ''\n }\n\n function reset(options: {consume?: boolean} = {}) {\n if (incompleteLine && options.consume) {\n parseLine(incompleteLine)\n }\n\n isFirstChunk = true\n id = undefined\n data = ''\n eventType = ''\n incompleteLine = ''\n }\n\n return {feed, reset}\n}\n\n/**\n * For the given `chunk`, split it into lines according to spec, and return any remaining incomplete line.\n *\n * @param chunk - The chunk to split into lines\n * @returns A tuple containing an array of complete lines, and any remaining incomplete line\n * @internal\n */\nfunction splitLines(chunk: string): [complete: Array, incomplete: string] {\n /**\n * According to the spec, a line is terminated by either:\n * - U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair\n * - a single U+000A LINE FEED(LF) character not preceded by a U+000D CARRIAGE RETURN(CR) character\n * - a single U+000D CARRIAGE RETURN(CR) character not followed by a U+000A LINE FEED(LF) character\n */\n const lines: Array = []\n let incompleteLine = ''\n let searchIndex = 0\n\n while (searchIndex < chunk.length) {\n // Find next line terminator\n const crIndex = chunk.indexOf('\\r', searchIndex)\n const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n // Determine line end\n let lineEnd = -1\n if (crIndex !== -1 && lfIndex !== -1) {\n // CRLF case\n lineEnd = Math.min(crIndex, lfIndex)\n } else if (crIndex !== -1) {\n // CR at the end of a chunk might be part of a CRLF sequence that spans chunks,\n // so we shouldn't treat it as a line terminator (yet)\n if (crIndex === chunk.length - 1) {\n lineEnd = -1\n } else {\n lineEnd = crIndex\n }\n } else if (lfIndex !== -1) {\n lineEnd = lfIndex\n }\n\n // Extract line if terminator found\n if (lineEnd === -1) {\n // No terminator found, rest is incomplete\n incompleteLine = chunk.slice(searchIndex)\n break\n } else {\n const line = chunk.slice(searchIndex, lineEnd)\n lines.push(line)\n\n // Move past line terminator\n searchIndex = lineEnd + 1\n if (chunk[searchIndex - 1] === '\\r' && chunk[searchIndex] === '\\n') {\n searchIndex++\n }\n }\n }\n\n return [lines, incompleteLine]\n}\n", "// ReadyStates, mirrors WhatWG spec, but uses strings instead of numbers.\n// Why make it harder to read than it needs to be?\n\n/**\n * ReadyState representing a connection that is connecting or has been scheduled to reconnect.\n * @public\n */\nexport const CONNECTING = 'connecting'\n\n/**\n * ReadyState representing a connection that is open, eg connected.\n * @public\n */\nexport const OPEN = 'open'\n\n/**\n * ReadyState representing a connection that has been closed (manually, or due to an error).\n * @public\n */\nexport const CLOSED = 'closed'\n", "import {createParser} from 'eventsource-parser'\n\nimport type {EnvAbstractions, EventSourceAsyncValueResolver} from './abstractions.js'\nimport {CLOSED, CONNECTING, OPEN} from './constants.js'\nimport type {\n EventSourceClient,\n EventSourceMessage,\n EventSourceOptions,\n FetchLike,\n FetchLikeInit,\n FetchLikeResponse,\n ReadyState,\n} from './types.js'\n\n/**\n * Intentional noop function for eased control flow\n */\nconst noop = () => {\n /* intentional noop */\n}\n\n/**\n * Creates a new EventSource client. Used internally by the environment-specific entry points,\n * and should not be used directly by consumers.\n *\n * @param optionsOrUrl - Options for the client, or an URL/URL string.\n * @param abstractions - Abstractions for the environments.\n * @returns A new EventSource client instance\n * @internal\n */\nexport function createEventSource(\n optionsOrUrl: EventSourceOptions | string | URL,\n {getStream}: EnvAbstractions,\n): EventSourceClient {\n const options =\n typeof optionsOrUrl === 'string' || optionsOrUrl instanceof URL\n ? {url: optionsOrUrl}\n : optionsOrUrl\n const {\n onMessage,\n onComment = noop,\n onConnect = noop,\n onDisconnect = noop,\n onScheduleReconnect = noop,\n } = options\n const {fetch, url, initialLastEventId} = validate(options)\n const requestHeaders = {...options.headers} // Prevent post-creation mutations to headers\n\n const onCloseSubscribers: (() => void)[] = []\n const subscribers: ((event: EventSourceMessage) => void)[] = onMessage ? [onMessage] : []\n const emit = (event: EventSourceMessage) => subscribers.forEach((fn) => fn(event))\n const parser = createParser({onEvent, onRetry, onComment})\n\n // Client state\n let request: Promise | null\n let currentUrl = url.toString()\n let controller = new AbortController()\n let lastEventId = initialLastEventId\n let reconnectMs = 2000\n let reconnectTimer: ReturnType | undefined\n let readyState: ReadyState = CLOSED\n\n // Let's go!\n connect()\n\n return {\n close,\n connect,\n [Symbol.iterator]: () => {\n throw new Error(\n 'EventSource does not support synchronous iteration. Use `for await` instead.',\n )\n },\n [Symbol.asyncIterator]: getEventIterator,\n get lastEventId() {\n return lastEventId\n },\n get url() {\n return currentUrl\n },\n get readyState() {\n return readyState\n },\n }\n\n function connect() {\n if (request) {\n return\n }\n\n readyState = CONNECTING\n controller = new AbortController()\n request = fetch(url, getRequestOptions())\n .then(onFetchResponse)\n .catch((err: Error & {type: string}) => {\n request = null\n\n // We expect abort errors when the user manually calls `close()` - ignore those\n if (err.name === 'AbortError' || err.type === 'aborted' || controller.signal.aborted) {\n return\n }\n\n scheduleReconnect()\n })\n }\n\n function close() {\n readyState = CLOSED\n controller.abort()\n parser.reset()\n clearTimeout(reconnectTimer)\n onCloseSubscribers.forEach((fn) => fn())\n }\n\n function getEventIterator(): AsyncGenerator {\n const pullQueue: EventSourceAsyncValueResolver[] = []\n const pushQueue: EventSourceMessage[] = []\n\n function pullValue() {\n return new Promise>((resolve) => {\n const value = pushQueue.shift()\n if (value) {\n resolve({value, done: false})\n } else {\n pullQueue.push(resolve)\n }\n })\n }\n\n const pushValue = function (value: EventSourceMessage) {\n const resolve = pullQueue.shift()\n if (resolve) {\n resolve({value, done: false})\n } else {\n pushQueue.push(value)\n }\n }\n\n function unsubscribe() {\n subscribers.splice(subscribers.indexOf(pushValue), 1)\n while (pullQueue.shift()) {}\n while (pushQueue.shift()) {}\n }\n\n function onClose() {\n const resolve = pullQueue.shift()\n if (!resolve) {\n return\n }\n\n resolve({done: true, value: undefined})\n unsubscribe()\n }\n\n onCloseSubscribers.push(onClose)\n subscribers.push(pushValue)\n\n return {\n next() {\n return readyState === CLOSED ? this.return() : pullValue()\n },\n return() {\n unsubscribe()\n return Promise.resolve({done: true, value: undefined})\n },\n throw(error) {\n unsubscribe()\n return Promise.reject(error)\n },\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n function scheduleReconnect() {\n onScheduleReconnect({delay: reconnectMs})\n if (controller.signal.aborted) {\n return\n }\n readyState = CONNECTING\n reconnectTimer = setTimeout(connect, reconnectMs)\n }\n\n async function onFetchResponse(response: FetchLikeResponse) {\n onConnect()\n parser.reset()\n\n const {body, redirected, status} = response\n\n // HTTP 204 means \"close the connection, no more data will be sent\"\n if (status === 204) {\n onDisconnect()\n close()\n return\n }\n\n if (!body) {\n throw new Error('Missing response body')\n }\n\n if (redirected) {\n currentUrl = response.url\n }\n\n // Ensure that the response stream is a web stream\n // @todo Figure out a way to make this work without casting\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const stream = getStream(body as any)\n const decoder = new TextDecoder()\n\n const reader = stream.getReader()\n let open = true\n\n readyState = OPEN\n\n do {\n const {done, value} = await reader.read()\n if (value) {\n parser.feed(decoder.decode(value, {stream: !done}))\n }\n\n if (!done) {\n continue\n }\n\n open = false\n request = null\n parser.reset()\n\n // EventSources never close unless explicitly handled with `.close()`:\n // Implementors should send an `done`/`complete`/`disconnect` event and\n // explicitly handle it in client code, or send an HTTP 204.\n scheduleReconnect()\n\n // Calling scheduleReconnect() prior to onDisconnect() allows consumers to\n // explicitly call .close() before the reconnection is performed.\n onDisconnect()\n } while (open)\n }\n\n function onEvent(msg: EventSourceMessage) {\n if (typeof msg.id === 'string') {\n lastEventId = msg.id\n }\n\n emit(msg)\n }\n\n function onRetry(ms: number) {\n reconnectMs = ms\n }\n\n function getRequestOptions(): FetchLikeInit {\n // @todo allow interception of options, but don't allow overriding signal\n const {mode, credentials, body, method, redirect, referrer, referrerPolicy} = options\n const lastEvent = lastEventId ? {'Last-Event-ID': lastEventId} : undefined\n const headers = {Accept: 'text/event-stream', ...requestHeaders, ...lastEvent}\n return {\n mode,\n credentials,\n body,\n method,\n redirect,\n referrer,\n referrerPolicy,\n headers,\n cache: 'no-store',\n signal: controller.signal,\n }\n }\n}\n\nfunction validate(options: EventSourceOptions): {\n fetch: FetchLike\n url: string | URL\n initialLastEventId: string | undefined\n} {\n const fetch = options.fetch || globalThis.fetch\n if (!isFetchLike(fetch)) {\n throw new Error('No fetch implementation provided, and one was not found on the global object.')\n }\n\n if (typeof AbortController !== 'function') {\n throw new Error('Missing AbortController implementation')\n }\n\n const {url, initialLastEventId} = options\n\n if (typeof url !== 'string' && !(url instanceof URL)) {\n throw new Error('Invalid URL provided - must be string or URL instance')\n }\n\n if (typeof initialLastEventId !== 'string' && initialLastEventId !== undefined) {\n throw new Error('Invalid initialLastEventId provided - must be string or undefined')\n }\n\n return {fetch, url, initialLastEventId}\n}\n\n// This is obviously naive, but hard to probe for full compatibility\nfunction isFetchLike(fetch: FetchLike | typeof globalThis.fetch): fetch is FetchLike {\n return typeof fetch === 'function'\n}\n", "import type {EnvAbstractions} from './abstractions.js'\nimport {createEventSource as createSource} from './client.js'\nimport type {EventSourceClient, EventSourceOptions} from './types.js'\n\nexport * from './constants.js'\nexport * from './types.js'\n\n/**\n * Default \"abstractions\", eg when all the APIs are globally available\n */\nconst defaultAbstractions: EnvAbstractions = {\n getStream,\n}\n\n/**\n * Creates a new EventSource client.\n *\n * @param optionsOrUrl - Options for the client, or an URL/URL string.\n * @returns A new EventSource client instance\n * @public\n */\nexport function createEventSource(\n optionsOrUrl: EventSourceOptions | URL | string,\n): EventSourceClient {\n return createSource(optionsOrUrl, defaultAbstractions)\n}\n\n/**\n * Returns a ReadableStream (Web Stream) from either an existing ReadableStream.\n * Only defined because of environment abstractions - is actually a 1:1 (passthrough).\n *\n * @param body - The body to convert\n * @returns A ReadableStream\n * @private\n */\nfunction getStream(\n body: NodeJS.ReadableStream | ReadableStream,\n): ReadableStream {\n if (!(body instanceof ReadableStream)) {\n throw new Error('Invalid stream, expected a web ReadableStream')\n }\n\n return body\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n 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(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport createDebug, { Debugger } from 'debug'\r\n\r\nconst loggerLevels = [\r\n 'info',\r\n 'warn',\r\n 'error',\r\n 'debug',\r\n] as const\r\n\r\ntype LoggerLevels = typeof loggerLevels[number]\r\n\r\n/**\r\n * Logger class that provides colored logging functionality using the debug package.\r\n * Supports different log levels: info, warn, error, and debug.\r\n */\r\nexport class Logger {\r\n private loggers: { [K in LoggerLevels]: Debugger } = {} as any\r\n\r\n /**\r\n * Creates a new Logger instance with the specified namespace.\r\n * @param namespace The namespace to use for the logger\r\n */\r\n constructor (namespace: string = '') {\r\n this.initializeLoggers(namespace)\r\n }\r\n\r\n private initializeLoggers (namespace: string) {\r\n for (const level of loggerLevels) {\r\n const logger = createDebug(`${namespace}:${level}`)\r\n logger.color = this.getPlatformColor(level)\r\n this.loggers[level] = logger\r\n }\r\n }\r\n\r\n private getPlatformColor (level: LoggerLevels): string {\r\n const platform = typeof window !== 'undefined' ? 'browser' : 'node'\r\n const colors = {\r\n node: {\r\n info: '2', // Green\r\n warn: '3', // Yellow\r\n error: '1', // Red\r\n debug: '4', // Blue\r\n },\r\n browser: {\r\n info: '#33CC99', // Green\r\n warn: '#CCCC33', // Yellow\r\n error: '#CC3366', // Red\r\n debug: '#0066FF', // Blue\r\n },\r\n }\r\n\r\n return colors[platform][level]\r\n }\r\n\r\n /**\r\n * Logs an informational message.\r\n * @param message The message to log\r\n * @param args Additional arguments to include in the log\r\n */\r\n info (message: string, ...args: any[]) {\r\n this.loggers.info(message, ...args)\r\n }\r\n\r\n /**\r\n * Logs a warning message.\r\n * @param message The message to log\r\n * @param args Additional arguments to include in the log\r\n */\r\n warn (message: string, ...args: any[]) {\r\n this.loggers.warn(message, ...args)\r\n }\r\n\r\n /**\r\n * Logs an error message.\r\n * @param message The message to log\r\n * @param args Additional arguments to include in the log\r\n */\r\n error (message: string, ...args: any[]) {\r\n this.loggers.error(message, ...args)\r\n }\r\n\r\n /**\r\n * Logs a debug message.\r\n * @param message The message to log\r\n * @param args Additional arguments to include in the log\r\n */\r\n debug (message: string, ...args: any[]) {\r\n this.loggers.debug(message, ...args)\r\n }\r\n}\r\n\r\n/**\r\n * Creates a new Logger instance with the specified namespace.\r\n * @param namespace The namespace to use for the logger\r\n * @returns A new Logger instance\r\n */\r\nexport function debug (namespace: string): Logger {\r\n return new Logger(namespace)\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Strategy } from './strategy'\r\n\r\nexport interface PrebuiltBotStrategySettings {\r\n readonly host: URL;\r\n readonly identifier: string;\r\n}\r\n\r\nexport class PrebuiltBotStrategy implements Strategy {\r\n private readonly API_VERSION = '2022-03-01-preview'\r\n private baseURL: URL\r\n\r\n constructor (settings: PrebuiltBotStrategySettings) {\r\n const { identifier, host } = settings\r\n\r\n this.baseURL = new URL(\r\n `/copilotstudio/prebuilt/authenticated/bots/${identifier}`,\r\n host\r\n )\r\n this.baseURL.searchParams.append('api-version', this.API_VERSION)\r\n }\r\n\r\n public getConversationUrl (conversationId?: string): string {\r\n const conversationUrl = new URL(this.baseURL.href)\r\n conversationUrl.pathname = `${conversationUrl.pathname}/conversations`\r\n\r\n if (conversationId) {\r\n conversationUrl.pathname = `${conversationUrl.pathname}/${conversationId}`\r\n }\r\n\r\n return conversationUrl.href\r\n }\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Strategy } from './strategy'\r\n\r\nexport interface PublishedBotStrategySettings {\r\n readonly host: URL;\r\n readonly schema: string;\r\n}\r\n\r\nexport class PublishedBotStrategy implements Strategy {\r\n private readonly API_VERSION = '2022-03-01-preview'\r\n private baseURL: URL\r\n\r\n constructor (settings: PublishedBotStrategySettings) {\r\n const { schema, host } = settings\r\n\r\n this.baseURL = new URL(\r\n `/copilotstudio/dataverse-backed/authenticated/bots/${schema}`,\r\n host\r\n )\r\n this.baseURL.searchParams.append('api-version', this.API_VERSION)\r\n }\r\n\r\n public getConversationUrl (conversationId?: string): string {\r\n const conversationUrl = new URL(this.baseURL.href)\r\n conversationUrl.pathname = `${conversationUrl.pathname}/conversations`\r\n\r\n if (conversationId) {\r\n conversationUrl.pathname = `${conversationUrl.pathname}/${conversationId}`\r\n }\r\n\r\n return conversationUrl.href\r\n }\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { AgentType } from './agentType'\r\nimport { ConnectionSettings } from './connectionSettings'\r\nimport { debug } from '@microsoft/agents-activity/logger'\r\nimport { PowerPlatformCloud } from './powerPlatformCloud'\r\nimport { PrebuiltBotStrategy } from './strategies/prebuiltBotStrategy'\r\nimport { PublishedBotStrategy } from './strategies/publishedBotStrategy'\r\n\r\nconst logger = debug('copilot-studio:power-platform')\r\n\r\n/**\r\n * Generates the connection URL for Copilot Studio.\r\n * @param settings - The connection settings.\r\n * @param conversationId - Optional conversation ID.\r\n * @returns The connection URL.\r\n * @throws Will throw an error if required settings are missing or invalid.\r\n */\r\nexport function getCopilotStudioConnectionUrl (\r\n settings: ConnectionSettings,\r\n conversationId?: string\r\n): string {\r\n if (settings.directConnectUrl?.trim()) {\r\n logger.debug(`Using direct connection: ${settings.directConnectUrl}`)\r\n if (!isValidUri(settings.directConnectUrl)) {\r\n throw new Error('directConnectUrl must be a valid URL')\r\n }\r\n\r\n // FIX for Missing Tenant ID\r\n if (settings.directConnectUrl.toLowerCase().includes('tenants/00000000-0000-0000-0000-000000000000')) {\r\n logger.debug(`Direct connection cannot be used, forcing default settings flow. Tenant ID is missing in the URL: ${settings.directConnectUrl}`)\r\n // Direct connection cannot be used, ejecting and forcing the normal settings flow:\r\n return getCopilotStudioConnectionUrl({ ...settings, directConnectUrl: '' }, conversationId)\r\n }\r\n\r\n return createURL(settings.directConnectUrl, conversationId).href\r\n }\r\n\r\n const cloudSetting = settings.cloud ?? PowerPlatformCloud.Prod\r\n const agentType = settings.copilotAgentType ?? AgentType.Published\r\n\r\n logger.debug(`Using cloud setting: ${cloudSetting}`)\r\n logger.debug(`Using agent type: ${agentType}`)\r\n\r\n if (!settings.environmentId?.trim()) {\r\n throw new Error('EnvironmentId must be provided')\r\n }\r\n\r\n if (!settings.agentIdentifier?.trim()) {\r\n throw new Error('AgentIdentifier must be provided')\r\n }\r\n\r\n if (cloudSetting === PowerPlatformCloud.Other) {\r\n if (!settings.customPowerPlatformCloud?.trim()) {\r\n throw new Error('customPowerPlatformCloud must be provided when PowerPlatformCloud is Other')\r\n } else if (isValidUri(settings.customPowerPlatformCloud)) {\r\n logger.debug(`Using custom Power Platform cloud: ${settings.customPowerPlatformCloud}`)\r\n } else {\r\n throw new Error(\r\n 'customPowerPlatformCloud must be a valid URL'\r\n )\r\n }\r\n }\r\n\r\n const host = getEnvironmentEndpoint(cloudSetting, settings.environmentId, settings.customPowerPlatformCloud)\r\n\r\n const strategy = {\r\n [AgentType.Published]: () => new PublishedBotStrategy({\r\n host,\r\n schema: settings.agentIdentifier!,\r\n }),\r\n [AgentType.Prebuilt]: () => new PrebuiltBotStrategy({\r\n host,\r\n identifier: settings.agentIdentifier!,\r\n }),\r\n }[agentType]()\r\n\r\n const url = strategy.getConversationUrl(conversationId)\r\n logger.debug(`Generated Copilot Studio connection URL: ${url}`)\r\n return url\r\n}\r\n\r\n/**\r\n * Returns the Power Platform API Audience.\r\n * @param settings - Configuration Settings to use.\r\n * @param cloud - Optional Power Platform Cloud Hosting Agent.\r\n * @param cloudBaseAddress - Optional Power Platform API endpoint to use if Cloud is configured as \"other\".\r\n * @param directConnectUrl - Optional DirectConnection URL to a given Copilot Studio agent, if provided all other settings are ignored.\r\n * @returns The Power Platform Audience.\r\n * @throws Will throw an error if required settings are missing or invalid.\r\n */\r\nexport function getTokenAudience (\r\n settings?: ConnectionSettings,\r\n cloud: PowerPlatformCloud = PowerPlatformCloud.Unknown,\r\n cloudBaseAddress: string = '',\r\n directConnectUrl: string = ''): string {\r\n if (!directConnectUrl && !settings?.directConnectUrl) {\r\n if (cloud === PowerPlatformCloud.Other && !cloudBaseAddress) {\r\n throw new Error('cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other')\r\n }\r\n if (!settings && cloud === PowerPlatformCloud.Unknown) {\r\n throw new Error('Either settings or cloud must be provided')\r\n }\r\n if (settings && settings.cloud && settings.cloud !== PowerPlatformCloud.Unknown) {\r\n cloud = settings.cloud\r\n }\r\n if (cloud === PowerPlatformCloud.Other) {\r\n if (cloudBaseAddress && isValidUri(cloudBaseAddress)) {\r\n cloud = PowerPlatformCloud.Other\r\n } else if (settings?.customPowerPlatformCloud && isValidUri(settings!.customPowerPlatformCloud)) {\r\n cloud = PowerPlatformCloud.Other\r\n cloudBaseAddress = settings.customPowerPlatformCloud\r\n } else {\r\n throw new Error('Either CustomPowerPlatformCloud or cloudBaseAddress must be provided when PowerPlatformCloudCategory is Other')\r\n }\r\n }\r\n cloudBaseAddress ??= 'api.unknown.powerplatform.com'\r\n return `https://${getEndpointSuffix(cloud, cloudBaseAddress)}/.default`\r\n } else {\r\n if (!directConnectUrl) {\r\n directConnectUrl = settings?.directConnectUrl ?? ''\r\n }\r\n if (directConnectUrl && isValidUri(directConnectUrl)) {\r\n if (decodeCloudFromURI(new URL(directConnectUrl)) === PowerPlatformCloud.Unknown) {\r\n const cloudToTest: PowerPlatformCloud = settings?.cloud ?? cloud\r\n\r\n if (cloudToTest === PowerPlatformCloud.Other || cloudToTest === PowerPlatformCloud.Unknown) {\r\n throw new Error('Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.')\r\n }\r\n if ((cloudToTest as PowerPlatformCloud) !== PowerPlatformCloud.Unknown) {\r\n return `https://${getEndpointSuffix(cloudToTest, '')}/.default`\r\n } else {\r\n throw new Error('Unable to resolve the PowerPlatform Cloud from DirectConnectUrl. The Token Audience resolver requires a specific PowerPlatformCloudCategory.')\r\n }\r\n }\r\n return `https://${getEndpointSuffix(decodeCloudFromURI(new URL(directConnectUrl)), '')}/.default`\r\n } else {\r\n throw new Error('DirectConnectUrl must be provided when DirectConnectUrl is set')\r\n }\r\n }\r\n}\r\nfunction isValidUri (uri: string): boolean {\r\n try {\r\n const absoluteUrl = uri.startsWith('http') ? uri : `https://${uri}`\r\n const newUri = new URL(absoluteUrl)\r\n return !!newUri\r\n } catch {\r\n return false\r\n }\r\n}\r\n\r\nfunction createURL (base: string, conversationId?: string): URL {\r\n const url = new URL(base)\r\n\r\n if (!url.searchParams.has('api-version')) {\r\n url.searchParams.append('api-version', '2022-03-01-preview')\r\n }\r\n\r\n if (url.pathname.endsWith('/')) {\r\n url.pathname = url.pathname.slice(0, -1)\r\n }\r\n\r\n if (url.pathname.includes('/conversations')) {\r\n url.pathname = url.pathname.substring(0, url.pathname.indexOf('/conversations'))\r\n }\r\n\r\n url.pathname = `${url.pathname}/conversations`\r\n if (conversationId) {\r\n url.pathname = `${url.pathname}/${conversationId}`\r\n }\r\n\r\n return url\r\n}\r\n\r\nfunction getEnvironmentEndpoint (\r\n cloud: PowerPlatformCloud,\r\n environmentId: string,\r\n cloudBaseAddress?: string\r\n): URL {\r\n if (cloud === PowerPlatformCloud.Other && (!cloudBaseAddress || !cloudBaseAddress.trim())) {\r\n throw new Error('cloudBaseAddress must be provided when PowerPlatformCloud is Other')\r\n }\r\n\r\n cloudBaseAddress = cloudBaseAddress ?? 'api.unknown.powerplatform.com'\r\n\r\n const normalizedResourceId = environmentId.toLowerCase().replaceAll('-', '')\r\n const idSuffixLength = getIdSuffixLength(cloud)\r\n const hexPrefix = normalizedResourceId.substring(0, normalizedResourceId.length - idSuffixLength)\r\n const hexSuffix = normalizedResourceId.substring(normalizedResourceId.length - idSuffixLength)\r\n\r\n return new URL(`https://${hexPrefix}.${hexSuffix}.environment.${getEndpointSuffix(cloud, cloudBaseAddress)}`)\r\n}\r\n\r\nfunction getEndpointSuffix (\r\n category: PowerPlatformCloud,\r\n cloudBaseAddress: string\r\n): string {\r\n switch (category) {\r\n case PowerPlatformCloud.Local:\r\n return 'api.powerplatform.localhost'\r\n case PowerPlatformCloud.Exp:\r\n return 'api.exp.powerplatform.com'\r\n case PowerPlatformCloud.Dev:\r\n return 'api.dev.powerplatform.com'\r\n case PowerPlatformCloud.Prv:\r\n return 'api.prv.powerplatform.com'\r\n case PowerPlatformCloud.Test:\r\n return 'api.test.powerplatform.com'\r\n case PowerPlatformCloud.Preprod:\r\n return 'api.preprod.powerplatform.com'\r\n case PowerPlatformCloud.FirstRelease:\r\n case PowerPlatformCloud.Prod:\r\n return 'api.powerplatform.com'\r\n case PowerPlatformCloud.GovFR:\r\n return 'api.gov.powerplatform.microsoft.us'\r\n case PowerPlatformCloud.Gov:\r\n return 'api.gov.powerplatform.microsoft.us'\r\n case PowerPlatformCloud.High:\r\n return 'api.high.powerplatform.microsoft.us'\r\n case PowerPlatformCloud.DoD:\r\n return 'api.appsplatform.us'\r\n case PowerPlatformCloud.Mooncake:\r\n return 'api.powerplatform.partner.microsoftonline.cn'\r\n case PowerPlatformCloud.Ex:\r\n return 'api.powerplatform.eaglex.ic.gov'\r\n case PowerPlatformCloud.Rx:\r\n return 'api.powerplatform.microsoft.scloud'\r\n case PowerPlatformCloud.Other:\r\n return cloudBaseAddress\r\n default:\r\n throw new Error(`Invalid cluster category value: ${category}`)\r\n }\r\n}\r\n\r\nfunction getIdSuffixLength (cloud: PowerPlatformCloud): number {\r\n switch (cloud) {\r\n case PowerPlatformCloud.FirstRelease:\r\n case PowerPlatformCloud.Prod:\r\n return 2\r\n default:\r\n return 1\r\n }\r\n}\r\n\r\nfunction decodeCloudFromURI (uri: URL): PowerPlatformCloud {\r\n const host = uri.host.toLowerCase()\r\n\r\n switch (host) {\r\n case 'api.powerplatform.localhost':\r\n return PowerPlatformCloud.Local\r\n case 'api.exp.powerplatform.com':\r\n return PowerPlatformCloud.Exp\r\n case 'api.dev.powerplatform.com':\r\n return PowerPlatformCloud.Dev\r\n case 'api.prv.powerplatform.com':\r\n return PowerPlatformCloud.Prv\r\n case 'api.test.powerplatform.com':\r\n return PowerPlatformCloud.Test\r\n case 'api.preprod.powerplatform.com':\r\n return PowerPlatformCloud.Preprod\r\n case 'api.powerplatform.com':\r\n return PowerPlatformCloud.Prod\r\n case 'api.gov.powerplatform.microsoft.us':\r\n return PowerPlatformCloud.GovFR\r\n case 'api.high.powerplatform.microsoft.us':\r\n return PowerPlatformCloud.High\r\n case 'api.appsplatform.us':\r\n return PowerPlatformCloud.DoD\r\n case 'api.powerplatform.partner.microsoftonline.cn':\r\n return PowerPlatformCloud.Mooncake\r\n default:\r\n return PowerPlatformCloud.Unknown\r\n }\r\n}\r\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0;\nvar util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (exports.util = util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (exports.objectUtil = objectUtil = {}));\nexports.ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return exports.ZodParsedType.undefined;\n case \"string\":\n return exports.ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number;\n case \"boolean\":\n return exports.ZodParsedType.boolean;\n case \"function\":\n return exports.ZodParsedType.function;\n case \"bigint\":\n return exports.ZodParsedType.bigint;\n case \"symbol\":\n return exports.ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return exports.ZodParsedType.array;\n }\n if (data === null) {\n return exports.ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return exports.ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return exports.ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return exports.ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return exports.ZodParsedType.date;\n }\n return exports.ZodParsedType.object;\n default:\n return exports.ZodParsedType.unknown;\n }\n};\nexports.getParsedType = getParsedType;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0;\nconst util_js_1 = require(\"./helpers/util.cjs\");\nexports.ZodIssueCode = util_js_1.util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexports.quotelessJson = quotelessJson;\nclass ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nexports.ZodError = ZodError;\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ZodError_js_1 = require(\"../ZodError.cjs\");\nconst util_js_1 = require(\"../helpers/util.cjs\");\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodError_js_1.ZodIssueCode.invalid_type:\n if (issue.received === util_js_1.ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodError_js_1.ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`;\n break;\n case ZodError_js_1.ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util_js_1.util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodError_js_1.ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodError_js_1.ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodError_js_1.ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodError_js_1.ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodError_js_1.ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodError_js_1.ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util_js_1.util.assertNever(issue);\n }\n return { message };\n};\nexports.default = errorMap;\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultErrorMap = void 0;\nexports.setErrorMap = setErrorMap;\nexports.getErrorMap = getErrorMap;\nconst en_js_1 = __importDefault(require(\"./locales/en.cjs\"));\nexports.defaultErrorMap = en_js_1.default;\nlet overrideErrorMap = en_js_1.default;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n", "\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0;\nexports.addIssueToContext = addIssueToContext;\nconst errors_js_1 = require(\"../errors.cjs\");\nconst en_js_1 = __importDefault(require(\"../locales/en.cjs\"));\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexports.makeIssue = makeIssue;\nexports.EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = (0, errors_js_1.getErrorMap)();\n const issue = (0, exports.makeIssue)({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === en_js_1.default ? undefined : en_js_1.default, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return exports.INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return exports.INVALID;\n if (value.status === \"aborted\")\n return exports.INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexports.ParseStatus = ParseStatus;\nexports.INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nexports.DIRTY = DIRTY;\nconst OK = (value) => ({ status: \"valid\", value });\nexports.OK = OK;\nconst isAborted = (x) => x.status === \"aborted\";\nexports.isAborted = isAborted;\nconst isDirty = (x) => x.status === \"dirty\";\nexports.isDirty = isDirty;\nconst isValid = (x) => x.status === \"valid\";\nexports.isValid = isValid;\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\nexports.isAsync = isAsync;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.errorUtil = void 0;\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (exports.errorUtil = errorUtil = {}));\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0;\nexports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0;\nexports.datetimeRegex = datetimeRegex;\nexports.custom = custom;\nconst ZodError_js_1 = require(\"./ZodError.cjs\");\nconst errors_js_1 = require(\"./errors.cjs\");\nconst errorUtil_js_1 = require(\"./helpers/errorUtil.cjs\");\nconst parseUtil_js_1 = require(\"./helpers/parseUtil.cjs\");\nconst util_js_1 = require(\"./helpers/util.cjs\");\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if ((0, parseUtil_js_1.isValid)(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError_js_1.ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return (0, util_js_1.getParsedType)(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: (0, util_js_1.getParsedType)(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new parseUtil_js_1.ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: (0, util_js_1.getParsedType)(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if ((0, parseUtil_js_1.isAsync)(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: (0, util_js_1.getParsedType)(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: (0, util_js_1.getParsedType)(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return (0, parseUtil_js_1.isValid)(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: (0, util_js_1.getParsedType)(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodError_js_1.ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nexports.ZodType = ZodType;\nexports.Schema = ZodType;\nexports.ZodSchema = ZodType;\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst 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;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst 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)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((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}))\\])|(\\[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})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst 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])$/;\nconst 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])$/;\n// const ipv6Regex =\n// /^(([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})))$/;\nconst 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]))$/;\nconst 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])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst 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])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.string,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const status = new parseUtil_js_1.ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"email\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"emoji\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"uuid\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"nanoid\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"cuid\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"cuid2\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"ulid\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"url\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"regex\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"duration\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"ip\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"jwt\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"cidr\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"base64\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n validation: \"base64url\",\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util_js_1.util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodError_js_1.ZodIssueCode.invalid_string,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil_js_1.errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil_js_1.errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil_js_1.errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil_js_1.errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil_js_1.errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil_js_1.errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil_js_1.errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil_js_1.errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil_js_1.errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nexports.ZodString = ZodString;\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.number,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n let ctx = undefined;\n const status = new parseUtil_js_1.ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util_js_1.util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util_js_1.util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil_js_1.errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil_js_1.errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil_js_1.errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil_js_1.errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil_js_1.errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil_js_1.errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util_js_1.util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nexports.ZodNumber = ZodNumber;\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new parseUtil_js_1.ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util_js_1.util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil_js_1.errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil_js_1.errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil_js_1.errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil_js_1.errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil_js_1.errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nexports.ZodBigInt = ZodBigInt;\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodBoolean = ZodBoolean;\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.date,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_date,\n });\n return parseUtil_js_1.INVALID;\n }\n const status = new parseUtil_js_1.ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util_js_1.util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil_js_1.errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nexports.ZodDate = ZodDate;\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodSymbol = ZodSymbol;\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodUndefined = ZodUndefined;\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.null,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodNull = ZodNull;\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodAny = ZodAny;\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodUnknown = ZodUnknown;\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.never,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n}\nexports.ZodNever = ZodNever;\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.void,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n}\nexports.ZodVoid = ZodVoid;\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== util_js_1.ZodParsedType.array) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.array,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return parseUtil_js_1.ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return parseUtil_js_1.ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nexports.ZodArray = ZodArray;\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util_js_1.util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.object,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil_js_1.errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util_js_1.util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util_js_1.util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util_js_1.util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util_js_1.util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util_js_1.util.objectKeys(this.shape));\n }\n}\nexports.ZodObject = ZodObject;\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues));\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_union,\n unionErrors,\n });\n return parseUtil_js_1.INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError_js_1.ZodError(issues));\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_union,\n unionErrors,\n });\n return parseUtil_js_1.INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nexports.ZodUnion = ZodUnion;\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util_js_1.util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.object) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.object,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return parseUtil_js_1.INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nexports.ZodDiscriminatedUnion = ZodDiscriminatedUnion;\nfunction mergeValues(a, b) {\n const aType = (0, util_js_1.getParsedType)(a);\n const bType = (0, util_js_1.getParsedType)(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) {\n const bKeys = util_js_1.util.objectKeys(b);\n const sharedKeys = util_js_1.util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) {\n return parseUtil_js_1.INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_intersection_types,\n });\n return parseUtil_js_1.INVALID;\n }\n if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nexports.ZodIntersection = ZodIntersection;\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.array) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.array,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return parseUtil_js_1.INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return parseUtil_js_1.ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return parseUtil_js_1.ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nexports.ZodTuple = ZodTuple;\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.object) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.object,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexports.ZodRecord = ZodRecord;\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.map) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.map,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return parseUtil_js_1.INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return parseUtil_js_1.INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nexports.ZodMap = ZodMap;\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.set) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.set,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil_js_1.errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nexports.ZodSet = ZodSet;\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.function) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.function,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n function makeArgsIssue(args, error) {\n return (0, parseUtil_js_1.makeIssue)({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodError_js_1.ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return (0, parseUtil_js_1.makeIssue)({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodError_js_1.ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return (0, parseUtil_js_1.OK)(async function (...args) {\n const error = new ZodError_js_1.ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return (0, parseUtil_js_1.OK)(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexports.ZodFunction = ZodFunction;\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nexports.ZodLazy = ZodLazy;\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n received: ctx.data,\n code: ZodError_js_1.ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return parseUtil_js_1.INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nexports.ZodLiteral = ZodLiteral;\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n expected: util_js_1.util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n });\n return parseUtil_js_1.INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n received: ctx.data,\n code: ZodError_js_1.ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nexports.ZodEnum = ZodEnum;\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) {\n const expectedValues = util_js_1.util.objectValues(nativeEnumValues);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n expected: util_js_1.util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n });\n return parseUtil_js_1.INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util_js_1.util.objectValues(nativeEnumValues);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n received: ctx.data,\n code: ZodError_js_1.ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return parseUtil_js_1.INVALID;\n }\n return (0, parseUtil_js_1.OK)(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nexports.ZodNativeEnum = ZodNativeEnum;\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) {\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return (0, parseUtil_js_1.OK)(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nexports.ZodPromise = ZodPromise;\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n (0, parseUtil_js_1.addIssueToContext)(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return parseUtil_js_1.INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (result.status === \"dirty\")\n return (0, parseUtil_js_1.DIRTY)(result.value);\n if (status.value === \"dirty\")\n return (0, parseUtil_js_1.DIRTY)(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return parseUtil_js_1.INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (result.status === \"dirty\")\n return (0, parseUtil_js_1.DIRTY)(result.value);\n if (status.value === \"dirty\")\n return (0, parseUtil_js_1.DIRTY)(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!(0, parseUtil_js_1.isValid)(base))\n return parseUtil_js_1.INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!(0, parseUtil_js_1.isValid)(base))\n return parseUtil_js_1.INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util_js_1.util.assertNever(effect);\n }\n}\nexports.ZodEffects = ZodEffects;\nexports.ZodTransformer = ZodEffects;\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === util_js_1.ZodParsedType.undefined) {\n return (0, parseUtil_js_1.OK)(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nexports.ZodOptional = ZodOptional;\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === util_js_1.ZodParsedType.null) {\n return (0, parseUtil_js_1.OK)(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nexports.ZodNullable = ZodNullable;\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === util_js_1.ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nexports.ZodDefault = ZodDefault;\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if ((0, parseUtil_js_1.isAsync)(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError_js_1.ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError_js_1.ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nexports.ZodCatch = ZodCatch;\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== util_js_1.ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n (0, parseUtil_js_1.addIssueToContext)(ctx, {\n code: ZodError_js_1.ZodIssueCode.invalid_type,\n expected: util_js_1.ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return parseUtil_js_1.INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nexports.ZodNaN = ZodNaN;\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexports.BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexports.ZodBranded = ZodBranded;\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return (0, parseUtil_js_1.DIRTY)(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return parseUtil_js_1.INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexports.ZodPipeline = ZodPipeline;\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if ((0, parseUtil_js_1.isValid)(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nexports.ZodReadonly = ZodReadonly;\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nfunction custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexports.late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nexports.instanceof = instanceOfType;\nconst stringType = ZodString.create;\nexports.string = stringType;\nconst numberType = ZodNumber.create;\nexports.number = numberType;\nconst nanType = ZodNaN.create;\nexports.nan = nanType;\nconst bigIntType = ZodBigInt.create;\nexports.bigint = bigIntType;\nconst booleanType = ZodBoolean.create;\nexports.boolean = booleanType;\nconst dateType = ZodDate.create;\nexports.date = dateType;\nconst symbolType = ZodSymbol.create;\nexports.symbol = symbolType;\nconst undefinedType = ZodUndefined.create;\nexports.undefined = undefinedType;\nconst nullType = ZodNull.create;\nexports.null = nullType;\nconst anyType = ZodAny.create;\nexports.any = anyType;\nconst unknownType = ZodUnknown.create;\nexports.unknown = unknownType;\nconst neverType = ZodNever.create;\nexports.never = neverType;\nconst voidType = ZodVoid.create;\nexports.void = voidType;\nconst arrayType = ZodArray.create;\nexports.array = arrayType;\nconst objectType = ZodObject.create;\nexports.object = objectType;\nconst strictObjectType = ZodObject.strictCreate;\nexports.strictObject = strictObjectType;\nconst unionType = ZodUnion.create;\nexports.union = unionType;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nexports.discriminatedUnion = discriminatedUnionType;\nconst intersectionType = ZodIntersection.create;\nexports.intersection = intersectionType;\nconst tupleType = ZodTuple.create;\nexports.tuple = tupleType;\nconst recordType = ZodRecord.create;\nexports.record = recordType;\nconst mapType = ZodMap.create;\nexports.map = mapType;\nconst setType = ZodSet.create;\nexports.set = setType;\nconst functionType = ZodFunction.create;\nexports.function = functionType;\nconst lazyType = ZodLazy.create;\nexports.lazy = lazyType;\nconst literalType = ZodLiteral.create;\nexports.literal = literalType;\nconst enumType = ZodEnum.create;\nexports.enum = enumType;\nconst nativeEnumType = ZodNativeEnum.create;\nexports.nativeEnum = nativeEnumType;\nconst promiseType = ZodPromise.create;\nexports.promise = promiseType;\nconst effectsType = ZodEffects.create;\nexports.effect = effectsType;\nexports.transformer = effectsType;\nconst optionalType = ZodOptional.create;\nexports.optional = optionalType;\nconst nullableType = ZodNullable.create;\nexports.nullable = nullableType;\nconst preprocessType = ZodEffects.createWithPreprocess;\nexports.preprocess = preprocessType;\nconst pipelineType = ZodPipeline.create;\nexports.pipeline = pipelineType;\nconst ostring = () => stringType().optional();\nexports.ostring = ostring;\nconst onumber = () => numberType().optional();\nexports.onumber = onumber;\nconst oboolean = () => booleanType().optional();\nexports.oboolean = oboolean;\nexports.coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexports.NEVER = parseUtil_js_1.INVALID;\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./errors.cjs\"), exports);\n__exportStar(require(\"./helpers/parseUtil.cjs\"), exports);\n__exportStar(require(\"./helpers/typeAliases.cjs\"), exports);\n__exportStar(require(\"./helpers/util.cjs\"), exports);\n__exportStar(require(\"./types.cjs\"), exports);\n__exportStar(require(\"./ZodError.cjs\"), exports);\n", "\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.z = void 0;\nconst z = __importStar(require(\"./v3/external.cjs\"));\nexports.z = z;\n__exportStar(require(\"./v3/external.cjs\"), exports);\nexports.default = z;\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing the types of actions.\r\n */\r\nexport enum ActionTypes {\r\n /**\r\n * Opens a URL in the default browser.\r\n */\r\n OpenUrl = 'openUrl',\r\n\r\n /**\r\n * Sends a message back to the bot as a simple string.\r\n */\r\n ImBack = 'imBack',\r\n\r\n /**\r\n * Sends a message back to the bot with additional data.\r\n */\r\n PostBack = 'postBack',\r\n\r\n /**\r\n * Plays an audio file.\r\n */\r\n PlayAudio = 'playAudio',\r\n\r\n /**\r\n * Plays a video file.\r\n */\r\n PlayVideo = 'playVideo',\r\n\r\n /**\r\n * Displays an image.\r\n */\r\n ShowImage = 'showImage',\r\n\r\n /**\r\n * Downloads a file.\r\n */\r\n DownloadFile = 'downloadFile',\r\n\r\n /**\r\n * Initiates a sign-in process.\r\n */\r\n Signin = 'signin',\r\n\r\n /**\r\n * Initiates a phone call.\r\n */\r\n Call = 'call',\r\n\r\n /**\r\n * Sends a message back to the bot with additional metadata.\r\n */\r\n MessageBack = 'messageBack',\r\n\r\n /**\r\n * Opens an application.\r\n */\r\n OpenApp = 'openApp',\r\n}\r\n\r\n/**\r\n * Zod schema for validating ActionTypes.\r\n */\r\nexport const actionTypesZodSchema = z.enum(['openUrl', 'imBack', 'postBack', 'playAudio', 'showImage', 'downloadFile', 'signin', 'call', 'messageBack', 'openApp'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing the state types of a semantic action.\r\n */\r\nexport enum SemanticActionStateTypes {\r\n /**\r\n * Indicates the start of a semantic action.\r\n */\r\n Start = 'start',\r\n\r\n /**\r\n * Indicates the continuation of a semantic action.\r\n */\r\n Continue = 'continue',\r\n\r\n /**\r\n * Indicates the completion of a semantic action.\r\n */\r\n Done = 'done',\r\n}\r\n\r\n/**\r\n * Zod schema for validating SemanticActionStateTypes.\r\n */\r\nexport const semanticActionStateTypesZodSchema = z.enum(['start', 'continue', 'done'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing the layout types for attachments.\r\n */\r\nexport enum AttachmentLayoutTypes {\r\n /**\r\n * Displays attachments in a list format.\r\n */\r\n List = 'list',\r\n\r\n /**\r\n * Displays attachments in a carousel format.\r\n */\r\n Carousel = 'carousel',\r\n}\r\n\r\n/**\r\n * Zod schema for validating attachment layout types.\r\n */\r\nexport const attachmentLayoutTypesZodSchema = z.enum(['list', 'carousel'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Enum representing the different channels an agent can communicate through.\r\n */\r\nexport enum Channels {\r\n /**\r\n * Represents the Alexa channel.\r\n */\r\n Alexa = 'alexa',\r\n\r\n /**\r\n * Represents the Console channel.\r\n */\r\n Console = 'console',\r\n\r\n /**\r\n * Represents the Directline channel.\r\n */\r\n Directline = 'directline',\r\n\r\n /**\r\n * Represents the Directline Speech channel.\r\n */\r\n DirectlineSpeech = 'directlinespeech',\r\n\r\n /**\r\n * Represents the Email channel.\r\n */\r\n Email = 'email',\r\n\r\n /**\r\n * Represents the Emulator channel.\r\n */\r\n Emulator = 'emulator',\r\n\r\n /**\r\n * Represents the Facebook channel.\r\n */\r\n Facebook = 'facebook',\r\n\r\n /**\r\n * Represents the GroupMe channel.\r\n */\r\n Groupme = 'groupme',\r\n\r\n /**\r\n * Represents the Line channel.\r\n */\r\n Line = 'line',\r\n\r\n /**\r\n * Represents the Microsoft Teams channel.\r\n */\r\n Msteams = 'msteams',\r\n\r\n /**\r\n * Represents the Omnichannel.\r\n */\r\n Omni = 'omnichannel',\r\n\r\n /**\r\n * Represents the Outlook channel.\r\n */\r\n Outlook = 'outlook',\r\n\r\n /**\r\n * Represents the Skype channel.\r\n */\r\n Skype = 'skype',\r\n\r\n /**\r\n * Represents the Slack channel.\r\n */\r\n Slack = 'slack',\r\n\r\n /**\r\n * Represents the SMS channel.\r\n */\r\n Sms = 'sms',\r\n\r\n /**\r\n * Represents the Telegram channel.\r\n */\r\n Telegram = 'telegram',\r\n\r\n /**\r\n * Represents the Telephony channel.\r\n */\r\n Telephony = 'telephony',\r\n\r\n /**\r\n * Represents the Test channel.\r\n */\r\n Test = 'test',\r\n\r\n /**\r\n * Represents the Webchat channel.\r\n */\r\n Webchat = 'webchat',\r\n}\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing the different end of conversation codes.\r\n */\r\nexport enum EndOfConversationCodes {\r\n /**\r\n * The end of conversation reason is unknown.\r\n */\r\n Unknown = 'unknown',\r\n\r\n /**\r\n * The conversation completed successfully.\r\n */\r\n CompletedSuccessfully = 'completedSuccessfully',\r\n\r\n /**\r\n * The user cancelled the conversation.\r\n */\r\n UserCancelled = 'userCancelled',\r\n\r\n /**\r\n * The agent timed out during the conversation.\r\n */\r\n AgentTimedOut = 'agentTimedOut',\r\n\r\n /**\r\n * The agent issued an invalid message.\r\n */\r\n AgentIssuedInvalidMessage = 'agentIssuedInvalidMessage',\r\n\r\n /**\r\n * The channel failed during the conversation.\r\n */\r\n ChannelFailed = 'channelFailed',\r\n}\r\n\r\n/**\r\n * Zod schema for validating end of conversation codes.\r\n */\r\nexport const endOfConversationCodesZodSchema = z.enum(['unknown', 'completedSuccessfully', 'userCancelled', 'agentTimedOut', 'agentIssuedInvalidMessage', 'channelFailed'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum defining the type of roster the user is a member of.\r\n */\r\nexport enum MembershipSourceTypes {\r\n /**\r\n * The source is that of a channel and the user is a member of that channel.\r\n */\r\n Channel = 'channel',\r\n\r\n /**\r\n * The source is that of a team and the user is a member of that team.\r\n */\r\n Team = 'team',\r\n}\r\n\r\n/**\r\n * Zod schema for validating membership source types.\r\n */\r\nexport const membershipSourceTypeZodSchema = z.enum(['channel', 'team'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum expressing the users relationship to the current channel.\r\n */\r\nexport enum MembershipTypes {\r\n /**\r\n * The user is a direct member of a channel.\r\n */\r\n Direct = 'direct',\r\n\r\n /**\r\n * The user is a member of a channel through a group.\r\n */\r\n Transitive = 'transitive',\r\n}\r\n\r\n/**\r\n * Zod schema for validating membership source types.\r\n */\r\nexport const membershipTypeZodSchema = z.enum(['direct', 'transitive'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing the different role types in a conversation.\r\n */\r\nexport enum RoleTypes {\r\n /**\r\n * Represents a user in the conversation.\r\n */\r\n User = 'user',\r\n\r\n /**\r\n * Represents an agent or bot in the conversation.\r\n */\r\n Agent = 'bot',\r\n\r\n /**\r\n * Represents a skill in the conversation.\r\n */\r\n Skill = 'skill',\r\n}\r\n\r\n/**\r\n * Zod schema for validating role types.\r\n */\r\nexport const roleTypeZodSchema = z.enum(['user', 'bot', 'skill'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Activity } from '../activity'\r\nimport { Entity } from './entity'\r\n\r\n/**\r\n * Supported icon names for client citations. These icons are displayed in Teams to help users\r\n * identify the type of content being referenced in AI-generated responses.\r\n */\r\nexport type ClientCitationIconName =\r\n /** Microsoft Word document icon */\r\n | 'Microsoft Word'\r\n /** Microsoft Excel spreadsheet icon */\r\n | 'Microsoft Excel'\r\n /** Microsoft PowerPoint presentation icon */\r\n | 'Microsoft PowerPoint'\r\n /** Microsoft OneNote notebook icon */\r\n | 'Microsoft OneNote'\r\n /** Microsoft SharePoint site or document icon */\r\n | 'Microsoft SharePoint'\r\n /** Microsoft Visio diagram icon */\r\n | 'Microsoft Visio'\r\n /** Microsoft Loop component icon */\r\n | 'Microsoft Loop'\r\n /** Microsoft Whiteboard icon */\r\n | 'Microsoft Whiteboard'\r\n /** Adobe Illustrator vector graphics icon */\r\n | 'Adobe Illustrator'\r\n /** Adobe Photoshop image editing icon */\r\n | 'Adobe Photoshop'\r\n /** Adobe InDesign layout design icon */\r\n | 'Adobe InDesign'\r\n /** Adobe Flash multimedia icon */\r\n | 'Adobe Flash'\r\n /** Sketch design tool icon */\r\n | 'Sketch'\r\n /** Source code file icon */\r\n | 'Source Code'\r\n /** Generic image file icon */\r\n | 'Image'\r\n /** Animated GIF image icon */\r\n | 'GIF'\r\n /** Video file icon */\r\n | 'Video'\r\n /** Audio/sound file icon */\r\n | 'Sound'\r\n /** ZIP archive file icon */\r\n | 'ZIP'\r\n /** Plain text file icon */\r\n | 'Text'\r\n /** PDF document icon */\r\n | 'PDF'\r\n\r\n/**\r\n * Represents a Teams client citation to be included in a message.\r\n *\r\n * @remarks\r\n * [Learn more about Bot messages with AI-generated content](https://learn.microsoft.com/microsoftteams/platform/bots/how-to/bot-messages-ai-generated-content?tabs=before%2Cbotmessage)\r\n */\r\nexport interface ClientCitation {\r\n /**\r\n * Required; must be \"Claim\"\r\n */\r\n '@type': 'Claim';\r\n\r\n /**\r\n * Required. Number and position of the citation.\r\n */\r\n position: number;\r\n /**\r\n * Optional; if provided, the citation will be displayed in the message.\r\n */\r\n appearance: {\r\n /**\r\n * Required; Must be 'DigitalDocument'\r\n */\r\n '@type': 'DigitalDocument';\r\n\r\n /**\r\n * Name of the document. (max length 80)\r\n */\r\n name: string;\r\n\r\n /**\r\n * Stringified adaptive card with additional information about the citation.\r\n * It is rendered within the modal.\r\n */\r\n text?: string;\r\n\r\n /**\r\n * URL of the document. This will make the name of the citation clickable and direct the user to the specified URL.\r\n */\r\n url?: string;\r\n\r\n /**\r\n * Extract of the referenced content. (max length 160)\r\n */\r\n abstract: string;\r\n\r\n /**\r\n * Encoding format of the `citation.appearance.text` field.\r\n */\r\n encodingFormat?: 'application/vnd.microsoft.card.adaptive';\r\n\r\n /**\r\n * Information about the citation\u2019s icon.\r\n */\r\n image?: {\r\n '@type': 'ImageObject';\r\n\r\n /**\r\n * The image/icon name\r\n */\r\n name: ClientCitationIconName;\r\n };\r\n\r\n /**\r\n * Optional; set by developer. (max length 3) (max keyword length 28)\r\n */\r\n keywords?: string[];\r\n\r\n /**\r\n * Optional sensitivity content information.\r\n */\r\n usageInfo?: SensitivityUsageInfo;\r\n };\r\n}\r\n\r\n/**\r\n * Sensitivity usage info for content sent to the user.\r\n *\r\n * @remarks\r\n * This is used to provide information about the content to the user. See {@link ClientCitation} for more information.\r\n */\r\nexport interface SensitivityUsageInfo {\r\n /**\r\n * Must be \"https://schema.org/Message\"\r\n */\r\n type: 'https://schema.org/Message';\r\n\r\n /**\r\n * Required; Set to CreativeWork;\r\n */\r\n '@type': 'CreativeWork';\r\n\r\n /**\r\n * Sensitivity description of the content\r\n */\r\n description?: string;\r\n\r\n /**\r\n * Sensitivity title of the content\r\n */\r\n name: string;\r\n\r\n /**\r\n * Optional; ignored in Teams.\r\n */\r\n position?: number;\r\n\r\n /**\r\n * Optional; if provided, the content is considered sensitive and should be handled accordingly.\r\n */\r\n pattern?: {\r\n /**\r\n * Set to DefinedTerm\r\n */\r\n '@type': 'DefinedTerm';\r\n\r\n inDefinedTermSet: string;\r\n\r\n /**\r\n * Color\r\n */\r\n name: string;\r\n\r\n /**\r\n * e.g. #454545\r\n */\r\n termCode: string;\r\n };\r\n}\r\n\r\nexport interface AIEntity extends Entity {\r\n /**\r\n * Required as 'https://schema.org/Message'\r\n */\r\n type: 'https://schema.org/Message';\r\n\r\n /**\r\n * Required as 'Message\r\n */\r\n '@type': 'Message';\r\n\r\n /**\r\n * Required as 'https://schema.org\r\n */\r\n '@context': 'https://schema.org';\r\n\r\n /**\r\n * Must be left blank. This is for Bot Framework schema.\r\n */\r\n '@id': '';\r\n\r\n /**\r\n * Indicate that the content was generated by AI.\r\n */\r\n additionalType: ['AIGeneratedContent'];\r\n\r\n /**\r\n * Optional; if citations object is included, the sent activity will include the citations, referenced in the activity text.\r\n */\r\n citation?: ClientCitation[];\r\n\r\n /**\r\n * Optional; if usage_info object is included, the sent activity will include the sensitivity usage information.\r\n */\r\n usageInfo?: SensitivityUsageInfo;\r\n}\r\n\r\n/**\r\n * Adds an AI entity to an activity to indicate that the content was generated by AI.\r\n *\r\n * @param activity - The activity to which the AI entity will be added. The activity's entities array will be initialized if it doesn't exist.\r\n * @param citations - Optional array of client citations to include with the AI-generated content.\r\n * Citations provide references to sources used in generating the content and are displayed in Teams.\r\n * @param usageInfo - Optional sensitivity usage information that provides context about the content's sensitivity level.\r\n * This helps users understand any special handling requirements for the content.\r\n *\r\n * @remarks\r\n * This function enhances the activity with metadata that helps clients (like Microsoft Teams)\r\n * understand that the content is AI-generated and optionally includes citations and sensitivity information.\r\n *\r\n * @example\r\n * ```typescript\r\n * import { Activity } from '../activity';\r\n * import { addAIToActivity, ClientCitation } from './AIEntity';\r\n *\r\n * const activity: Activity = {\r\n * type: 'message',\r\n * text: 'Based on the documents, here are the key findings...'\r\n * };\r\n *\r\n * const citations: ClientCitation[] = [{\r\n * '@type': 'Claim',\r\n * position: 1,\r\n * appearance: {\r\n * '@type': 'DigitalDocument',\r\n * name: 'Research Report 2024',\r\n * abstract: 'Key findings from the annual research report',\r\n * url: 'https://example.com/report.pdf',\r\n * image: {\r\n * '@type': 'ImageObject',\r\n * name: 'PDF'\r\n * }\r\n * }\r\n * }];\r\n *\r\n * // Add AI entity with citations\r\n * addAIToActivity(activity, citations);\r\n * ```\r\n */\r\nexport const addAIToActivity = (\r\n activity: Activity,\r\n citations?: ClientCitation[],\r\n usageInfo?: SensitivityUsageInfo\r\n): void => {\r\n const aiEntity: AIEntity = {\r\n type: 'https://schema.org/Message',\r\n '@type': 'Message',\r\n '@context': 'https://schema.org',\r\n '@id': '',\r\n additionalType: ['AIGeneratedContent'],\r\n citation: citations,\r\n usageInfo\r\n }\r\n activity.entities ??= []\r\n activity.entities.push(aiEntity)\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Represents an adaptive card invoke action.\r\n */\r\nexport interface AdaptiveCardInvokeAction {\r\n /**\r\n * The type of the action.\r\n */\r\n type: string\r\n /**\r\n * The unique identifier of the action.\r\n */\r\n id?: string\r\n /**\r\n * The verb associated with the action.\r\n */\r\n verb: string\r\n /**\r\n * Additional data associated with the action.\r\n */\r\n data: Record\r\n}\r\n\r\n/**\r\n * Zod schema for validating an adaptive card invoke action.\r\n */\r\nexport const adaptiveCardInvokeActionZodSchema = z.object({\r\n type: z.string().min(1),\r\n id: z.string().optional(),\r\n verb: z.string().min(1),\r\n data: z.record(z.string().min(1), z.any())\r\n})\r\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = 'ffffffff-ffff-ffff-ffff-ffffffffffff';\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = '00000000-0000-0000-0000-000000000000';\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst regex_js_1 = require(\"./regex.js\");\nfunction validate(uuid) {\n return typeof uuid === 'string' && regex_js_1.default.test(uuid);\n}\nexports.default = validate;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_js_1 = require(\"./validate.js\");\nfunction parse(uuid) {\n if (!(0, validate_js_1.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff);\n}\nexports.default = parse;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.unsafeStringify = void 0;\nconst validate_js_1 = require(\"./validate.js\");\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nfunction unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nexports.unsafeStringify = unsafeStringify;\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!(0, validate_js_1.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexports.default = stringify;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nfunction rng() {\n if (!getRandomValues) {\n if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n getRandomValues = crypto.getRandomValues.bind(crypto);\n }\n return getRandomValues(rnds8);\n}\nexports.default = rng;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.updateV1State = void 0;\nconst rng_js_1 = require(\"./rng.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nconst _state = {};\nfunction v1(options, buf, offset) {\n let bytes;\n const isV6 = options?._v6 ?? false;\n if (options) {\n const optionsKeys = Object.keys(options);\n if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') {\n options = undefined;\n }\n }\n if (options) {\n bytes = v1Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset);\n }\n else {\n const now = Date.now();\n const rnds = (0, rng_js_1.default)();\n updateV1State(_state, now, rnds);\n bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset);\n }\n return buf ?? (0, stringify_js_1.unsafeStringify)(bytes);\n}\nfunction updateV1State(state, now, rnds) {\n state.msecs ??= -Infinity;\n state.nsecs ??= 0;\n if (now === state.msecs) {\n state.nsecs++;\n if (state.nsecs >= 10000) {\n state.node = undefined;\n state.nsecs = 0;\n }\n }\n else if (now > state.msecs) {\n state.nsecs = 0;\n }\n else if (now < state.msecs) {\n state.node = undefined;\n }\n if (!state.node) {\n state.node = rnds.slice(10, 16);\n state.node[0] |= 0x01;\n state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff;\n }\n state.msecs = now;\n return state;\n}\nexports.updateV1State = updateV1State;\nfunction v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n if (!buf) {\n buf = new Uint8Array(16);\n offset = 0;\n }\n else {\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n }\n msecs ??= Date.now();\n nsecs ??= 0;\n clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff;\n node ??= rnds.slice(10, 16);\n msecs += 12219292800000;\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n buf[offset++] = (tl >>> 24) & 0xff;\n buf[offset++] = (tl >>> 16) & 0xff;\n buf[offset++] = (tl >>> 8) & 0xff;\n buf[offset++] = tl & 0xff;\n const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff;\n buf[offset++] = (tmh >>> 8) & 0xff;\n buf[offset++] = tmh & 0xff;\n buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10;\n buf[offset++] = (tmh >>> 16) & 0xff;\n buf[offset++] = (clockseq >>> 8) | 0x80;\n buf[offset++] = clockseq & 0xff;\n for (let n = 0; n < 6; ++n) {\n buf[offset++] = node[n];\n }\n return buf;\n}\nexports.default = v1;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst parse_js_1 = require(\"./parse.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nfunction v1ToV6(uuid) {\n const v1Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid;\n const v6Bytes = _v1ToV6(v1Bytes);\n return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v6Bytes) : v6Bytes;\n}\nexports.default = v1ToV6;\nfunction _v1ToV6(v1Bytes) {\n return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]);\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction md5(bytes) {\n const words = uint8ToUint32(bytes);\n const md5Bytes = wordsToMd5(words, bytes.length * 8);\n return uint32ToUint8(md5Bytes);\n}\nfunction uint32ToUint8(input) {\n const bytes = new Uint8Array(input.length * 4);\n for (let i = 0; i < input.length * 4; i++) {\n bytes[i] = (input[i >> 2] >>> ((i % 4) * 8)) & 0xff;\n }\n return bytes;\n}\nfunction getOutputLength(inputLength8) {\n return (((inputLength8 + 64) >>> 9) << 4) + 14 + 1;\n}\nfunction wordsToMd5(x, len) {\n const xpad = new Uint32Array(getOutputLength(len)).fill(0);\n xpad.set(x);\n xpad[len >> 5] |= 0x80 << len % 32;\n xpad[xpad.length - 1] = len;\n x = xpad;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n for (let i = 0; i < x.length; i += 16) {\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n return Uint32Array.of(a, b, c, d);\n}\nfunction uint8ToUint32(input) {\n if (input.length === 0) {\n return new Uint32Array();\n }\n const output = new Uint32Array(getOutputLength(input.length * 8)).fill(0);\n for (let i = 0; i < input.length; i++) {\n output[i >> 2] |= (input[i] & 0xff) << ((i % 4) * 8);\n }\n return output;\n}\nfunction safeAdd(x, y) {\n const lsw = (x & 0xffff) + (y & 0xffff);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xffff);\n}\nfunction bitRotateLeft(num, cnt) {\n return (num << cnt) | (num >>> (32 - cnt));\n}\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn((b & c) | (~b & d), a, b, x, s, t);\n}\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn((b & d) | (c & ~d), a, b, x, s, t);\n}\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\nexports.default = md5;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URL = exports.DNS = exports.stringToBytes = void 0;\nconst parse_js_1 = require(\"./parse.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str));\n const bytes = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i) {\n bytes[i] = str.charCodeAt(i);\n }\n return bytes;\n}\nexports.stringToBytes = stringToBytes;\nexports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nfunction v35(version, hash, value, namespace, buf, offset) {\n const valueBytes = typeof value === 'string' ? stringToBytes(value) : value;\n const namespaceBytes = typeof namespace === 'string' ? (0, parse_js_1.default)(namespace) : namespace;\n if (typeof namespace === 'string') {\n namespace = (0, parse_js_1.default)(namespace);\n }\n if (namespace?.length !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n }\n let bytes = new Uint8Array(16 + valueBytes.length);\n bytes.set(namespaceBytes);\n bytes.set(valueBytes, namespaceBytes.length);\n bytes = hash(bytes);\n bytes[6] = (bytes[6] & 0x0f) | version;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, stringify_js_1.unsafeStringify)(bytes);\n}\nexports.default = v35;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URL = exports.DNS = void 0;\nconst md5_js_1 = require(\"./md5.js\");\nconst v35_js_1 = require(\"./v35.js\");\nvar v35_js_2 = require(\"./v35.js\");\nObject.defineProperty(exports, \"DNS\", { enumerable: true, get: function () { return v35_js_2.DNS; } });\nObject.defineProperty(exports, \"URL\", { enumerable: true, get: function () { return v35_js_2.URL; } });\nfunction v3(value, namespace, buf, offset) {\n return (0, v35_js_1.default)(0x30, md5_js_1.default, value, namespace, buf, offset);\n}\nv3.DNS = v35_js_1.DNS;\nv3.URL = v35_js_1.URL;\nexports.default = v3;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexports.default = { randomUUID };\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst native_js_1 = require(\"./native.js\");\nconst rng_js_1 = require(\"./rng.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nfunction v4(options, buf, offset) {\n if (native_js_1.default.randomUUID && !buf && !options) {\n return native_js_1.default.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? (0, rng_js_1.default)();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return (0, stringify_js_1.unsafeStringify)(rnds);\n}\nexports.default = v4;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return (x & y) ^ (~x & z);\n case 1:\n return x ^ y ^ z;\n case 2:\n return (x & y) ^ (x & z) ^ (y & z);\n case 3:\n return x ^ y ^ z;\n }\n}\nfunction ROTL(x, n) {\n return (x << n) | (x >>> (32 - n));\n}\nfunction sha1(bytes) {\n const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n const newBytes = new Uint8Array(bytes.length + 1);\n newBytes.set(bytes);\n newBytes[bytes.length] = 0x80;\n bytes = newBytes;\n const l = bytes.length / 4 + 2;\n const N = Math.ceil(l / 16);\n const M = new Array(N);\n for (let i = 0; i < N; ++i) {\n const arr = new Uint32Array(16);\n for (let j = 0; j < 16; ++j) {\n arr[j] =\n (bytes[i * 64 + j * 4] << 24) |\n (bytes[i * 64 + j * 4 + 1] << 16) |\n (bytes[i * 64 + j * 4 + 2] << 8) |\n bytes[i * 64 + j * 4 + 3];\n }\n M[i] = arr;\n }\n M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff;\n for (let i = 0; i < N; ++i) {\n const W = new Uint32Array(80);\n for (let t = 0; t < 16; ++t) {\n W[t] = M[i][t];\n }\n for (let t = 16; t < 80; ++t) {\n W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);\n }\n let a = H[0];\n let b = H[1];\n let c = H[2];\n let d = H[3];\n let e = H[4];\n for (let t = 0; t < 80; ++t) {\n const s = Math.floor(t / 20);\n const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n H[0] = (H[0] + a) >>> 0;\n H[1] = (H[1] + b) >>> 0;\n H[2] = (H[2] + c) >>> 0;\n H[3] = (H[3] + d) >>> 0;\n H[4] = (H[4] + e) >>> 0;\n }\n return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]);\n}\nexports.default = sha1;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.URL = exports.DNS = void 0;\nconst sha1_js_1 = require(\"./sha1.js\");\nconst v35_js_1 = require(\"./v35.js\");\nvar v35_js_2 = require(\"./v35.js\");\nObject.defineProperty(exports, \"DNS\", { enumerable: true, get: function () { return v35_js_2.DNS; } });\nObject.defineProperty(exports, \"URL\", { enumerable: true, get: function () { return v35_js_2.URL; } });\nfunction v5(value, namespace, buf, offset) {\n return (0, v35_js_1.default)(0x50, sha1_js_1.default, value, namespace, buf, offset);\n}\nv5.DNS = v35_js_1.DNS;\nv5.URL = v35_js_1.URL;\nexports.default = v5;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst stringify_js_1 = require(\"./stringify.js\");\nconst v1_js_1 = require(\"./v1.js\");\nconst v1ToV6_js_1 = require(\"./v1ToV6.js\");\nfunction v6(options, buf, offset) {\n options ??= {};\n offset ??= 0;\n let bytes = (0, v1_js_1.default)({ ...options, _v6: true }, new Uint8Array(16));\n bytes = (0, v1ToV6_js_1.default)(bytes);\n if (buf) {\n for (let i = 0; i < 16; i++) {\n buf[offset + i] = bytes[i];\n }\n return buf;\n }\n return (0, stringify_js_1.unsafeStringify)(bytes);\n}\nexports.default = v6;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst parse_js_1 = require(\"./parse.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nfunction v6ToV1(uuid) {\n const v6Bytes = typeof uuid === 'string' ? (0, parse_js_1.default)(uuid) : uuid;\n const v1Bytes = _v6ToV1(v6Bytes);\n return typeof uuid === 'string' ? (0, stringify_js_1.unsafeStringify)(v1Bytes) : v1Bytes;\n}\nexports.default = v6ToV1;\nfunction _v6ToV1(v6Bytes) {\n return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]);\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.updateV7State = void 0;\nconst rng_js_1 = require(\"./rng.js\");\nconst stringify_js_1 = require(\"./stringify.js\");\nconst _state = {};\nfunction v7(options, buf, offset) {\n let bytes;\n if (options) {\n bytes = v7Bytes(options.random ?? options.rng?.() ?? (0, rng_js_1.default)(), options.msecs, options.seq, buf, offset);\n }\n else {\n const now = Date.now();\n const rnds = (0, rng_js_1.default)();\n updateV7State(_state, now, rnds);\n bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);\n }\n return buf ?? (0, stringify_js_1.unsafeStringify)(bytes);\n}\nfunction updateV7State(state, now, rnds) {\n state.msecs ??= -Infinity;\n state.seq ??= 0;\n if (now > state.msecs) {\n state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];\n state.msecs = now;\n }\n else {\n state.seq = (state.seq + 1) | 0;\n if (state.seq === 0) {\n state.msecs++;\n }\n }\n return state;\n}\nexports.updateV7State = updateV7State;\nfunction v7Bytes(rnds, msecs, seq, buf, offset = 0) {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n if (!buf) {\n buf = new Uint8Array(16);\n offset = 0;\n }\n else {\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n }\n msecs ??= Date.now();\n seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9];\n buf[offset++] = (msecs / 0x10000000000) & 0xff;\n buf[offset++] = (msecs / 0x100000000) & 0xff;\n buf[offset++] = (msecs / 0x1000000) & 0xff;\n buf[offset++] = (msecs / 0x10000) & 0xff;\n buf[offset++] = (msecs / 0x100) & 0xff;\n buf[offset++] = msecs & 0xff;\n buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f);\n buf[offset++] = (seq >>> 20) & 0xff;\n buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f);\n buf[offset++] = (seq >>> 6) & 0xff;\n buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03);\n buf[offset++] = rnds[11];\n buf[offset++] = rnds[12];\n buf[offset++] = rnds[13];\n buf[offset++] = rnds[14];\n buf[offset++] = rnds[15];\n return buf;\n}\nexports.default = v7;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst validate_js_1 = require(\"./validate.js\");\nfunction version(uuid) {\n if (!(0, validate_js_1.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n return parseInt(uuid.slice(14, 15), 16);\n}\nexports.default = version;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.version = exports.validate = exports.v7 = exports.v6ToV1 = exports.v6 = exports.v5 = exports.v4 = exports.v3 = exports.v1ToV6 = exports.v1 = exports.stringify = exports.parse = exports.NIL = exports.MAX = void 0;\nvar max_js_1 = require(\"./max.js\");\nObject.defineProperty(exports, \"MAX\", { enumerable: true, get: function () { return max_js_1.default; } });\nvar nil_js_1 = require(\"./nil.js\");\nObject.defineProperty(exports, \"NIL\", { enumerable: true, get: function () { return nil_js_1.default; } });\nvar parse_js_1 = require(\"./parse.js\");\nObject.defineProperty(exports, \"parse\", { enumerable: true, get: function () { return parse_js_1.default; } });\nvar stringify_js_1 = require(\"./stringify.js\");\nObject.defineProperty(exports, \"stringify\", { enumerable: true, get: function () { return stringify_js_1.default; } });\nvar v1_js_1 = require(\"./v1.js\");\nObject.defineProperty(exports, \"v1\", { enumerable: true, get: function () { return v1_js_1.default; } });\nvar v1ToV6_js_1 = require(\"./v1ToV6.js\");\nObject.defineProperty(exports, \"v1ToV6\", { enumerable: true, get: function () { return v1ToV6_js_1.default; } });\nvar v3_js_1 = require(\"./v3.js\");\nObject.defineProperty(exports, \"v3\", { enumerable: true, get: function () { return v3_js_1.default; } });\nvar v4_js_1 = require(\"./v4.js\");\nObject.defineProperty(exports, \"v4\", { enumerable: true, get: function () { return v4_js_1.default; } });\nvar v5_js_1 = require(\"./v5.js\");\nObject.defineProperty(exports, \"v5\", { enumerable: true, get: function () { return v5_js_1.default; } });\nvar v6_js_1 = require(\"./v6.js\");\nObject.defineProperty(exports, \"v6\", { enumerable: true, get: function () { return v6_js_1.default; } });\nvar v6ToV1_js_1 = require(\"./v6ToV1.js\");\nObject.defineProperty(exports, \"v6ToV1\", { enumerable: true, get: function () { return v6ToV1_js_1.default; } });\nvar v7_js_1 = require(\"./v7.js\");\nObject.defineProperty(exports, \"v7\", { enumerable: true, get: function () { return v7_js_1.default; } });\nvar validate_js_1 = require(\"./validate.js\");\nObject.defineProperty(exports, \"validate\", { enumerable: true, get: function () { return validate_js_1.default; } });\nvar version_js_1 = require(\"./version.js\");\nObject.defineProperty(exports, \"version\", { enumerable: true, get: function () { return version_js_1.default; } });\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Represents a generic Entity.\r\n */\r\nexport interface Entity {\r\n /**\r\n * The type of the entity.\r\n */\r\n type: string\r\n /**\r\n * Additional properties of the entity.\r\n */\r\n [key: string]: unknown\r\n}\r\n\r\n/**\r\n * Zod schema for validating Entity objects.\r\n */\r\nexport const entityZodSchema = z.object({\r\n type: z.string().min(1)\r\n}).passthrough()\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { Entity, entityZodSchema } from '../entity/entity'\r\nimport { SemanticActionStateTypes, semanticActionStateTypesZodSchema } from './semanticActionStateTypes'\r\n\r\n/**\r\n * Represents a semantic action.\r\n */\r\nexport interface SemanticAction {\r\n /**\r\n * Unique identifier for the semantic action.\r\n */\r\n id: string\r\n /**\r\n * State of the semantic action.\r\n */\r\n state: SemanticActionStateTypes | string\r\n /**\r\n * Entities associated with the semantic action.\r\n */\r\n entities: { [propertyName: string]: Entity }\r\n}\r\n\r\n/**\r\n * Zod schema for validating SemanticAction.\r\n */\r\nexport const semanticActionZodSchema = z.object({\r\n id: z.string().min(1),\r\n state: z.union([semanticActionStateTypesZodSchema, z.string().min(1)]),\r\n entities: z.record(entityZodSchema)\r\n})\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { ActionTypes, actionTypesZodSchema } from './actionTypes'\r\n\r\n/**\r\n * Represents a card action.\r\n */\r\nexport interface CardAction {\r\n /**\r\n * Type of the action.\r\n */\r\n type: ActionTypes | string\r\n /**\r\n * Title of the action.\r\n */\r\n title: string\r\n /**\r\n * URL of the image associated with the action.\r\n */\r\n image?: string\r\n /**\r\n * Text associated with the action.\r\n */\r\n text?: string\r\n /**\r\n * Display text for the action.\r\n */\r\n displayText?: string\r\n /**\r\n * Value associated with the action.\r\n */\r\n value?: any\r\n /**\r\n * Channel-specific data associated with the action.\r\n */\r\n channelData?: unknown\r\n /**\r\n * Alt text for the image.\r\n */\r\n imageAltText?: string\r\n}\r\n\r\n/**\r\n * Zod schema for validating CardAction.\r\n */\r\nexport const cardActionZodSchema = z.object({\r\n type: z.union([actionTypesZodSchema, z.string().min(1)]),\r\n title: z.string().min(1),\r\n image: z.string().min(1).optional(),\r\n text: z.string().min(1).optional(),\r\n displayText: z.string().min(1).optional(),\r\n value: z.any().optional(),\r\n channelData: z.unknown().optional(),\r\n imageAltText: z.string().min(1).optional()\r\n})\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { CardAction, cardActionZodSchema } from './cardAction'\r\n\r\n/**\r\n * Represents suggested actions.\r\n */\r\nexport interface SuggestedActions {\r\n /**\r\n * Array of recipient IDs.\r\n */\r\n to: string[]\r\n /**\r\n * Array of card actions.\r\n */\r\n actions: CardAction[]\r\n}\r\n\r\n/**\r\n * Zod schema for validating SuggestedActions.\r\n */\r\nexport const suggestedActionsZodSchema = z.object({\r\n to: z.array(z.string().min(1)),\r\n actions: z.array(cardActionZodSchema)\r\n})\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing activity event names.\r\n */\r\nexport enum ActivityEventNames {\r\n /**\r\n * Event name for continuing a conversation.\r\n */\r\n ContinueConversation = 'ContinueConversation',\r\n\r\n /**\r\n * Event name for creating a new conversation.\r\n */\r\n CreateConversation = 'CreateConversation',\r\n}\r\n\r\n/**\r\n * Zod schema for validating an ActivityEventNames enum.\r\n */\r\nexport const activityEventNamesZodSchema = z.enum(['ContinueConversation', 'CreateConversation'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing activity importance levels.\r\n */\r\nexport enum ActivityImportance {\r\n /**\r\n * Indicates low importance.\r\n */\r\n Low = 'low',\r\n\r\n /**\r\n * Indicates normal importance.\r\n */\r\n Normal = 'normal',\r\n\r\n /**\r\n * Indicates high importance.\r\n */\r\n High = 'high',\r\n}\r\n\r\n/**\r\n * Zod schema for validating an ActivityImportance enum.\r\n */\r\nexport const activityImportanceZodSchema = z.enum(['low', 'normal', 'high'])\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing activity types.\r\n */\r\nexport enum ActivityTypes {\r\n /**\r\n * A message activity.\r\n */\r\n Message = 'message',\r\n\r\n /**\r\n * An update to a contact relationship.\r\n */\r\n ContactRelationUpdate = 'contactRelationUpdate',\r\n\r\n /**\r\n * An update to a conversation.\r\n */\r\n ConversationUpdate = 'conversationUpdate',\r\n\r\n /**\r\n * A typing indicator activity.\r\n */\r\n Typing = 'typing',\r\n\r\n /**\r\n * Indicates the end of a conversation.\r\n */\r\n EndOfConversation = 'endOfConversation',\r\n\r\n /**\r\n * An event activity.\r\n */\r\n Event = 'event',\r\n\r\n /**\r\n * An invoke activity.\r\n */\r\n Invoke = 'invoke',\r\n\r\n /**\r\n * A response to an invoke activity.\r\n */\r\n InvokeResponse = 'invokeResponse',\r\n\r\n /**\r\n * An activity to delete user data.\r\n */\r\n DeleteUserData = 'deleteUserData',\r\n\r\n /**\r\n * An update to a message.\r\n */\r\n MessageUpdate = 'messageUpdate',\r\n\r\n /**\r\n * A deletion of a message.\r\n */\r\n MessageDelete = 'messageDelete',\r\n\r\n /**\r\n * An update to an installation.\r\n */\r\n InstallationUpdate = 'installationUpdate',\r\n\r\n /**\r\n * A reaction to a message.\r\n */\r\n MessageReaction = 'messageReaction',\r\n\r\n /**\r\n * A suggestion activity.\r\n */\r\n Suggestion = 'suggestion',\r\n\r\n /**\r\n * A trace activity for debugging.\r\n */\r\n Trace = 'trace',\r\n\r\n /**\r\n * A handoff activity to another bot or human.\r\n */\r\n Handoff = 'handoff',\r\n\r\n /**\r\n * A command activity.\r\n */\r\n Command = 'command',\r\n\r\n /**\r\n * A result of a command activity.\r\n */\r\n CommandResult = 'commandResult',\r\n\r\n /**\r\n * A delay activity.\r\n */\r\n Delay = 'delay'\r\n}\r\n\r\n/**\r\n * Zod schema for validating an ActivityTypes enum.\r\n */\r\nexport const activityTypesZodSchema = z.enum([\r\n 'message',\r\n 'contactRelationUpdate',\r\n 'conversationUpdate',\r\n 'typing',\r\n 'endOfConversation',\r\n 'event',\r\n 'invoke',\r\n 'invokeResponse',\r\n 'deleteUserData',\r\n 'messageUpdate',\r\n 'messageDelete',\r\n 'installationUpdate',\r\n 'messageReaction',\r\n 'suggestion',\r\n 'trace',\r\n 'handoff',\r\n 'command',\r\n 'commandResult',\r\n 'delay'\r\n])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Represents an attachment.\r\n */\r\nexport interface Attachment {\r\n /**\r\n * The MIME type of the attachment content.\r\n */\r\n contentType: string\r\n\r\n /**\r\n * The URL of the attachment content.\r\n */\r\n contentUrl?: string\r\n\r\n /**\r\n * The content of the attachment.\r\n */\r\n content?: unknown\r\n\r\n /**\r\n * The name of the attachment.\r\n */\r\n name?: string\r\n\r\n /**\r\n * The URL of the thumbnail for the attachment.\r\n */\r\n thumbnailUrl?: string\r\n}\r\n\r\n/**\r\n * Zod schema for validating attachments.\r\n */\r\nexport const attachmentZodSchema = z.object({\r\n contentType: z.string().min(1),\r\n contentUrl: z.string().min(1).optional(),\r\n content: z.unknown().optional(),\r\n name: z.string().min(1).optional(),\r\n thumbnailUrl: z.string().min(1).optional()\r\n})\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { roleTypeZodSchema, RoleTypes } from './roleTypes'\r\nimport { MembershipSource } from './membershipSource'\r\n\r\n/**\r\n * Represents a channel account.\r\n */\r\nexport interface ChannelAccount {\r\n /**\r\n * The unique identifier of the channel account.\r\n */\r\n id?: string\r\n\r\n /**\r\n * The name of the channel account.\r\n */\r\n name?: string\r\n\r\n /**\r\n * The Azure Active Directory object ID of the channel account.\r\n */\r\n aadObjectId?: string\r\n\r\n /**\r\n * The role of the channel account.\r\n */\r\n role?: RoleTypes | string\r\n\r\n /**\r\n * Additional properties of the channel account.\r\n */\r\n properties?: unknown\r\n\r\n /**\r\n * List of membership sources associated with the channel account.\r\n */\r\n membershipSources?: MembershipSource[]\r\n}\r\n\r\n/**\r\n * Zod schema for validating a channel account.\r\n */\r\nexport const channelAccountZodSchema = z.object({\r\n id: z.string().min(1).optional(),\r\n name: z.string().optional(),\r\n aadObjectId: z.string().min(1).optional(),\r\n role: z.union([roleTypeZodSchema, z.string().min(1)]).optional(),\r\n properties: z.unknown().optional()\r\n})\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { roleTypeZodSchema, RoleTypes } from './roleTypes'\r\n\r\n/**\r\n * Represents a conversation account.\r\n */\r\nexport interface ConversationAccount {\r\n /**\r\n * The unique identifier of the conversation account.\r\n */\r\n id: string\r\n\r\n /**\r\n * The type of the conversation (e.g., personal, group, etc.).\r\n */\r\n conversationType?: string\r\n\r\n /**\r\n * The tenant ID associated with the conversation account.\r\n */\r\n tenantId?: string\r\n\r\n /**\r\n * Indicates whether the conversation is a group.\r\n */\r\n isGroup?: boolean\r\n\r\n /**\r\n * The name of the conversation account.\r\n */\r\n name?: string\r\n\r\n /**\r\n * The Azure Active Directory object ID of the conversation account.\r\n */\r\n aadObjectId?: string\r\n\r\n /**\r\n * The role of the conversation account.\r\n */\r\n role?: RoleTypes | string\r\n\r\n /**\r\n * Additional properties of the conversation account.\r\n */\r\n properties?: unknown\r\n}\r\n\r\n/**\r\n * Zod schema for validating a conversation account.\r\n */\r\nexport const conversationAccountZodSchema = z.object({\r\n isGroup: z.boolean().optional(),\r\n conversationType: z.string().min(1).optional(),\r\n tenantId: z.string().min(1).optional(),\r\n id: z.string().min(1),\r\n name: z.string().min(1).optional(),\r\n aadObjectId: z.string().min(1).optional(),\r\n role: z.union([roleTypeZodSchema, z.string().min(1)]).optional(),\r\n properties: z.unknown().optional()\r\n})\r\n", "/**\r\n * Copyright(c) Microsoft Corporation.All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { ChannelAccount, channelAccountZodSchema } from './channelAccount'\r\nimport { ConversationAccount, conversationAccountZodSchema } from './conversationAccount'\r\n\r\n/**\r\n * Represents a reference to a conversation.\r\n */\r\nexport interface ConversationReference {\r\n /**\r\n * The ID of the activity. Optional.\r\n */\r\n activityId?: string\r\n\r\n /**\r\n * The user involved in the conversation. Optional.\r\n */\r\n user?: ChannelAccount\r\n\r\n /**\r\n * The locale of the conversation. Optional.\r\n */\r\n locale?: string\r\n\r\n /**\r\n * The agent involved in the conversation. Can be undefined or null. Optional.\r\n */\r\n agent?: ChannelAccount | undefined | null\r\n\r\n /**\r\n * The conversation account details.\r\n */\r\n conversation: ConversationAccount\r\n\r\n /**\r\n * The ID of the channel where the conversation is taking place.\r\n */\r\n channelId: string\r\n\r\n /**\r\n * The service URL for the conversation. Optional.\r\n */\r\n serviceUrl?: string | undefined\r\n}\r\n\r\n/**\r\n * Zod schema for validating a conversation reference.\r\n */\r\nexport const conversationReferenceZodSchema = z.object({\r\n activityId: z.string().min(1).optional(),\r\n user: channelAccountZodSchema.optional(),\r\n locale: z.string().min(1).optional(),\r\n agent: channelAccountZodSchema.optional().nullable(),\r\n conversation: conversationAccountZodSchema,\r\n channelId: z.string().min(1),\r\n serviceUrl: z.string().min(1).optional()\r\n})\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing delivery modes.\r\n */\r\nexport enum DeliveryModes {\r\n /**\r\n * Represents the normal delivery mode.\r\n */\r\n Normal = 'normal',\r\n\r\n /**\r\n * Represents a notification delivery mode.\r\n */\r\n Notification = 'notification',\r\n\r\n /**\r\n * Represents a delivery mode where replies are expected.\r\n */\r\n ExpectReplies = 'expectReplies',\r\n\r\n /**\r\n * Represents an ephemeral delivery mode.\r\n */\r\n Ephemeral = 'ephemeral',\r\n}\r\n\r\n/**\r\n * Zod schema for validating a DeliveryModes enum.\r\n */\r\nexport const deliveryModesZodSchema = z.enum(['normal', 'notification', 'expectReplies', 'ephemeral'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing input hints.\r\n */\r\nexport enum InputHints {\r\n /**\r\n * Indicates that the bot is ready to accept input from the user.\r\n */\r\n AcceptingInput = 'acceptingInput',\r\n\r\n /**\r\n * Indicates that the bot is ignoring input from the user.\r\n */\r\n IgnoringInput = 'ignoringInput',\r\n\r\n /**\r\n * Indicates that the bot is expecting input from the user.\r\n */\r\n ExpectingInput = 'expectingInput',\r\n}\r\n\r\n/**\r\n * Zod schema for validating an InputHints enum.\r\n */\r\nexport const inputHintsZodSchema = z.enum(['acceptingInput', 'ignoringInput', 'expectingInput'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing message reaction types.\r\n */\r\nexport enum MessageReactionTypes {\r\n /**\r\n * Represents a 'like' reaction to a message.\r\n */\r\n Like = 'like',\r\n\r\n /**\r\n * Represents a '+1' reaction to a message.\r\n */\r\n PlusOne = 'plusOne',\r\n}\r\n\r\n/**\r\n * Zod schema for validating MessageReactionTypes enum values.\r\n */\r\nexport const messageReactionTypesZodSchema = z.enum(['like', 'plusOne'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\nimport { MessageReactionTypes, messageReactionTypesZodSchema } from './messageReactionTypes'\r\n\r\n/**\r\n * Represents a message reaction.\r\n */\r\nexport interface MessageReaction {\r\n /**\r\n * The type of the reaction.\r\n */\r\n type: MessageReactionTypes | string\r\n}\r\n\r\n/**\r\n * Zod schema for validating a MessageReaction object.\r\n */\r\nexport const messageReactionZodSchema = z.object({\r\n type: z.union([messageReactionTypesZodSchema, z.string().min(1)])\r\n})\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing text format types.\r\n */\r\nexport enum TextFormatTypes {\r\n /**\r\n * Represents text formatted using Markdown.\r\n */\r\n Markdown = 'markdown',\r\n\r\n /**\r\n * Represents plain text without any formatting.\r\n */\r\n Plain = 'plain',\r\n\r\n /**\r\n * Represents text formatted using XML.\r\n */\r\n Xml = 'xml',\r\n}\r\n\r\n/**\r\n * Zod schema for validating TextFormatTypes enum values.\r\n */\r\nexport const textFormatTypesZodSchema = z.enum(['markdown', 'plain', 'xml'])\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Represents a text highlight.\r\n */\r\nexport interface TextHighlight {\r\n /**\r\n * The highlighted text.\r\n */\r\n text: string\r\n /**\r\n * The occurrence count of the highlighted text.\r\n */\r\n occurrence: number\r\n}\r\n\r\n/**\r\n * Zod schema for validating TextHighlight objects.\r\n */\r\nexport const textHighlightZodSchema = z.object({\r\n text: z.string().min(1),\r\n occurrence: z.number()\r\n})\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { v4 as uuid } from 'uuid'\r\nimport { z } from 'zod'\r\nimport { SemanticAction, semanticActionZodSchema } from './action/semanticAction'\r\nimport { SuggestedActions, suggestedActionsZodSchema } from './action/suggestedActions'\r\nimport { ActivityEventNames, activityEventNamesZodSchema } from './activityEventNames'\r\nimport { ActivityImportance, activityImportanceZodSchema } from './activityImportance'\r\nimport { ActivityTypes, activityTypesZodSchema } from './activityTypes'\r\nimport { Attachment, attachmentZodSchema } from './attachment/attachment'\r\nimport { AttachmentLayoutTypes, attachmentLayoutTypesZodSchema } from './attachment/attachmentLayoutTypes'\r\nimport { ChannelAccount, channelAccountZodSchema } from './conversation/channelAccount'\r\nimport { Channels } from './conversation/channels'\r\nimport { ConversationAccount, conversationAccountZodSchema } from './conversation/conversationAccount'\r\nimport { ConversationReference, conversationReferenceZodSchema } from './conversation/conversationReference'\r\nimport { EndOfConversationCodes, endOfConversationCodesZodSchema } from './conversation/endOfConversationCodes'\r\nimport { DeliveryModes, deliveryModesZodSchema } from './deliveryModes'\r\nimport { Entity, entityZodSchema } from './entity/entity'\r\nimport { Mention } from './entity/mention'\r\nimport { InputHints, inputHintsZodSchema } from './inputHints'\r\nimport { MessageReaction, messageReactionZodSchema } from './messageReaction'\r\nimport { TextFormatTypes, textFormatTypesZodSchema } from './textFormatTypes'\r\nimport { TextHighlight, textHighlightZodSchema } from './textHighlight'\r\n\r\n/**\r\n * Zod schema for validating an Activity object.\r\n */\r\nexport const activityZodSchema = z.object({\r\n type: z.union([activityTypesZodSchema, z.string().min(1)]),\r\n text: z.string().optional(),\r\n id: z.string().min(1).optional(),\r\n channelId: z.string().min(1).optional(),\r\n from: channelAccountZodSchema.optional(),\r\n timestamp: z.union([z.date(), z.string().min(1).datetime().optional(), z.string().min(1).transform(s => new Date(s)).optional()]),\r\n localTimestamp: z.string().min(1).transform(s => new Date(s)).optional().or(z.date()).optional(), // z.string().min(1).transform(s => new Date(s)).optional(),\r\n localTimezone: z.string().min(1).optional(),\r\n callerId: z.string().min(1).optional(),\r\n serviceUrl: z.string().min(1).optional(),\r\n conversation: conversationAccountZodSchema.optional(),\r\n recipient: channelAccountZodSchema.optional(),\r\n textFormat: z.union([textFormatTypesZodSchema, z.string().min(1)]).optional(),\r\n attachmentLayout: z.union([attachmentLayoutTypesZodSchema, z.string().min(1)]).optional(),\r\n membersAdded: z.array(channelAccountZodSchema).optional(),\r\n membersRemoved: z.array(channelAccountZodSchema).optional(),\r\n reactionsAdded: z.array(messageReactionZodSchema).optional(),\r\n reactionsRemoved: z.array(messageReactionZodSchema).optional(),\r\n topicName: z.string().min(1).optional(),\r\n historyDisclosed: z.boolean().optional(),\r\n locale: z.string().min(1).optional(),\r\n speak: z.string().min(1).optional(),\r\n inputHint: z.union([inputHintsZodSchema, z.string().min(1)]).optional(),\r\n summary: z.string().min(1).optional(),\r\n suggestedActions: suggestedActionsZodSchema.optional(),\r\n attachments: z.array(attachmentZodSchema).optional(),\r\n entities: z.array(entityZodSchema.passthrough()).optional(),\r\n channelData: z.any().optional(),\r\n action: z.string().min(1).optional(),\r\n replyToId: z.string().min(1).optional(),\r\n label: z.string().min(1).optional(),\r\n valueType: z.string().min(1).optional(),\r\n value: z.unknown().optional(),\r\n name: z.union([activityEventNamesZodSchema, z.string().min(1)]).optional(),\r\n relatesTo: conversationReferenceZodSchema.optional(),\r\n code: z.union([endOfConversationCodesZodSchema, z.string().min(1)]).optional(),\r\n expiration: z.string().min(1).datetime().optional(),\r\n importance: z.union([activityImportanceZodSchema, z.string().min(1)]).optional(),\r\n deliveryMode: z.union([deliveryModesZodSchema, z.string().min(1)]).optional(),\r\n listenFor: z.array(z.string().min(1)).optional(),\r\n textHighlights: z.array(textHighlightZodSchema).optional(),\r\n semanticAction: semanticActionZodSchema.optional(),\r\n})\r\n\r\n/**\r\n * Represents an activity in a conversation.\r\n */\r\nexport class Activity {\r\n /**\r\n * The type of the activity.\r\n */\r\n type: ActivityTypes | string\r\n\r\n /**\r\n * The text content of the activity.\r\n */\r\n text?: string\r\n\r\n /**\r\n * The unique identifier of the activity.\r\n */\r\n id?: string\r\n\r\n /**\r\n * The channel ID where the activity originated.\r\n */\r\n channelId?: string\r\n\r\n /**\r\n * The account of the sender of the activity.\r\n */\r\n from?: ChannelAccount\r\n\r\n /**\r\n * The timestamp of the activity.\r\n */\r\n timestamp?: Date | string\r\n\r\n /**\r\n * The local timestamp of the activity.\r\n */\r\n localTimestamp?: Date | string\r\n\r\n /**\r\n * The local timezone of the activity.\r\n */\r\n localTimezone?: string\r\n\r\n /**\r\n * The caller ID of the activity.\r\n */\r\n callerId?: string\r\n\r\n /**\r\n * The service URL of the activity.\r\n */\r\n serviceUrl?: string\r\n\r\n /**\r\n * The conversation account associated with the activity.\r\n */\r\n conversation?: ConversationAccount\r\n\r\n /**\r\n * The recipient of the activity.\r\n */\r\n recipient?: ChannelAccount\r\n\r\n /**\r\n * The text format of the activity.\r\n */\r\n textFormat?: TextFormatTypes | string\r\n\r\n /**\r\n * The attachment layout of the activity.\r\n */\r\n attachmentLayout?: AttachmentLayoutTypes | string\r\n\r\n /**\r\n * The members added to the conversation.\r\n */\r\n membersAdded?: ChannelAccount[]\r\n\r\n /**\r\n * The members removed from the conversation.\r\n */\r\n membersRemoved?: ChannelAccount[]\r\n\r\n /**\r\n * The reactions added to the activity.\r\n */\r\n reactionsAdded?: MessageReaction[]\r\n\r\n /**\r\n * The reactions removed from the activity.\r\n */\r\n reactionsRemoved?: MessageReaction[]\r\n\r\n /**\r\n * The topic name of the activity.\r\n */\r\n topicName?: string\r\n\r\n /**\r\n * Indicates whether the history is disclosed.\r\n */\r\n historyDisclosed?: boolean\r\n\r\n /**\r\n * The locale of the activity.\r\n */\r\n locale?: string\r\n\r\n /**\r\n * The speech text of the activity.\r\n */\r\n speak?: string\r\n\r\n /**\r\n * The input hint for the activity.\r\n */\r\n inputHint?: InputHints | string\r\n\r\n /**\r\n * The summary of the activity.\r\n */\r\n summary?: string\r\n\r\n /**\r\n * The suggested actions for the activity.\r\n */\r\n suggestedActions?: SuggestedActions\r\n\r\n /**\r\n * The attachments of the activity.\r\n */\r\n attachments?: Attachment[]\r\n\r\n /**\r\n * The entities associated with the activity.\r\n */\r\n entities?: Entity[]\r\n\r\n /**\r\n * The channel-specific data for the activity.\r\n */\r\n channelData?: any\r\n\r\n /**\r\n * The action associated with the activity.\r\n */\r\n action?: string\r\n\r\n /**\r\n * The ID of the activity being replied to.\r\n */\r\n replyToId?: string\r\n\r\n /**\r\n * The label for the activity.\r\n */\r\n label?: string\r\n\r\n /**\r\n * The value type of the activity.\r\n */\r\n valueType?: string\r\n\r\n /**\r\n * The value associated with the activity.\r\n */\r\n value?: unknown\r\n\r\n /**\r\n * The name of the activity event.\r\n */\r\n name?: ActivityEventNames | string\r\n\r\n /**\r\n * The conversation reference for the activity.\r\n */\r\n relatesTo?: ConversationReference\r\n\r\n /**\r\n * The end-of-conversation code for the activity.\r\n */\r\n code?: EndOfConversationCodes | string\r\n\r\n /**\r\n * The expiration time of the activity.\r\n */\r\n expiration?: string | Date\r\n\r\n /**\r\n * The importance of the activity.\r\n */\r\n importance?: ActivityImportance | string\r\n\r\n /**\r\n * The delivery mode of the activity.\r\n */\r\n deliveryMode?: DeliveryModes | string\r\n\r\n /**\r\n * The list of keywords to listen for in the activity.\r\n */\r\n listenFor?: string[]\r\n\r\n /**\r\n * The text highlights in the activity.\r\n */\r\n textHighlights?: TextHighlight[]\r\n\r\n /**\r\n * The semantic action associated with the activity.\r\n */\r\n semanticAction?: SemanticAction\r\n\r\n /**\r\n * The raw timestamp of the activity.\r\n */\r\n rawTimestamp?: string\r\n\r\n /**\r\n * The raw expiration time of the activity.\r\n */\r\n rawExpiration?: string\r\n\r\n /**\r\n * The raw local timestamp of the activity.\r\n */\r\n rawLocalTimestamp?: string\r\n\r\n /**\r\n * Additional properties of the activity.\r\n */\r\n [x: string]: unknown\r\n\r\n /**\r\n * Creates a new Activity instance.\r\n * @param t The type of the activity.\r\n * @throws Will throw an error if the activity type is invalid.\r\n */\r\n constructor (t: ActivityTypes | string) {\r\n if (t === undefined) {\r\n throw new Error('Invalid ActivityType: undefined')\r\n }\r\n if (t === null) {\r\n throw new Error('Invalid ActivityType: null')\r\n }\r\n if ((typeof t === 'string') && (t.length === 0)) {\r\n throw new Error('Invalid ActivityType: empty string')\r\n }\r\n\r\n this.type = t\r\n }\r\n\r\n /**\r\n * Creates an Activity instance from a JSON string.\r\n * @param json The JSON string representing the activity.\r\n * @returns The created Activity instance.\r\n */\r\n static fromJson (json: string): Activity {\r\n return this.fromObject(JSON.parse(json))\r\n }\r\n\r\n /**\r\n * Creates an Activity instance from an object.\r\n * @param o The object representing the activity.\r\n * @returns The created Activity instance.\r\n */\r\n static fromObject (o: object): Activity {\r\n const parsedActivity = activityZodSchema.passthrough().parse(o)\r\n const activity = new Activity(parsedActivity.type)\r\n Object.assign(activity, parsedActivity)\r\n return activity\r\n }\r\n\r\n /**\r\n * Creates a continuation activity from a conversation reference.\r\n * @param reference The conversation reference.\r\n * @returns The created continuation activity.\r\n */\r\n static getContinuationActivity (reference: ConversationReference): Activity {\r\n const continuationActivityObj = {\r\n type: ActivityTypes.Event,\r\n name: ActivityEventNames.ContinueConversation,\r\n id: uuid(),\r\n channelId: reference.channelId,\r\n locale: reference.locale,\r\n serviceUrl: reference.serviceUrl,\r\n conversation: reference.conversation,\r\n recipient: reference.agent,\r\n from: reference.user,\r\n relatesTo: reference\r\n }\r\n const continuationActivity: Activity = Activity.fromObject(continuationActivityObj)\r\n return continuationActivity\r\n }\r\n\r\n /**\r\n * Gets the appropriate reply-to ID for the activity.\r\n * @returns The reply-to ID, or undefined if not applicable.\r\n */\r\n private getAppropriateReplyToId (): string | undefined {\r\n if (\r\n this.type !== ActivityTypes.ConversationUpdate ||\r\n (this.channelId !== Channels.Directline && this.channelId !== Channels.Webchat)\r\n ) {\r\n return this.id\r\n }\r\n\r\n return undefined\r\n }\r\n\r\n /**\r\n * Gets the conversation reference for the activity.\r\n * @returns The conversation reference.\r\n * @throws Will throw an error if required properties are undefined.\r\n */\r\n public getConversationReference (): ConversationReference {\r\n if (this.recipient === null || this.recipient === undefined) {\r\n throw new Error('Activity Recipient undefined')\r\n }\r\n if (this.conversation === null || this.conversation === undefined) {\r\n throw new Error('Activity Conversation undefined')\r\n }\r\n if (this.channelId === null || this.channelId === undefined) {\r\n throw new Error('Activity ChannelId undefined')\r\n }\r\n\r\n return {\r\n activityId: this.getAppropriateReplyToId(),\r\n user: this.from,\r\n agent: this.recipient,\r\n conversation: this.conversation,\r\n channelId: this.channelId,\r\n locale: this.locale,\r\n serviceUrl: this.serviceUrl\r\n }\r\n }\r\n\r\n /**\r\n * Applies a conversation reference to the activity.\r\n * @param reference The conversation reference.\r\n * @param isIncoming Whether the activity is incoming.\r\n * @returns The updated activity.\r\n */\r\n public applyConversationReference (\r\n reference: ConversationReference,\r\n isIncoming = false\r\n ): Activity {\r\n this.channelId = reference.channelId\r\n this.locale ??= reference.locale\r\n this.serviceUrl = reference.serviceUrl\r\n this.conversation = reference.conversation\r\n if (isIncoming) {\r\n this.from = reference.user\r\n this.recipient = reference.agent ?? undefined\r\n if (reference.activityId) {\r\n this.id = reference.activityId\r\n }\r\n } else {\r\n this.from = reference.agent ?? undefined\r\n this.recipient = reference.user\r\n if (reference.activityId) {\r\n this.replyToId = reference.activityId\r\n }\r\n }\r\n\r\n return this\r\n }\r\n\r\n public clone (): Activity {\r\n const activityCopy = JSON.parse(JSON.stringify(this))\r\n\r\n for (const key in activityCopy) {\r\n if (typeof activityCopy[key] === 'string' && !isNaN(Date.parse(activityCopy[key]))) {\r\n activityCopy[key] = new Date(activityCopy[key] as string)\r\n }\r\n }\r\n\r\n Object.setPrototypeOf(activityCopy, Activity.prototype)\r\n return activityCopy\r\n }\r\n\r\n /**\r\n * Gets the mentions in the activity.\r\n * @param activity The activity.\r\n * @returns The list of mentions.\r\n */\r\n public getMentions (activity: Activity): Mention[] {\r\n const result: Mention[] = []\r\n if (activity.entities !== undefined) {\r\n for (let i = 0; i < activity.entities.length; i++) {\r\n if (activity.entities[i].type.toLowerCase() === 'mention') {\r\n result.push(activity.entities[i] as unknown as Mention)\r\n }\r\n }\r\n }\r\n return result\r\n }\r\n\r\n /**\r\n * Normalizes mentions in the activity by removing mention tags and optionally removing recipient mention.\r\n * @param removeMention Whether to remove the recipient mention from the activity.\r\n */\r\n public normalizeMentions (removeMention: boolean = false): void {\r\n if (this.type === ActivityTypes.Message) {\r\n if (removeMention) {\r\n // Strip recipient mention tags and text\r\n this.removeRecipientMention()\r\n\r\n // Strip entity.mention records for recipient id\r\n if (this.entities !== undefined && this.recipient?.id) {\r\n this.entities = this.entities.filter((entity) => {\r\n if (entity.type.toLowerCase() === 'mention') {\r\n const mention = entity as unknown as Mention\r\n return mention.mentioned.id !== this.recipient?.id\r\n }\r\n return true\r\n })\r\n }\r\n }\r\n\r\n // Remove tags keeping the inner text\r\n if (this.text) {\r\n this.text = Activity.removeAt(this.text)\r\n }\r\n\r\n // Remove tags from mention records keeping the inner text\r\n if (this.entities !== undefined) {\r\n const mentions = this.getMentions(this)\r\n for (const mention of mentions) {\r\n if (mention.text) {\r\n mention.text = Activity.removeAt(mention.text)?.trim()\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Removes tags from the specified text.\r\n * @param text The text to process.\r\n * @returns The text with tags removed.\r\n */\r\n private static removeAt (text: string): string {\r\n if (!text) {\r\n return text\r\n }\r\n\r\n let foundTag: boolean\r\n do {\r\n foundTag = false\r\n const iAtStart = text.toLowerCase().indexOf('= 0) {\r\n const iAtEnd = text.indexOf('>', iAtStart)\r\n if (iAtEnd > 0) {\r\n const iAtClose = text.toLowerCase().indexOf('', iAtEnd)\r\n if (iAtClose > 0) {\r\n // Replace \r\n let followingText = text.substring(iAtClose + 5)\r\n\r\n // If first char of followingText is not whitespace, insert space\r\n if (followingText.length > 0 && !(/\\s/.test(followingText[0]))) {\r\n followingText = ` ${followingText}`\r\n }\r\n\r\n text = text.substring(0, iAtClose) + followingText\r\n\r\n // Get tag content (text between and )\r\n const tagContent = text.substring(iAtEnd + 1, iAtClose)\r\n\r\n // Replace with just the tag content\r\n let prefixText = text.substring(0, iAtStart)\r\n\r\n // If prefixText is not empty and doesn't end with whitespace, add a space\r\n if (prefixText.length > 0 && !(/\\s$/.test(prefixText))) {\r\n prefixText += ' '\r\n }\r\n\r\n text = prefixText + tagContent + followingText\r\n\r\n // We found one, try again, there may be more\r\n foundTag = true\r\n }\r\n }\r\n }\r\n } while (foundTag)\r\n\r\n return text\r\n }\r\n\r\n /**\r\n * Removes the mention text for a given ID.\r\n * @param id The ID of the mention to remove.\r\n * @returns The updated text.\r\n */\r\n public removeMentionText (id: string): string {\r\n const mentions = this.getMentions(this)\r\n const mentionsFiltered = mentions.filter((mention): boolean => mention.mentioned.id === id)\r\n if ((mentionsFiltered.length > 0) && this.text) {\r\n this.text = this.text.replace(mentionsFiltered[0].text, '').trim()\r\n }\r\n return this.text || ''\r\n }\r\n\r\n /**\r\n * Removes the recipient mention from the activity text.\r\n * @returns The updated text.\r\n */\r\n public removeRecipientMention (): string {\r\n if ((this.recipient != null) && this.recipient.id) {\r\n return this.removeMentionText(this.recipient.id)\r\n }\r\n return ''\r\n }\r\n\r\n /**\r\n * Gets the conversation reference for a reply.\r\n * @param replyId The ID of the reply.\r\n * @returns The conversation reference.\r\n */\r\n public getReplyConversationReference (\r\n replyId: string\r\n ): ConversationReference {\r\n const reference: ConversationReference = this.getConversationReference()\r\n\r\n reference.activityId = replyId\r\n\r\n return reference\r\n }\r\n\r\n public toJsonString (): string {\r\n return JSON.stringify(this)\r\n }\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Constants representing caller IDs.\r\n */\r\nexport const CallerIdConstants = {\r\n /**\r\n * Public Azure channel caller ID.\r\n */\r\n PublicAzureChannel: 'urn:botframework:azure',\r\n /**\r\n * US Government channel caller ID.\r\n */\r\n USGovChannel: 'urn:botframework:azureusgov',\r\n /**\r\n * Agent prefix for caller ID.\r\n */\r\n AgentPrefix: 'urn:botframework:aadappid:'\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { z } from 'zod'\r\n\r\n/**\r\n * Enum representing treatment types for the activity.\r\n */\r\nexport enum ActivityTreatments {\r\n /**\r\n * Indicates that only the recipient should be able to see the message even if the activity\r\n * is being sent to a group of people.\r\n */\r\n Targeted = 'targeted',\r\n}\r\n\r\n/**\r\n * Zod schema for validating an ActivityTreatments enum.\r\n */\r\nexport const activityTreatments = z.nativeEnum(ActivityTreatments)\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\n/**\r\n * Export statements for various modules.\r\n */\r\nexport { ActionTypes } from './action/actionTypes'\r\nexport { CardAction } from './action/cardAction'\r\nexport { SemanticAction } from './action/semanticAction'\r\nexport { SemanticActionStateTypes } from './action/semanticActionStateTypes'\r\nexport { SuggestedActions } from './action/suggestedActions'\r\n\r\nexport { Attachment } from './attachment/attachment'\r\nexport { AttachmentLayoutTypes } from './attachment/attachmentLayoutTypes'\r\n\r\nexport { ChannelAccount } from './conversation/channelAccount'\r\nexport { Channels } from './conversation/channels'\r\nexport { ConversationAccount } from './conversation/conversationAccount'\r\nexport { ConversationReference } from './conversation/conversationReference'\r\nexport { EndOfConversationCodes } from './conversation/endOfConversationCodes'\r\nexport { ConversationParameters } from './conversation/conversationParameters'\r\nexport { MembershipSource } from './conversation/membershipSource'\r\nexport { MembershipSourceTypes } from './conversation/membershipSourceTypes'\r\nexport { MembershipTypes } from './conversation/membershipTypes'\r\nexport { RoleTypes } from './conversation/roleTypes'\r\n\r\nexport { Entity } from './entity/entity'\r\nexport { Mention } from './entity/mention'\r\nexport { GeoCoordinates } from './entity/geoCoordinates'\r\nexport { Place } from './entity/place'\r\nexport { Thing } from './entity/thing'\r\nexport * from './entity/AIEntity'\r\n\r\nexport * from './invoke/adaptiveCardInvokeAction'\r\n\r\nexport { Activity, activityZodSchema } from './activity'\r\nexport { ActivityEventNames } from './activityEventNames'\r\nexport { ActivityImportance } from './activityImportance'\r\nexport { ActivityTypes } from './activityTypes'\r\nexport { CallerIdConstants } from './callerIdConstants'\r\nexport { DeliveryModes } from './deliveryModes'\r\nexport { ExpectedReplies } from './expectedReplies'\r\nexport { InputHints } from './inputHints'\r\nexport { MessageReaction } from './messageReaction'\r\nexport { MessageReactionTypes } from './messageReactionTypes'\r\nexport { TextFormatTypes } from './textFormatTypes'\r\nexport { TextHighlight } from './textHighlight'\r\nexport { ActivityTreatments } from './activityTreatments'\r\nexport { debug, Logger } from './logger'\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { Activity } from '@microsoft/agents-activity'\r\n\r\n/**\r\n * Represents a request to execute a turn in a conversation.\r\n * This class encapsulates the activity to be executed during the turn.\r\n */\r\nexport class ExecuteTurnRequest {\r\n /** The activity to be executed. */\r\n activity?: Activity\r\n\r\n /**\r\n * Creates an instance of ExecuteTurnRequest.\r\n * @param activity The activity to be executed.\r\n */\r\n constructor (activity?: Activity) {\r\n this.activity = activity\r\n }\r\n}\r\n", "{\r\n \"name\": \"@microsoft/agents-copilotstudio-client\",\r\n \"version\": \"0.1.0\",\r\n \"homepage\": \"https://github.com/microsoft/Agents-for-js\",\r\n \"repository\": {\r\n \"type\": \"git\",\r\n \"url\": \"git+https://github.com/microsoft/Agents-for-js.git\"\r\n },\r\n \"author\": {\r\n \"name\": \"Microsoft\",\r\n \"email\": \"agentssdk@microsoft.com\",\r\n \"url\": \"https://aka.ms/Agents\"\r\n },\r\n \"description\": \"Microsoft Copilot Studio Client for JavaScript. Copilot Studio Client.\",\r\n \"keywords\": [\r\n \"Agents\",\r\n \"copilotstudio\",\r\n \"powerplatform\"\r\n ],\r\n \"main\": \"dist/src/index.js\",\r\n \"types\": \"dist/src/index.d.ts\",\r\n \"browser\": {\r\n \"os\": \"./src/browser/os.ts\",\r\n \"crypto\": \"./src/browser/crypto.ts\"\r\n },\r\n \"scripts\": {\r\n \"build:browser\": \"esbuild --platform=browser --target=es2019 --format=esm --bundle --sourcemap --minify --outfile=dist/src/browser.mjs src/index.ts\"\r\n },\r\n \"dependencies\": {\r\n \"@microsoft/agents-activity\": \"file:../agents-activity\",\r\n \"eventsource-client\": \"^1.2.0\",\r\n \"rxjs\": \"7.8.2\",\r\n \"uuid\": \"^11.1.0\"\r\n },\r\n \"license\": \"MIT\",\r\n \"files\": [\r\n \"README.md\",\r\n \"dist/src\",\r\n \"src\",\r\n \"package.json\"\r\n ],\r\n \"exports\": {\r\n \".\": {\r\n \"types\": \"./dist/src/index.d.ts\",\r\n \"import\": {\r\n \"browser\": \"./dist/src/browser.mjs\",\r\n \"default\": \"./dist/src/index.js\"\r\n },\r\n \"require\": {\r\n \"default\": \"./dist/src/index.js\"\r\n }\r\n },\r\n \"./package.json\": \"./package.json\"\r\n },\r\n \"engines\": {\r\n \"node\": \">=20.0.0\"\r\n }\r\n}\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport type * as osTypes from 'os'\r\n\r\nexport default {} as typeof osTypes\r\n", "/**\r\n * Copyright (c) Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License.\r\n */\r\n\r\nimport { createEventSource, EventSourceClient } from 'eventsource-client'\r\nimport { ConnectionSettings } from './connectionSettings'\r\nimport { getCopilotStudioConnectionUrl, getTokenAudience } from './powerPlatformEnvironment'\r\nimport { Activity, ActivityTypes, ConversationAccount } from '@microsoft/agents-activity'\r\nimport { ExecuteTurnRequest } from './executeTurnRequest'\r\nimport { debug } from '@microsoft/agents-activity/logger'\r\nimport { version } from '../package.json'\r\nimport os from 'os'\r\n\r\nconst logger = debug('copilot-studio:client')\r\n\r\n/**\r\n * Client for interacting with Microsoft Copilot Studio services.\r\n * Provides functionality to start conversations and send messages to Copilot Studio bots.\r\n */\r\nexport class CopilotStudioClient {\r\n /** Header key for conversation ID. */\r\n private static readonly conversationIdHeaderKey: string = 'x-ms-conversationid'\r\n /** Island Header key */\r\n private static readonly islandExperimentalUrlHeaderKey: string = 'x-ms-d2e-experimental'\r\n\r\n /** The ID of the current conversation. */\r\n private conversationId: string = ''\r\n /** The connection settings for the client. */\r\n private readonly settings: ConnectionSettings\r\n /** The authenticaton token. */\r\n private readonly token: string\r\n\r\n /**\r\n * Returns the scope URL needed to connect to Copilot Studio from the connection settings.\r\n * This is used for authentication token audience configuration.\r\n * @param settings Copilot Studio connection settings.\r\n * @returns The scope URL for token audience.\r\n */\r\n static scopeFromSettings: (settings: ConnectionSettings) => string = getTokenAudience\r\n\r\n /**\r\n * Creates an instance of CopilotStudioClient.\r\n * @param settings The connection settings.\r\n * @param token The authentication token.\r\n */\r\n constructor (settings: ConnectionSettings, token: string) {\r\n this.settings = settings\r\n this.token = token\r\n }\r\n\r\n /**\r\n * Streams activities from the Copilot Studio service using eventsource-client.\r\n * @param url The connection URL for Copilot Studio.\r\n * @param body Optional. The request body (for POST).\r\n * @param method Optional. The HTTP method (default: POST).\r\n * @returns An async generator yielding the Agent's Activities.\r\n */\r\n private async * postRequestAsync (url: string, body?: any, method: string = 'POST'): AsyncGenerator {\r\n logger.debug(`>>> SEND TO ${url}`)\r\n\r\n const eventSource: EventSourceClient = createEventSource({\r\n url,\r\n headers: {\r\n Authorization: `Bearer ${this.token}`,\r\n 'User-Agent': CopilotStudioClient.getProductInfo(),\r\n 'Content-Type': 'application/json',\r\n Accept: 'text/event-stream'\r\n },\r\n body: body ? JSON.stringify(body) : undefined,\r\n method,\r\n fetch: async (url, init) => {\r\n const response = await fetch(url, init)\r\n this.processResponseHeaders(response.headers)\r\n return response\r\n }\r\n })\r\n\r\n try {\r\n for await (const { data, event } of eventSource) {\r\n if (data && event === 'activity') {\r\n try {\r\n const activity = Activity.fromJson(data)\r\n switch (activity.type) {\r\n case ActivityTypes.Message:\r\n if (!this.conversationId.trim()) { // Did not get it from the header.\r\n this.conversationId = activity.conversation?.id ?? ''\r\n logger.debug(`Conversation ID: ${this.conversationId}`)\r\n }\r\n yield activity\r\n break\r\n default:\r\n logger.debug(`Activity type: ${activity.type}`)\r\n yield activity\r\n break\r\n }\r\n } catch (error) {\r\n logger.error('Failed to parse activity:', error)\r\n }\r\n } else if (event === 'end') {\r\n logger.debug('Stream complete')\r\n break\r\n }\r\n\r\n if (eventSource.readyState === 'closed') {\r\n logger.debug('Connection closed')\r\n break\r\n }\r\n }\r\n } finally {\r\n eventSource.close()\r\n }\r\n }\r\n\r\n /**\r\n * Appends this package.json version to the User-Agent header.\r\n * - For browser environments, it includes the user agent of the browser.\r\n * - For Node.js environments, it includes the Node.js version, platform, architecture, and release.\r\n * @returns A string containing the product information, including version and user agent.\r\n */\r\n private static getProductInfo (): string {\r\n const versionString = `CopilotStudioClient.agents-sdk-js/${version}`\r\n let userAgent: string\r\n\r\n if (typeof window !== 'undefined' && window.navigator) {\r\n userAgent = `${versionString} ${navigator.userAgent}`\r\n } else {\r\n userAgent = `${versionString} nodejs/${process.version} ${os.platform()}-${os.arch()}/${os.release()}`\r\n }\r\n\r\n logger.debug(`User-Agent: ${userAgent}`)\r\n return userAgent\r\n }\r\n\r\n private processResponseHeaders (responseHeaders: Headers): void {\r\n if (this.settings.useExperimentalEndpoint && !this.settings.directConnectUrl?.trim()) {\r\n const islandExperimentalUrl = responseHeaders?.get(CopilotStudioClient.islandExperimentalUrlHeaderKey)\r\n if (islandExperimentalUrl) {\r\n this.settings.directConnectUrl = islandExperimentalUrl\r\n logger.debug(`Island Experimental URL: ${islandExperimentalUrl}`)\r\n }\r\n }\r\n\r\n this.conversationId = responseHeaders?.get(CopilotStudioClient.conversationIdHeaderKey) ?? ''\r\n if (this.conversationId) {\r\n logger.debug(`Conversation ID: ${this.conversationId}`)\r\n }\r\n\r\n const sanitizedHeaders = new Headers()\r\n responseHeaders.forEach((value, key) => {\r\n if (key.toLowerCase() !== 'authorization' && key.toLowerCase() !== CopilotStudioClient.conversationIdHeaderKey.toLowerCase()) {\r\n sanitizedHeaders.set(key, value)\r\n }\r\n })\r\n logger.debug('Headers received:', sanitizedHeaders)\r\n }\r\n\r\n /**\r\n * Starts a new conversation with the Copilot Studio service.\r\n * @param emitStartConversationEvent Whether to emit a start conversation event. Defaults to true.\r\n * @returns An async generator yielding the Agent's Activities.\r\n */\r\n public async * startConversationAsync (emitStartConversationEvent: boolean = true): AsyncGenerator {\r\n const uriStart: string = getCopilotStudioConnectionUrl(this.settings)\r\n const body = { emitStartConversationEvent }\r\n\r\n logger.info('Starting conversation ...')\r\n\r\n yield * this.postRequestAsync(uriStart, body, 'POST')\r\n }\r\n\r\n /**\r\n * Sends a question to the Copilot Studio service and retrieves the response activities.\r\n * @param question The question to ask.\r\n * @param conversationId The ID of the conversation. Defaults to the current conversation ID.\r\n * @returns An async generator yielding the Agent's Activities.\r\n */\r\n public async * askQuestionAsync (question: string, conversationId: string = this.conversationId) : AsyncGenerator {\r\n const conversationAccount: ConversationAccount = {\r\n id: conversationId\r\n }\r\n const activityObj = {\r\n type: 'message',\r\n text: question,\r\n conversation: conversationAccount\r\n }\r\n const activity = Activity.fromObject(activityObj)\r\n\r\n yield * this.sendActivity(activity)\r\n }\r\n\r\n /**\r\n * Sends an activity to the Copilot Studio service and retrieves the response activities.\r\n * @param activity The activity to send.\r\n * @param conversationId The ID of the conversation. Defaults to the current conversation ID.\r\n * @returns An async generator yielding the Agent's Activities.\r\n */\r\n public async * sendActivity (activity: Activity, conversationId: string = this.conversationId) : AsyncGenerator {\r\n const localConversationId = activity.conversation?.id ?? conversationId\r\n const uriExecute = getCopilotStudioConnectionUrl(this.settings, localConversationId)\r\n const qbody: ExecuteTurnRequest = new ExecuteTurnRequest(activity)\r\n\r\n logger.info('Sending activity...', activity)\r\n yield * this.postRequestAsync(uriExecute, qbody, 'POST')\r\n }\r\n}\r\n", "/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n", "/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n */\nexport class Subscription implements SubscriptionLike {\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n", "import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification, subscriber: Subscriber) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n", "import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n", "/* tslint:disable:no-empty */\nexport function noop() { }\n", "import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification(value: T) {\n return createNotification('N', value, undefined) as NextNotification;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n", "import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n */\nexport class Subscriber extends Subscription implements Observer {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber | Observer; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber | Observer) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param value The `next` value.\n */\n next(value: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param err The `error` exception.\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver implements Observer {\n constructor(private partialObserver: Partial>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber extends Subscriber {\n constructor(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent.\n * @param subscriber The stopped subscriber.\n */\nfunction handleStoppedNotification(notification: ObservableNotification, subscriber: Subscriber) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n", "/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n", "/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity(x: T): T {\n return x;\n}\n", "import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe(fn1: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction): UnaryFunction;\nexport function pipe(fn1: UnaryFunction, fn2: UnaryFunction, fn3: UnaryFunction): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction\n): UnaryFunction;\nexport function pipe(\n fn1: UnaryFunction,\n fn2: UnaryFunction,\n fn3: UnaryFunction,\n fn4: UnaryFunction,\n fn5: UnaryFunction,\n fn6: UnaryFunction,\n fn7: UnaryFunction,\n fn8: UnaryFunction,\n fn9: UnaryFunction,\n ...fns: UnaryFunction[]\n): UnaryFunction;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array>): UnaryFunction {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray(fns: Array>): UnaryFunction {\n if (fns.length === 0) {\n return identity as UnaryFunction;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction) => fn(prev), input as any);\n };\n}\n", "import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n */\nexport class Observable implements Subscribable {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator | undefined;\n\n /**\n * @param subscribe The function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable, subscriber: Subscriber) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @param subscribe the subscriber function to be passed to the Observable constructor\n * @return A new observable.\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = (subscribe?: (subscriber: Subscriber) => TeardownLogic) => {\n return new Observable(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @param operator the operator defining the operation to take on the observable\n * @return A new observable with the Operator applied.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift(operator?: Operator): Observable {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * Use it when you have all these Observables, but still nothing is happening.\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param observerOrNext Either an {@link Observer} with some or all callback methods,\n * or the `next` handler that is called for each value emitted from the subscribed Observable.\n * @param error A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param complete A handler for a terminal event resulting from successful completion.\n * @return A subscription reference to the registered handlers.\n */\n subscribe(\n observerOrNext?: Partial> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next A handler for each value emitted by the observable.\n * @return A promise that either resolves on observable completion or\n * rejects with the handled error.\n */\n forEach(next: (value: T) => void): Promise;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @return This instance of the observable.\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable;\n pipe(op1: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction): Observable;\n pipe(op1: OperatorFunction, op2: OperatorFunction, op3: OperatorFunction): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction\n ): Observable;\n pipe(\n op1: OperatorFunction,\n op2: OperatorFunction,\n op3: OperatorFunction,\n op4: OperatorFunction,\n op5: OperatorFunction,\n op6: OperatorFunction,\n op7: OperatorFunction,\n op8: OperatorFunction,\n op9: OperatorFunction,\n ...operations: OperatorFunction[]\n ): Observable;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n *\n * @return The Observable result of all the operators having been called\n * in the order they were passed in.\n */\n pipe(...operations: OperatorFunction[]): Observable {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver(value: any): value is Observer {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber(value: any): value is Subscriber {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate(\n init: (liftedSource: Observable, subscriber: Subscriber) => (() => void) | void\n): OperatorFunction {\n return (source: Observable) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber, liftedSource: Observable) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n", "import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber extends Subscriber {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n", "import { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Make a {@link ConnectableObservable} behave like a ordinary observable and automates the way\n * you can connect to it.\n *\n * Internally it counts the subscriptions to the observable and subscribes (only once) to the source if\n * the number of subscriptions is larger than 0. If the number of subscriptions is smaller than 1, it\n * unsubscribes from the source. This way you can make sure that everything before the *published*\n * refCount has only a single subscription independently of the number of subscribers to the target\n * observable.\n *\n * Note that using the {@link share} operator is exactly the same as using the `multicast(() => new Subject())` operator\n * (making the observable hot) and the *refCount* operator in a sequence.\n *\n * ![](refCount.png)\n *\n * ## Example\n *\n * In the following example there are two intervals turned into connectable observables\n * by using the *publish* operator. The first one uses the *refCount* operator, the\n * second one does not use it. You will notice that a connectable observable does nothing\n * until you call its connect function.\n *\n * ```ts\n * import { interval, tap, publish, refCount } from 'rxjs';\n *\n * // Turn the interval observable into a ConnectableObservable (hot)\n * const refCountInterval = interval(400).pipe(\n * tap(num => console.log(`refCount ${ num }`)),\n * publish(),\n * refCount()\n * );\n *\n * const publishedInterval = interval(400).pipe(\n * tap(num => console.log(`publish ${ num }`)),\n * publish()\n * );\n *\n * refCountInterval.subscribe();\n * refCountInterval.subscribe();\n * // 'refCount 0' -----> 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the `publish` operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @return A function that returns an Observable that automates the connection\n * to ConnectableObservable.\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n * @deprecated Replaced with the {@link share} operator. How `share` is used\n * will depend on the connectable observable you created just prior to the\n * `refCount` operator.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function refCount(): MonoTypeOperatorFunction {\n return operate((source, subscriber) => {\n let connection: Subscription | null = null;\n\n (source as any)._refCount++;\n\n const refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, () => {\n if (!source || (source as any)._refCount <= 0 || 0 < --(source as any)._refCount) {\n connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // )\n // .subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n\n const sharedConnection = (source as any)._connection;\n const conn = connection;\n connection = null;\n\n if (sharedConnection && (!conn || sharedConnection === conn)) {\n sharedConnection.unsubscribe();\n }\n\n subscriber.unsubscribe();\n });\n\n source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n connection = (source as ConnectableObservable).connect();\n }\n });\n}\n", "import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { hasLift } from '../util/lift';\n\n/**\n * @class ConnectableObservable\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * If you are using the `refCount` method of `ConnectableObservable`, use the {@link share} operator\n * instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport class ConnectableObservable extends Observable {\n protected _subject: Subject | null = null;\n protected _refCount: number = 0;\n protected _connection: Subscription | null = null;\n\n /**\n * @param source The source observable\n * @param subjectFactory The factory that creates the subject used internally.\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * `new ConnectableObservable(source, factory)` is equivalent to\n * `connectable(source, { connector: factory })`.\n * When the `refCount()` method is needed, the {@link share} operator should be used instead:\n * `new ConnectableObservable(source, factory).refCount()` is equivalent to\n * `source.pipe(share({ connector: factory }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n constructor(public source: Observable, protected subjectFactory: () => Subject) {\n super();\n // If we have lift, monkey patch that here. This is done so custom observable\n // types will compose through multicast. Otherwise the resulting observable would\n // simply be an instance of `ConnectableObservable`.\n if (hasLift(source)) {\n this.lift = source.lift;\n }\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber) {\n return this.getSubject().subscribe(subscriber);\n }\n\n protected getSubject(): Subject {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject!;\n }\n\n protected _teardown() {\n this._refCount = 0;\n const { _connection } = this;\n this._subject = this._connection = null;\n _connection?.unsubscribe();\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use {@link connectable} instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n connect(): Subscription {\n let connection = this._connection;\n if (!connection) {\n connection = this._connection = new Subscription();\n const subject = this.getSubject();\n connection.add(\n this.source.subscribe(\n createOperatorSubscriber(\n subject as any,\n undefined,\n () => {\n this._teardown();\n subject.complete();\n },\n (err) => {\n this._teardown();\n subject.error(err);\n },\n () => this._teardown()\n )\n )\n );\n\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use the {@link share} operator instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n refCount(): Observable {\n return higherOrderRefCount()(this) as Observable;\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface PerformanceTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const performanceTimestampProvider: PerformanceTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (performanceTimestampProvider.delegate || performance).now();\n },\n delegate: undefined,\n};\n", "import { Subscription } from '../Subscription';\n\ninterface AnimationFrameProvider {\n schedule(callback: FrameRequestCallback): Subscription;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n delegate:\n | {\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n }\n | undefined;\n}\n\nexport const animationFrameProvider: AnimationFrameProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n schedule(callback) {\n let request = requestAnimationFrame;\n let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame;\n const { delegate } = animationFrameProvider;\n if (delegate) {\n request = delegate.requestAnimationFrame;\n cancel = delegate.cancelAnimationFrame;\n }\n const handle = request((timestamp) => {\n // Clear the cancel function. The request has been fulfilled, so\n // attempting to cancel the request upon unsubscription would be\n // pointless.\n cancel = undefined;\n callback(timestamp);\n });\n return new Subscription(() => cancel?.(handle));\n },\n requestAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args);\n },\n cancelAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args);\n },\n delegate: undefined,\n};\n", "import { Observable } from '../../Observable';\nimport { TimestampProvider } from '../../types';\nimport { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';\nimport { animationFrameProvider } from '../../scheduler/animationFrameProvider';\n\n/**\n * An observable of animation frames\n *\n * Emits the amount of time elapsed since subscription and the timestamp on each animation frame.\n * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.\n *\n * Every subscription will start a separate animation loop. Since animation frames are always scheduled\n * by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously\n * should not be much different or have more overhead than looping over an array of events during\n * a single animation frame. However, if for some reason the developer would like to ensure the\n * execution of animation-related handlers are all executed during the same task by the engine,\n * the `share` operator can be used.\n *\n * This is useful for setting up animations with RxJS.\n *\n * ## Examples\n *\n * Tweening a div to move it on the screen\n *\n * ```ts\n * import { animationFrames, map, takeWhile, endWith } from 'rxjs';\n *\n * function tween(start: number, end: number, duration: number) {\n * const diff = end - start;\n * return animationFrames().pipe(\n * // Figure out what percentage of time has passed\n * map(({ elapsed }) => elapsed / duration),\n * // Take the vector while less than 100%\n * takeWhile(v => v < 1),\n * // Finish with 100%\n * endWith(1),\n * // Calculate the distance traveled between start and end\n * map(v => v * diff + start)\n * );\n * }\n *\n * // Setup a div for us to move around\n * const div = document.createElement('div');\n * document.body.appendChild(div);\n * div.style.position = 'absolute';\n * div.style.width = '40px';\n * div.style.height = '40px';\n * div.style.backgroundColor = 'lime';\n * div.style.transform = 'translate3d(10px, 0, 0)';\n *\n * tween(10, 200, 4000).subscribe(x => {\n * div.style.transform = `translate3d(${ x }px, 0, 0)`;\n * });\n * ```\n *\n * Providing a custom timestamp provider\n *\n * ```ts\n * import { animationFrames, TimestampProvider } from 'rxjs';\n *\n * // A custom timestamp provider\n * let now = 0;\n * const customTSProvider: TimestampProvider = {\n * now() { return now++; }\n * };\n *\n * const source$ = animationFrames(customTSProvider);\n *\n * // Log increasing numbers 0...1...2... on every animation frame.\n * source$.subscribe(({ elapsed }) => console.log(elapsed));\n * ```\n *\n * @param timestampProvider An object with a `now` method that provides a numeric timestamp\n */\nexport function animationFrames(timestampProvider?: TimestampProvider) {\n return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;\n}\n\n/**\n * Does the work of creating the observable for `animationFrames`.\n * @param timestampProvider The timestamp provider to use to create the observable\n */\nfunction animationFramesFactory(timestampProvider?: TimestampProvider) {\n return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {\n // If no timestamp provider is specified, use performance.now() - as it\n // will return timestamps 'compatible' with those passed to the run\n // callback and won't be affected by NTP adjustments, etc.\n const provider = timestampProvider || performanceTimestampProvider;\n\n // Capture the start time upon subscription, as the run callback can remain\n // queued for a considerable period of time and the elapsed time should\n // represent the time elapsed since subscription - not the time since the\n // first rendered animation frame.\n const start = provider.now();\n\n let id = 0;\n const run = () => {\n if (!subscriber.closed) {\n id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {\n id = 0;\n // Use the provider's timestamp to calculate the elapsed time. Note that\n // this means - if the caller hasn't passed a provider - that\n // performance.now() will be used instead of the timestamp that was\n // passed to the run callback. The reason for this is that the timestamp\n // passed to the callback can be earlier than the start time, as it\n // represents the time at which the browser decided it would render any\n // queued frames - and that time can be earlier the captured start time.\n const now = provider.now();\n subscriber.next({\n timestamp: timestampProvider ? now : timestamp,\n elapsed: now - start,\n });\n run();\n });\n }\n };\n\n run();\n\n return () => {\n if (id) {\n animationFrameProvider.cancelAnimationFrame(id);\n }\n };\n });\n}\n\n/**\n * In the common case, where the timestamp provided by the rAF API is used,\n * we use this shared observable to reduce overhead.\n */\nconst DEFAULT_ANIMATION_FRAMES = animationFramesFactory();\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n", "import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject extends Observable implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = (destination: Observer, source: Observable): AnonymousSubject => {\n return new AnonymousSubject(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift(operator: Operator): Observable {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return Observable that this Subject casts to.\n */\n asObservable(): Observable {\n const observable: any = new Observable();\n observable.source = this;\n return observable;\n }\n}\n\nexport class AnonymousSubject extends Subject {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer,\n source?: Observable\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n", "import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n */\nexport class BehaviorSubject extends Subject {\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n\n getValue(): T {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n\n next(value: T): void {\n super.next((this._value = value));\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n", "import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject extends Subject {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param _bufferSize The size of the buffer to replay on subscription\n * @param _windowTime The amount of time the buffered items will stay buffered\n * @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n", "import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n */\nexport class AsyncSubject extends Subject {\n private _value: T | null = null;\n private _hasValue = false;\n private _isComplete = false;\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber) {\n const { hasError, _hasValue, _value, thrownError, isStopped, _isComplete } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped || _isComplete) {\n _hasValue && subscriber.next(_value!);\n subscriber.complete();\n }\n }\n\n next(value: T): void {\n if (!this.isStopped) {\n this._value = value;\n this._hasValue = true;\n }\n }\n\n complete(): void {\n const { _hasValue, _value, _isComplete } = this;\n if (!_isComplete) {\n this._isComplete = true;\n _hasValue && super.next(_value!);\n super.complete();\n }\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n */\nexport class Action extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param state Some contextual data that the `work` function uses when called by the\n * Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is implicit\n * and defined by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetIntervalFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearIntervalFunction = (handle: TimerHandle) => void;\n\ninterface IntervalProvider {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n delegate:\n | {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n }\n | undefined;\n}\n\nexport const intervalProvider: IntervalProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setInterval(handler: () => void, timeout?: number, ...args) {\n const { delegate } = intervalProvider;\n if (delegate?.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return (delegate?.clearInterval || clearInterval)(handle as any);\n },\n delegate: undefined,\n};\n", "import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncAction extends Action {\n public id: TimerHandle | undefined;\n public state?: T;\n // @ts-ignore: Property has no initializer and is not definitely assigned\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n */\n public execute(state: T, delay: number): any {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, _delay: number): any {\n let errored: boolean = false;\n let errorValue: any;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n // HACK: Since code elsewhere is relying on the \"truthiness\" of the\n // return here, we can't have it return \"\" or 0 or false.\n // TODO: Clean this up when we refactor schedulers mid-version-8 or so.\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n\n this.work = this.state = this.scheduler = null!;\n this.pending = false;\n\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null!;\n super.unsubscribe();\n }\n }\n}\n", "let nextHandle = 1;\n// The promise needs to be created lazily otherwise it won't be patched by Zones\nlet resolved: Promise;\nconst activeHandles: { [key: number]: any } = {};\n\n/**\n * Finds the handle in the list of active handles, and removes it.\n * Returns `true` if found, `false` otherwise. Used both to clear\n * Immediate scheduled tasks, and to identify if a task should be scheduled.\n */\nfunction findAndClearHandle(handle: number): boolean {\n if (handle in activeHandles) {\n delete activeHandles[handle];\n return true;\n }\n return false;\n}\n\n/**\n * Helper functions to schedule and unschedule microtasks.\n */\nexport const Immediate = {\n setImmediate(cb: () => void): number {\n const handle = nextHandle++;\n activeHandles[handle] = true;\n if (!resolved) {\n resolved = Promise.resolve();\n }\n resolved.then(() => findAndClearHandle(handle) && cb());\n return handle;\n },\n\n clearImmediate(handle: number): void {\n findAndClearHandle(handle);\n },\n};\n\n/**\n * Used for internal testing purposes only. Do not export from library.\n */\nexport const TestTools = {\n pending() {\n return Object.keys(activeHandles).length;\n }\n};\n", "import { Immediate } from '../util/Immediate';\nimport type { TimerHandle } from './timerHandle';\nconst { setImmediate, clearImmediate } = Immediate;\n\ntype SetImmediateFunction = (handler: () => void, ...args: any[]) => TimerHandle;\ntype ClearImmediateFunction = (handle: TimerHandle) => void;\n\ninterface ImmediateProvider {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n delegate:\n | {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n }\n | undefined;\n}\n\nexport const immediateProvider: ImmediateProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setImmediate(...args) {\n const { delegate } = immediateProvider;\n return (delegate?.setImmediate || setImmediate)(...args);\n },\n clearImmediate(handle) {\n const { delegate } = immediateProvider;\n return (delegate?.clearImmediate || clearImmediate)(handle as any);\n },\n delegate: undefined,\n};\n", "import { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\nimport { immediateProvider } from './immediateProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsapAction extends AsyncAction {\n constructor(protected scheduler: AsapScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If a microtask has already been scheduled, don't schedule another\n // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n // the current scheduled microtask id.\n return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));\n }\n\n protected recycleAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested microtask and set the scheduled flag to undefined\n // so the next AsapAction will request its own.\n const { actions } = scheduler;\n if (id != null && actions[actions.length - 1]?.id !== id) {\n immediateProvider.clearImmediate(id);\n if (scheduler._scheduled === id) {\n scheduler._scheduled = undefined;\n }\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n", "import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}. Will be made internal in v8.\n */\nexport class Scheduler implements SchedulerLike {\n public static now: () => number = dateTimestampProvider.now;\n\n constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param work A function representing a task, or some unit of work to be\n * executed by the Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is\n * implicit and defined by the Scheduler itself.\n * @param state Some contextual data that the `work` function uses when called\n * by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(work: (this: SchedulerAction, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.schedulerActionCtor(this, work).schedule(state, delay);\n }\n}\n", "import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncScheduler extends Scheduler {\n public actions: Array> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @internal\n */\n public _active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @internal\n */\n public _scheduled: TimerHandle | undefined;\n\n constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {\n super(SchedulerAction, now);\n }\n\n public flush(action: AsyncAction): void {\n const { actions } = this;\n\n if (this._active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this._active = true;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()!)); // exhaust the scheduler queue\n\n this._active = false;\n\n if (error) {\n while ((action = actions.shift()!)) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n const flushId = this._scheduled;\n this._scheduled = undefined;\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * Perform task as fast as it can be performed asynchronously\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n */\n\nexport const asapScheduler = new AsapScheduler(AsapAction);\n\n/**\n * @deprecated Renamed to {@link asapScheduler}. Will be removed in v8.\n */\nexport const asap = asapScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * Schedule task as if you used setTimeout(task, duration)\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\n\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated Renamed to {@link asyncScheduler}. Will be removed in v8.\n */\nexport const async = asyncScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class QueueAction extends AsyncAction {\n constructor(protected scheduler: QueueScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n\n // Otherwise flush the scheduler starting with this action.\n scheduler.flush(this);\n\n // HACK: In the past, this was returning `void`. However, `void` isn't a valid\n // `TimerHandle`, and generally the return value here isn't really used. So the\n // compromise is to return `0` which is both \"falsy\" and a valid `TimerHandle`,\n // as opposed to refactoring every other instanceo of `requestAsyncId`.\n return 0;\n }\n}\n", "import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n", "import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * Put every next task on a queue, instead of executing it immediately\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\n\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated Renamed to {@link queueScheduler}. Will be removed in v8.\n */\nexport const queue = queueScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\nimport { animationFrameProvider } from './animationFrameProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AnimationFrameAction extends AsyncAction {\n constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));\n }\n\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested animation frame and set the scheduled flag to\n // undefined so the next AnimationFrameAction will request its own.\n const { actions } = scheduler;\n if (id != null && id === scheduler._scheduled && actions[actions.length - 1]?.id !== id) {\n animationFrameProvider.cancelAnimationFrame(id as number);\n scheduler._scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n", "import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n let flushId;\n if (action) {\n flushId = action.id;\n } else {\n flushId = this._scheduled;\n this._scheduled = undefined;\n }\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n", "import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * Perform task when `window.requestAnimationFrame` would fire\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html:
\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\n\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated Renamed to {@link animationFrameScheduler}. Will be removed in v8.\n */\nexport const animationFrame = animationFrameScheduler;\n", "import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n /** @deprecated Not used in VirtualTimeScheduler directly. Will be removed in v8. */\n static frameTimeFactor = 10;\n\n /**\n * The current frame for the state of the virtual scheduler instance. The difference\n * between two \"frames\" is synonymous with the passage of \"virtual time units\". So if\n * you record `scheduler.frame` to be `1`, then later, observe `scheduler.frame` to be at `11`,\n * that means `10` virtual time units have passed.\n */\n public frame: number = 0;\n\n /**\n * Used internally to examine the current virtual action index being processed.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n public index: number = -1;\n\n /**\n * This creates an instance of a `VirtualTimeScheduler`. Experts only. The signature of\n * this constructor is likely to change in the long run.\n *\n * @param schedulerActionCtor The type of Action to initialize when initializing actions during scheduling.\n * @param maxFrames The maximum number of frames to process before stopping. Used to prevent endless flush cycles.\n */\n constructor(schedulerActionCtor: typeof AsyncAction = VirtualAction as any, public maxFrames: number = Infinity) {\n super(schedulerActionCtor, () => this.frame);\n }\n\n /**\n * Prompt the Scheduler to execute all of its queued actions, therefore\n * clearing its queue.\n */\n public flush(): void {\n const { actions, maxFrames } = this;\n let error: any;\n let action: AsyncAction | undefined;\n\n while ((action = actions[0]) && action.delay <= maxFrames) {\n actions.shift();\n this.frame = action.delay;\n\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n }\n\n if (error) {\n while ((action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n\nexport class VirtualAction extends AsyncAction {\n protected active: boolean = true;\n\n constructor(\n protected scheduler: VirtualTimeScheduler,\n protected work: (this: SchedulerAction, state?: T) => void,\n protected index: number = (scheduler.index += 1)\n ) {\n super(scheduler, work);\n this.index = scheduler.index = index;\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (Number.isFinite(delay)) {\n if (!this.id) {\n return super.schedule(state, delay);\n }\n this.active = false;\n // If an action is rescheduled, we save allocations by mutating its state,\n // pushing it to the end of the scheduler queue, and recycling the action.\n // But since the VirtualTimeScheduler is used for testing, VirtualActions\n // must be immutable so they can be inspected later.\n const action = new VirtualAction(this.scheduler, this.work);\n this.add(action);\n return action.schedule(state, delay);\n } else {\n // If someone schedules something with Infinity, it'll never happen. So we\n // don't even schedule it.\n return Subscription.EMPTY;\n }\n }\n\n protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle {\n this.delay = scheduler.frame + delay;\n const { actions } = scheduler;\n actions.push(this);\n (actions as Array>).sort(VirtualAction.sortActions);\n return 1;\n }\n\n protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle | undefined {\n return undefined;\n }\n\n protected _execute(state: T, delay: number): any {\n if (this.active === true) {\n return super._execute(state, delay);\n }\n }\n\n private static sortActions(a: VirtualAction, b: VirtualAction) {\n if (a.delay === b.delay) {\n if (a.index === b.index) {\n return 0;\n } else if (a.index > b.index) {\n return 1;\n } else {\n return -1;\n }\n } else if (a.delay > b.delay) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * Just emits 'complete', and nothing else.\n *\n * ![](empty.png)\n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n", "export const isArrayLike = ((x: any): x is ArrayLike => x && typeof x.length === 'number' && typeof x !== 'function');", "import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike {\n return isFunction(value?.then);\n}\n", "import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable {\n return isFunction(input[Symbol_observable]);\n}\n", "import { isFunction } from './isFunction';\n\nexport function isAsyncIterable(obj: any): obj is AsyncIterable {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n", "/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n", "export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n", "import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable {\n return isFunction(input?.[Symbol_iterator]);\n}\n", "import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator(readableStream: ReadableStreamLike): AsyncGenerator {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike(obj: any): obj is ReadableStreamLike {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an