@mcpjam/cli 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/evals/index.ts","../src/utils/logger.ts","../src/evals/runner.ts","../../node_modules/convex/src/index.ts","../../node_modules/convex/src/values/base64.ts","../../node_modules/convex/src/common/index.ts","../../node_modules/convex/src/values/value.ts","../../node_modules/convex/src/values/validators.ts","../../node_modules/convex/src/values/validator.ts","../../node_modules/convex/src/values/errors.ts","../../node_modules/convex/src/values/compare_utf8.ts","../../node_modules/convex/src/browser/logging.ts","../../node_modules/convex/src/server/functionName.ts","../../node_modules/convex/src/server/components/paths.ts","../../node_modules/convex/src/server/api.ts","../../node_modules/convex/src/browser/long.ts","../../node_modules/jwt-decode/build/esm/index.js","../../node_modules/convex/src/browser/sync/authentication_manager.ts","../../node_modules/convex/src/browser/http_client.ts","../../node_modules/convex/src/browser/simple_client.ts","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js","../../node_modules/common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js","../../node_modules/common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js","../../node_modules/common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js","../../node_modules/common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js","../../node_modules/common/temp/node_modules/.pnpm/utf-8-validate@5.0.10/node_modules/utf-8-validate/fallback.js","../../node_modules/common/temp/node_modules/.pnpm/utf-8-validate@5.0.10/node_modules/utf-8-validate/index.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js","../../node_modules/convex/src/browser/simple_client-node.ts","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/wrapper.mjs","../src/db/index.ts","../../node_modules/convex/src/server/pagination.ts","../../node_modules/convex/src/server/schema.ts","../_generated/api.js","../src/db/user.ts","../src/utils/validators.ts","../src/utils/helpers.ts","../src/evals/evaluator.ts","../package.json"],"sourcesContent":["import { config } from \"dotenv\";\nimport { Command } from \"commander\";\nimport { createRequire } from \"module\";\nimport { evalsCommand } from \"./evals/index\";\nimport updateNotifier from \"update-notifier\";\nimport packageJson from '../package.json' assert {type: 'json'};\nconst require = createRequire(import.meta.url);\n\nupdateNotifier({pkg: packageJson, updateCheckInterval: 0}).notify();\n\nconst { name, version } = require(\"../package.json\") as {\n name: string;\n version: string;\n};\n\nupdateNotifier({ pkg: { name, version } }).notify();\n\nconfig();\n\nconst program = new Command();\n\nprogram\n .name(\"mcpjam\")\n .description(\"MCPJam CLI for programmatic MCP testing\")\n .version(version);\n\nprogram.addCommand(evalsCommand);\n\nprogram.parse();\n","import { Command } from \"commander\";\nimport { readFile } from \"fs/promises\";\nimport { resolve } from \"path\";\nimport { Logger } from \"../utils/logger.js\";\nimport { runEvals } from \"./runner.js\";\n\n// node dist/index.js evals run -t examples/test-servers.json -e examples/mcp-environment.json\n\nexport const evalsCommand = new Command(\"evals\");\n\nevalsCommand\n .description(\"Run MCP evaluations\")\n .command(\"run\")\n .description(\"Run tests against MCP servers\")\n .requiredOption(\"-t, --tests <file>\", \"Path to tests JSON file\")\n .requiredOption(\"-e, --environment <file>\", \"Path to environment JSON file\")\n .requiredOption(\"-l, --llms <file>\", \"Path to LLMs JSON file\")\n .option(\"-a, --api-key <key>\", \"Personal access key\")\n .action(async (options) => {\n try {\n // Read and parse test file\n const testsContent = await readFile(resolve(options.tests), \"utf8\");\n const testsData = JSON.parse(testsContent);\n\n // Read and parse environment file\n const envContent = await readFile(resolve(options.environment), \"utf8\");\n const envData = JSON.parse(envContent);\n\n // Read and parse LLMs file\n const llmsContent = await readFile(resolve(options.llms), \"utf8\");\n const llmsData = JSON.parse(llmsContent);\n\n // Read API token (optional)\n const apiKey = options.apiKey;\n runEvals(testsData, envData, llmsData, apiKey);\n } catch (error) {\n Logger.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n","import chalk from \"chalk\";\nimport type { ModelMessage } from \"ai\";\n\ntype MessageContent = string | Record<string, unknown> | MessageContent[];\n\ntype ToolSummaryResult = {\n missing: string[];\n unexpected: string[];\n passed: boolean;\n};\n\ntype ToolSummaryOptions = {\n expected: string[];\n actual: string[];\n passed: boolean;\n missing?: string[];\n unexpected?: string[];\n indentLevel?: number;\n};\n\ntype ConversationOptions = {\n messages: ModelMessage[];\n indentLevel?: number;\n};\n\ntype ToolCallSummary = {\n toolName: string;\n args?: string;\n};\n\ntype RunResultOptions = {\n passed: boolean;\n durationMs: number;\n indentLevel?: number;\n};\n\ntype RunStartOptions = {\n runNumber: number;\n totalRuns: number;\n provider?: string;\n model?: string;\n temperature?: number;\n indentLevel?: number;\n};\n\nconst MAX_CONTENT_LENGTH = 160;\n\nexport class Logger {\n private static activeStream:\n | { role: ModelMessage[\"role\"]; indentLevel: number }\n | null = null;\n\n private static closeActiveStream(): void {\n if (this.activeStream) {\n process.stdout.write(\"\\n\");\n this.activeStream = null;\n }\n }\n\n private static startStream(\n role: ModelMessage[\"role\"],\n indentLevel: number,\n ): void {\n this.closeActiveStream();\n const prefix = \" \".repeat(indentLevel) + this.colorRole(role) + \": \";\n process.stdout.write(prefix);\n this.activeStream = { role, indentLevel };\n }\n\n private static appendToStream(text: string): void {\n if (!this.activeStream) {\n this.startStream(\"assistant\", 2);\n }\n process.stdout.write(text);\n }\n\n private static logLine(text: string, indentLevel = 0): void {\n this.closeActiveStream();\n const prefix = \" \".repeat(indentLevel);\n console.log(prefix + text);\n }\n\n private static logMultiline(text: string, indentLevel = 0): void {\n text\n .split(\"\\n\")\n .forEach((line) => this.logLine(line, indentLevel));\n }\n\n static suiteIntro(options: { testCount: number; startedAt: Date }): void {\n const { testCount, startedAt } = options;\n this.logLine(\n chalk.bold.blue(\n `▸ Running ${testCount} test${testCount === 1 ? \"\" : \"s\"} (${startedAt.toISOString()})`,\n ),\n );\n }\n\n static suiteComplete(options: {\n durationMs: number;\n passed: number;\n failed: number;\n }): void {\n const { durationMs, passed, failed } = options;\n const total = passed + failed;\n const summary = `${passed}/${total} passed • ${this.formatDuration(durationMs)}`;\n const prefix = failed === 0 ? chalk.green(\"✔\") : chalk.red(\"✖\");\n this.logLine(`${prefix} ${summary}`);\n }\n\n static header(version: string): void {\n this.logLine(chalk.bold.blue(`MCPJAM CLI ${version}`));\n this.logLine(\"\");\n }\n\n static serverConnection(serverCount: number, toolCount: number): void {\n this.logLine(\n chalk.gray(\n `Connecting to ${serverCount} server${serverCount === 1 ? \"\" : \"s\"} and ${toolCount} tool${toolCount === 1 ? \"\" : \"s\"}`,\n ),\n );\n }\n\n static startTests(count: number): void {\n this.logLine(chalk.gray(`Running ${count} test${count === 1 ? \"\" : \"s\"}...`));\n this.logLine(\"\");\n }\n\n static testTitle(testName: string): void {\n this.logLine(chalk.white.bold(`• ${testName}`));\n }\n\n static testRunStart(options: RunStartOptions): void {\n const { runNumber, totalRuns, provider, model, temperature, indentLevel = 1 } = options;\n const parts = [`run ${runNumber}/${totalRuns}`];\n if (provider && model) {\n parts.push(`${provider}:${model}`);\n }\n if (typeof temperature === \"number\") {\n parts.push(`temp=${temperature}`);\n }\n this.logLine(chalk.gray(parts.join(\" • \")), indentLevel);\n }\n\n static conversation(options: ConversationOptions): void {\n const { messages, indentLevel = 2 } = options;\n\n this.closeActiveStream();\n\n if (!messages.length) {\n this.logLine(chalk.dim(\"(no messages)\"), indentLevel);\n return;\n }\n\n messages.forEach((message, index) => {\n if (index > 0) {\n this.closeActiveStream();\n console.log(\"\");\n }\n\n const role = this.colorRole(message.role);\n\n if (message.role === \"assistant\") {\n const summary = this.summarizeContent(\n message.content as MessageContent,\n );\n this.logMessageLines(role, summary.textLines, indentLevel);\n summary.toolCalls.forEach((toolCall) => {\n this.logToolCall(toolCall, indentLevel + 1);\n });\n return;\n }\n\n const content = this.formatMessageContent(\n message.content as MessageContent,\n );\n const lines = content.split(\"\\n\");\n this.logMessageLines(role, lines, indentLevel);\n });\n }\n\n static toolSummary(options: ToolSummaryOptions): ToolSummaryResult {\n const { expected, actual, passed, missing: providedMissing, unexpected: providedUnexpected, indentLevel = 2 } = options;\n\n const missing = providedMissing ?? expected.filter((tool) => !actual.includes(tool));\n const unexpected = providedUnexpected ?? actual.filter((tool) => !expected.includes(tool));\n\n const lines: string[] = [];\n lines.push(\n this.truncate(`Expected: [${expected.join(\", \") || \"—\"}]`),\n );\n lines.push(\n this.truncate(`Actual: [${actual.join(\", \") || \"—\"}]`),\n );\n\n if (missing.length) {\n lines.push(this.truncate(`Missing: ${missing.join(\", \")}`));\n }\n\n if (unexpected.length) {\n lines.push(this.truncate(`Unexpected: ${unexpected.join(\", \")}`));\n }\n\n const statusText = passed ? \"Status: PASS\" : \"Status: FAIL\";\n lines.push(statusText);\n\n const borderColor = passed ? chalk.greenBright : chalk.redBright;\n const statusColor = passed ? chalk.green : chalk.red;\n this.renderBox(lines, {\n borderColor,\n statusColor,\n indentLevel,\n });\n\n return { missing, unexpected, passed };\n }\n\n static testRunResult(options: RunResultOptions): void {\n const { passed, durationMs, indentLevel = 2 } = options;\n const status = passed ? chalk.green(\"PASS\") : chalk.red(\"FAIL\");\n this.logLine(`${status} (${this.formatDuration(durationMs)})`, indentLevel);\n }\n\n static info(message: string): void {\n this.logLine(chalk.blue(`ℹ ${message}`));\n }\n\n static success(message: string): void {\n this.logLine(chalk.green(`✓ ${message}`));\n }\n\n static error(message: string): void {\n this.logLine(\"\");\n this.logLine(chalk.red(`✕ Error: ${message}`));\n }\n\n static progress(current: number, total: number, testName: string): void {\n const progress = `[${current}/${total}]`;\n this.logLine(chalk.gray(`${progress} ${testName}...`));\n }\n\n static testStarting(testName: string): void {\n this.logLine(chalk.gray(` Running ${testName}...`));\n }\n\n static testError(testName: string, error: string): void {\n this.logLine(chalk.red(` ✕ ${testName} failed: ${error}`));\n }\n\n static connectionError(serverName: string, error: string): void {\n this.logLine(chalk.red(` ✕ Failed to connect to ${serverName}: ${error}`));\n }\n\n static apiKeyError(provider: string, error: string): void {\n this.logLine(chalk.red(` ✕ API key error for ${provider}: ${error}`));\n }\n\n static modelCreationError(\n provider: string,\n modelId: string,\n error: string,\n ): void {\n this.logLine(\n chalk.red(\n ` ✕ Failed to create ${provider} model \"${modelId}\": ${error}`,\n ),\n );\n }\n\n private static formatMessageContent(content: MessageContent): string {\n if (content === null || content === undefined) {\n return this.truncate(\"(empty)\");\n }\n\n if (typeof content === \"string\") {\n return this.truncate(content);\n }\n\n if (Array.isArray(content)) {\n const pieces = content\n .map((part) => this.formatMessageContent(part as MessageContent))\n .filter(Boolean);\n return this.truncate(pieces.join(\"\\n\"));\n }\n\n if (typeof content === \"object\") {\n const typedContent = content as Record<string, unknown> & { type?: string };\n\n if (typeof typedContent.type === \"string\") {\n const type = typedContent.type;\n\n if (type === \"text\" && typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n\n if (type === \"tool-call\") {\n const toolName = typedContent.toolName ?? typedContent.name ?? \"tool\";\n const args = typedContent.args ?? typedContent.input ?? typedContent.parameters;\n const details = args ? ` args=${this.stringify(args)}` : \"\";\n return this.truncate(`${toolName}${details}`);\n }\n\n if (type === \"tool-result\") {\n const result = typedContent.result ?? typedContent.output ?? typedContent.data;\n return this.truncate(this.stringify(result));\n }\n\n if (type === \"reasoning\" && typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n }\n\n if (typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n\n return this.truncate(this.stringify(typedContent));\n }\n\n return this.truncate(String(content));\n }\n\n private static summarizeContent(content: MessageContent): {\n textLines: string[];\n toolCalls: ToolCallSummary[];\n } {\n const textLines: string[] = [];\n const toolCalls: ToolCallSummary[] = [];\n\n const visit = (value: MessageContent): void => {\n if (value === null || value === undefined) {\n return;\n }\n\n if (typeof value === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(value)));\n return;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item) => visit(item as MessageContent));\n return;\n }\n\n if (typeof value === \"object\") {\n const typedValue = value as Record<string, unknown> & {\n type?: string;\n };\n\n if (typedValue.type === \"tool-call\") {\n const toolName =\n (typedValue.toolName as string) ||\n (typedValue.name as string) ||\n \"tool\";\n const args = typedValue.args ?? typedValue.input ?? typedValue.parameters;\n toolCalls.push({\n toolName,\n args: args ? this.truncate(this.stringify(args)) : undefined,\n });\n return;\n }\n\n if (typedValue.type === \"text\" && typeof typedValue.text === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n if (\n typedValue.type === \"reasoning\" &&\n typeof typedValue.text === \"string\"\n ) {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n if (\n typedValue.type === \"tool-result\" ||\n typedValue.type === \"tool-error\"\n ) {\n const label = typedValue.type === \"tool-error\" ? \"Tool error\" : \"Tool result\";\n textLines.push(\n `${label}: ${this.truncate(this.stringify(typedValue))}`,\n );\n return;\n }\n\n if (typeof typedValue.text === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n textLines.push(this.truncate(this.stringify(typedValue)));\n return;\n }\n\n textLines.push(this.truncate(String(value)));\n };\n\n visit(content);\n\n const normalizedTextLines = textLines.length\n ? textLines\n : toolCalls.length\n ? []\n : [this.truncate(\"(no content)\")];\n\n return {\n textLines: normalizedTextLines,\n toolCalls,\n };\n }\n\n private static splitAndTrim(text: string): string[] {\n return text\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n }\n\n private static logMessageLines(\n roleLabel: string,\n lines: string[],\n indentLevel: number,\n ): void {\n if (!lines.length) {\n this.logLine(`${roleLabel}:`, indentLevel);\n return;\n }\n\n this.logLine(`${roleLabel}: ${lines[0]}`, indentLevel);\n for (let i = 1; i < lines.length; i++) {\n this.logLine(lines[i] ?? \"\", indentLevel + 1);\n }\n }\n\n private static logToolCall(toolCall: ToolCallSummary, indentLevel: number): void {\n const header = chalk.magentaBright(`[tool-call] ${toolCall.toolName}`);\n this.logLine(header, indentLevel);\n if (toolCall.args) {\n this.logLine(chalk.gray(this.truncate(toolCall.args)), indentLevel + 1);\n }\n }\n\n static beginStreamingMessage(role: ModelMessage[\"role\"], indentLevel = 2): void {\n this.startStream(role, indentLevel);\n }\n\n static appendStreamingText(text: string): void {\n if (!text) {\n return;\n }\n this.appendToStream(text);\n }\n\n static finishStreamingMessage(): void {\n this.closeActiveStream();\n }\n\n static streamToolCall(\n toolName: string,\n args: unknown,\n indentLevel = 3,\n ): void {\n const serializedArgs =\n args === undefined ? undefined : this.truncate(this.stringify(args));\n this.closeActiveStream();\n this.logToolCall({ toolName, args: serializedArgs }, indentLevel);\n }\n\n static streamToolResult(\n toolName: string,\n output: unknown,\n indentLevel = 3,\n ): void {\n this.closeActiveStream();\n const header = chalk.magentaBright(`[tool-result] ${toolName}`);\n this.logLine(header, indentLevel);\n if (output !== undefined) {\n this.logLine(\n chalk.gray(this.truncate(this.stringify(output))),\n indentLevel + 1,\n );\n }\n }\n\n static streamToolError(\n toolName: string,\n error: unknown,\n indentLevel = 3,\n ): void {\n this.closeActiveStream();\n const header = chalk.redBright(`[tool-error] ${toolName}`);\n this.logLine(header, indentLevel);\n this.logLine(\n chalk.red(this.truncate(this.stringify(error ?? \"Unknown error\"))),\n indentLevel + 1,\n );\n }\n\n private static renderBox(\n lines: string[],\n options: {\n borderColor: (text: string) => string;\n statusColor: (text: string) => string;\n indentLevel: number;\n },\n ): void {\n if (!lines.length) {\n return;\n }\n\n const { borderColor, statusColor, indentLevel } = options;\n const statusIndex = lines.findIndex((line) => line.startsWith(\"Status:\"));\n const width = lines.reduce((max, line) => Math.max(max, line.length), 0);\n const horizontal = borderColor(`+${\"-\".repeat(width + 2)}+`);\n this.logLine(horizontal, indentLevel);\n\n lines.forEach((line, index) => {\n const padded = line.padEnd(width, \" \");\n const isStatusLine = index === statusIndex;\n const colouredContent = isStatusLine\n ? statusColor(padded)\n : chalk.white(padded);\n this.logLine(\n `${borderColor(\"| \")}${colouredContent}${borderColor(\" |\")}`,\n indentLevel,\n );\n });\n\n this.logLine(horizontal, indentLevel);\n }\n\n private static stringify(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n try {\n return JSON.stringify(value, null, 2);\n } catch (error) {\n return String(value);\n }\n }\n\n private static truncate(text: string): string {\n const trimmed = text.trim();\n if (trimmed.length <= MAX_CONTENT_LENGTH) {\n return trimmed;\n }\n return `${trimmed.slice(0, MAX_CONTENT_LENGTH - 3).trimEnd()}...`;\n }\n\n private static formatDuration(durationMs: number): string {\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n return \"?\";\n }\n\n if (durationMs < 1000) {\n return `${durationMs.toFixed(0)}ms`;\n }\n\n const seconds = durationMs / 1000;\n if (seconds < 60) {\n return `${seconds.toFixed(1)}s`;\n }\n\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = (seconds % 60).toFixed(0).padStart(2, \"0\");\n return `${minutes}m${remainingSeconds}s`;\n }\n\n private static colorRole(role: ModelMessage[\"role\"]): string {\n switch (role) {\n case \"user\":\n return chalk.cyan(\"user\");\n case \"assistant\":\n return chalk.cyan(\"assistant\");\n case \"tool\":\n return chalk.cyan(\"tool\");\n case \"system\":\n return chalk.cyan(\"system\");\n default:\n return chalk.cyan(role);\n }\n }\n}\n","import { MCPClient } from \"@mastra/mcp\";\nimport { streamText, Tool, ToolChoice, ModelMessage } from \"ai\";\nimport { getUserIdFromApiKeyOrNull } from \"../db/user\";\nimport {\n convertMastraToolsToVercelTools,\n validateAndNormalizeMCPClientConfiguration,\n validateLlms,\n validateTestCase,\n} from \"../utils/validators\";\nimport { createLlmModel, extractToolNamesAsArray } from \"../utils/helpers\";\nimport { Logger } from \"../utils/logger\";\nimport { evaluateResults } from \"./evaluator\";\n\nexport const runEvals = async (\n tests: any,\n environment: any,\n llms: any,\n apiKey?: string,\n) => {\n // Only validate API key if provided\n if (apiKey) {\n await getUserIdFromApiKeyOrNull(apiKey);\n }\n\n const mcpClientOptions =\n validateAndNormalizeMCPClientConfiguration(environment);\n const validatedTests = validateTestCase(tests);\n const validatedLlmApiKeys = validateLlms(llms);\n\n const mcpClient = new MCPClient(mcpClientOptions);\n\n const availableTools = await mcpClient.getTools();\n const serverCount = Object.keys(mcpClientOptions.servers).length;\n const toolCount = Object.keys(availableTools).length;\n Logger.serverConnection(serverCount, toolCount);\n Logger.startTests(validatedTests.length);\n\n const vercelTools = convertMastraToolsToVercelTools(availableTools);\n\n const suiteStartedAt = Date.now();\n let passedRuns = 0;\n let failedRuns = 0;\n\n for (const test of validatedTests) {\n const { runs, model, provider, advancedConfig, query } = test;\n Logger.testTitle(test.title);\n const numberOfRuns = runs;\n const { system, temperature, toolChoice } = advancedConfig ?? {};\n\n for (let run = 0; run < numberOfRuns; run++) {\n Logger.testRunStart({\n runNumber: run + 1,\n totalRuns: numberOfRuns,\n provider,\n model,\n temperature,\n });\n const runStartedAt = Date.now();\n const maxSteps = 20;\n let stepCount = 0;\n\n if (system) {\n Logger.conversation({\n messages: [{ role: \"system\", content: system }],\n indentLevel: 2,\n });\n }\n\n const userMessage: ModelMessage = {\n role: \"user\",\n content: query,\n };\n\n Logger.conversation({ messages: [userMessage], indentLevel: 2 });\n\n const messageHistory: ModelMessage[] = [userMessage];\n const toolsCalled: string[] = [];\n\n while (stepCount < maxSteps) {\n let assistantStreaming = false;\n\n const streamResult = await streamText({\n model: createLlmModel(provider, model, validatedLlmApiKeys),\n system,\n temperature,\n tools: vercelTools,\n toolChoice: toolChoice as ToolChoice<NoInfer<Record<string, Tool>>>,\n messages: messageHistory,\n onChunk: async (chunk) => {\n switch (chunk.chunk.type) {\n case \"text-delta\":\n case \"reasoning-delta\": {\n if (!assistantStreaming) {\n Logger.beginStreamingMessage(\"assistant\", 2);\n assistantStreaming = true;\n }\n Logger.appendStreamingText(chunk.chunk.text);\n break;\n }\n case \"tool-call\": {\n if (assistantStreaming) {\n Logger.finishStreamingMessage();\n assistantStreaming = false;\n }\n Logger.streamToolCall(chunk.chunk.toolName, chunk.chunk.input, 3);\n break;\n }\n case \"tool-result\": {\n Logger.streamToolResult(chunk.chunk.toolName, chunk.chunk.output, 3);\n break;\n }\n default:\n break;\n }\n },\n });\n\n await streamResult.consumeStream();\n\n if (assistantStreaming) {\n Logger.finishStreamingMessage();\n assistantStreaming = false;\n }\n\n const toolNamesForStep = extractToolNamesAsArray(\n await streamResult.toolCalls,\n );\n if (toolNamesForStep.length) {\n toolsCalled.push(...toolNamesForStep);\n }\n\n const responseMessages = ((await streamResult.response)?.messages ?? []) as ModelMessage[];\n if (responseMessages.length) {\n messageHistory.push(...responseMessages);\n }\n\n stepCount++;\n\n const finishReason = await streamResult.finishReason;\n if (finishReason !== \"tool-calls\") {\n break;\n }\n }\n\n Logger.finishStreamingMessage();\n\n const evaluation = evaluateResults(\n test.expectedToolCalls,\n toolsCalled,\n );\n\n Logger.toolSummary({\n expected: evaluation.expectedToolCalls,\n actual: evaluation.toolsCalled,\n missing: evaluation.missing,\n unexpected: evaluation.unexpected,\n passed: evaluation.passed,\n indentLevel: 2,\n });\n\n Logger.testRunResult({\n passed: evaluation.passed,\n durationMs: Date.now() - runStartedAt,\n indentLevel: 2,\n });\n\n if (evaluation.passed) {\n passedRuns++;\n } else {\n failedRuns++;\n }\n }\n }\n\n Logger.suiteComplete({\n durationMs: Date.now() - suiteStartedAt,\n passed: passedRuns,\n failed: failedRuns,\n });\n};\n","export const version = \"1.26.2\";\n","/*\nhttps://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js\nCopyright (c) 2014 Jameson Little\nThe MIT License (MIT)\n*/\n\n// Vendored because this library has no ESM build, and some environments\n// (SvelteKit) are happiest when all dependencies are ESM.\n\nvar lookup: string[] = [];\nvar revLookup: number[] = [];\nvar Arr = Uint8Array;\n\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\n\nfunction getLens(b64: string) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error(\"Invalid string. Length must be a multiple of 4\");\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf(\"=\");\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen];\n}\n\n// base64 is 4/3 + up to two characters of the original data\n/** @public */\nexport function byteLength(b64: string): number {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\nfunction _byteLength(_b64: string, validLen: number, placeHoldersLen: number) {\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\n/** @public */\nexport function toByteArray(b64: string): Uint8Array {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xff;\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n return arr;\n}\n\nfunction tripletToBase64(num: number) {\n return (\n lookup[(num >> 18) & 0x3f] +\n lookup[(num >> 12) & 0x3f] +\n lookup[(num >> 6) & 0x3f] +\n lookup[num & 0x3f]\n );\n}\n\nfunction encodeChunk(uint8: Uint8Array, start: number, end: number) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xff0000) +\n ((uint8[i + 1] << 8) & 0xff00) +\n (uint8[i + 2] & 0xff);\n output.push(tripletToBase64(tmp));\n }\n return output.join(\"\");\n}\n\n/** @public */\nexport function fromByteArray(uint8: Uint8Array): string {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength,\n ),\n );\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + \"==\");\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3f] +\n lookup[(tmp << 2) & 0x3f] +\n \"=\",\n );\n }\n\n return parts.join(\"\");\n}\n\nexport function fromByteArrayUrlSafeNoPadding(uint8: Uint8Array): string {\n return fromByteArray(uint8)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n","import type { Value } from \"../values/value.js\";\n\n/**\n * Validate that the arguments to a Convex function are an object, defaulting\n * `undefined` to `{}`.\n */\nexport function parseArgs(\n args: Record<string, Value> | undefined,\n): Record<string, Value> {\n if (args === undefined) {\n return {};\n }\n if (!isSimpleObject(args)) {\n throw new Error(\n `The arguments to a Convex function must be an object. Received: ${\n args as any\n }`,\n );\n }\n return args;\n}\n\nexport function validateDeploymentUrl(deploymentUrl: string) {\n // Don't use things like `new URL(deploymentUrl).hostname` since these aren't\n // supported by React Native's JS environment\n if (typeof deploymentUrl === \"undefined\") {\n throw new Error(\n `Client created with undefined deployment address. If you used an environment variable, check that it's set.`,\n );\n }\n if (typeof deploymentUrl !== \"string\") {\n throw new Error(\n `Invalid deployment address: found ${deploymentUrl as any}\".`,\n );\n }\n if (\n !(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))\n ) {\n throw new Error(\n `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`,\n );\n }\n\n // Most clients should connect to \".convex.cloud\". But we also support localhost and\n // custom custom. We validate the deployment url is a valid url, which is the most\n // common failure pattern.\n try {\n new URL(deploymentUrl);\n } catch {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n\n // If a user uses .convex.site, this is very likely incorrect.\n if (deploymentUrl.endsWith(\".convex.site\")) {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n}\n\n/**\n * Check whether a value is a plain old JavaScript object.\n */\nexport function isSimpleObject(value: unknown) {\n const isObject = typeof value === \"object\";\n const prototype = Object.getPrototypeOf(value);\n const isSimple =\n prototype === null ||\n prototype === Object.prototype ||\n // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n return isObject && isSimple;\n}\n","/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nconst MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nexport function stringifyValueForError(value: any) {\n return JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // By default `JSON.stringify` converts undefined, functions, symbols,\n // Infinity, and NaN to null which produces a confusing error message.\n // We deal with `undefined` specifically because it's the most common.\n // Ideally we'd use a pretty-printing library that prints `undefined`\n // (no quotes), but it might not be worth the bundle size cost.\n return \"undefined\";\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n","import { GenericId } from \"./index.js\";\nimport { GenericValidator } from \"./validator.js\";\nimport { JSONValue, convexToJson } from \"./value.js\";\n\ntype TableNameFromType<T> =\n T extends GenericId<infer TableName> ? TableName : string;\n\n/**\n * Avoid using `instanceof BaseValidator`; this is inheritence for code reuse\n * not type heirarchy.\n */\nabstract class BaseValidator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> {\n /**\n * Only for TypeScript, the TS type of the JS values validated\n * by this validator.\n */\n readonly type!: Type;\n /**\n * Only for TypeScript, if this an Object validator, then\n * this is the TS type of its property names.\n */\n readonly fieldPaths!: FieldPaths;\n\n /**\n * Whether this is an optional Object property value validator.\n */\n readonly isOptional: IsOptional;\n\n /**\n * Always `\"true\"`.\n */\n readonly isConvexValidator: true;\n\n constructor({ isOptional }: { isOptional: IsOptional }) {\n this.isOptional = isOptional;\n this.isConvexValidator = true;\n }\n /** @deprecated - use isOptional instead */\n get optional(): boolean {\n return this.isOptional === \"optional\" ? true : false;\n }\n /** @internal */\n abstract get json(): ValidatorJSON;\n /** @internal */\n abstract asOptional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n}\n\n/**\n * The type of the `v.id(tableName)` validator.\n */\nexport class VId<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The name of the table that the validated IDs must belong to.\n */\n readonly tableName: TableNameFromType<Type>;\n\n /**\n * The kind of validator, `\"id\"`.\n */\n readonly kind = \"id\" as const;\n\n /**\n * Usually you'd use `v.id(tableName)` instead.\n */\n constructor({\n isOptional,\n tableName,\n }: {\n isOptional: IsOptional;\n tableName: TableNameFromType<Type>;\n }) {\n super({ isOptional });\n if (typeof tableName !== \"string\") {\n throw new Error(\"v.id(tableName) requires a string\");\n }\n this.tableName = tableName;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return { type: \"id\", tableName: this.tableName };\n }\n /** @internal */\n asOptional() {\n return new VId<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n tableName: this.tableName,\n });\n }\n}\n\n/**\n * The type of the `v.float64()` validator.\n */\nexport class VFloat64<\n Type = number,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"float64\"`.\n */\n readonly kind = \"float64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `number` string instead of `float64`.\n return { type: \"number\" };\n }\n /** @internal */\n asOptional() {\n return new VFloat64<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.int64()` validator.\n */\nexport class VInt64<\n Type = bigint,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"int64\"`.\n */\n readonly kind = \"int64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `bigint`.\n return { type: \"bigint\" };\n }\n /** @internal */\n asOptional() {\n return new VInt64<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.boolean()` validator.\n */\nexport class VBoolean<\n Type = boolean,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"boolean\"`.\n */\n readonly kind = \"boolean\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VBoolean<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.bytes()` validator.\n */\nexport class VBytes<\n Type = ArrayBuffer,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"bytes\"`.\n */\n readonly kind = \"bytes\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VBytes<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.string()` validator.\n */\nexport class VString<\n Type = string,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"string\"`.\n */\n readonly kind = \"string\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VString<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.null()` validator.\n */\nexport class VNull<\n Type = null,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"null\"`.\n */\n readonly kind = \"null\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** @internal */\n asOptional() {\n return new VNull<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n}\n\n/**\n * The type of the `v.any()` validator.\n */\nexport class VAny<\n Type = any,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The kind of validator, `\"any\"`.\n */\n readonly kind = \"any\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n };\n }\n /** @internal */\n asOptional() {\n return new VAny<Type | undefined, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n });\n }\n}\n\n/**\n * The type of the `v.object()` validator.\n */\nexport class VObject<\n Type,\n Fields extends Record<string, GenericValidator>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = {\n [Property in keyof Fields]:\n | JoinFieldPaths<Property & string, Fields[Property][\"fieldPaths\"]>\n | Property;\n }[keyof Fields] &\n string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * An object with the validator for each property.\n */\n readonly fields: Fields;\n\n /**\n * The kind of validator, `\"object\"`.\n */\n readonly kind = \"object\" as const;\n\n /**\n * Usually you'd use `v.object({ ... })` instead.\n */\n constructor({\n isOptional,\n fields,\n }: {\n isOptional: IsOptional;\n fields: Fields;\n }) {\n super({ isOptional });\n globalThis.Object.values(fields).forEach((v) => {\n if (!v.isConvexValidator) {\n throw new Error(\"v.object() entries must be valiators\");\n }\n });\n this.fields = fields;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: globalThis.Object.fromEntries(\n globalThis.Object.entries(this.fields).map(([k, v]) => [\n k,\n {\n fieldType: v.json,\n optional: v.isOptional === \"optional\" ? true : false,\n },\n ]),\n ),\n };\n }\n /** @internal */\n asOptional() {\n return new VObject<Type | undefined, Fields, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n fields: this.fields,\n });\n }\n}\n\n/**\n * The type of the `v.literal()` validator.\n */\nexport class VLiteral<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The value that the validated values must be equal to.\n */\n readonly value: Type;\n\n /**\n * The kind of validator, `\"literal\"`.\n */\n readonly kind = \"literal\" as const;\n\n /**\n * Usually you'd use `v.literal(value)` instead.\n */\n constructor({ isOptional, value }: { isOptional: IsOptional; value: Type }) {\n super({ isOptional });\n if (\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\"\n ) {\n throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n }\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: convexToJson(this.value as string | boolean | number | bigint),\n };\n }\n /** @internal */\n asOptional() {\n return new VLiteral<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n value: this.value,\n });\n }\n}\n\n/**\n * The type of the `v.array()` validator.\n */\nexport class VArray<\n Type,\n Element extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The validator for the elements of the array.\n */\n readonly element: Element;\n\n /**\n * The kind of validator, `\"array\"`.\n */\n readonly kind = \"array\" as const;\n\n /**\n * Usually you'd use `v.array(element)` instead.\n */\n constructor({\n isOptional,\n element,\n }: {\n isOptional: IsOptional;\n element: Element;\n }) {\n super({ isOptional });\n this.element = element;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.element.json,\n };\n }\n /** @internal */\n asOptional() {\n return new VArray<Type | undefined, Element, \"optional\">({\n isOptional: \"optional\",\n element: this.element,\n });\n }\n}\n\n/**\n * The type of the `v.record()` validator.\n */\nexport class VRecord<\n Type,\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The validator for the keys of the record.\n */\n readonly key: Key;\n\n /**\n * The validator for the values of the record.\n */\n readonly value: Value;\n\n /**\n * The kind of validator, `\"record\"`.\n */\n readonly kind = \"record\" as const;\n\n /**\n * Usually you'd use `v.record(key, value)` instead.\n */\n constructor({\n isOptional,\n key,\n value,\n }: {\n isOptional: IsOptional;\n key: Key;\n value: Value;\n }) {\n super({ isOptional });\n if ((key.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional keys\");\n }\n if ((value.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional values\");\n }\n if (!key.isConvexValidator || !value.isConvexValidator) {\n throw new Error(\"Key and value of v.record() but be validators\");\n }\n this.key = key;\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n // This cast is needed because TypeScript thinks the key type is too wide\n keys: this.key.json as RecordKeyValidatorJSON,\n values: {\n fieldType: this.value.json,\n optional: false,\n },\n };\n }\n /** @internal */\n asOptional() {\n return new VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n key: this.key,\n value: this.value,\n });\n }\n}\n\n/**\n * The type of the `v.union()` validator.\n */\nexport class VUnion<\n Type,\n T extends Validator<any, \"required\", any>[],\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = T[number][\"fieldPaths\"],\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The array of validators, one of which must match the value.\n */\n readonly members: T;\n\n /**\n * The kind of validator, `\"union\"`.\n */\n readonly kind = \"union\" as const;\n\n /**\n * Usually you'd use `v.union(...members)` instead.\n */\n constructor({ isOptional, members }: { isOptional: IsOptional; members: T }) {\n super({ isOptional });\n members.forEach((member) => {\n if (!member.isConvexValidator) {\n throw new Error(\"All members of v.union() must be validators\");\n }\n });\n this.members = members;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.members.map((v) => v.json),\n };\n }\n /** @internal */\n asOptional() {\n return new VUnion<Type | undefined, T, \"optional\">({\n isOptional: \"optional\",\n members: this.members,\n });\n }\n}\n\n// prettier-ignore\nexport type VOptional<T extends Validator<any, OptionalProperty, any>> =\n T extends VId<infer Type, OptionalProperty> ? VId<Type | undefined, \"optional\">\n : T extends VString<infer Type, OptionalProperty>\n ? VString<Type | undefined, \"optional\">\n : T extends VFloat64<infer Type, OptionalProperty>\n ? VFloat64<Type | undefined, \"optional\">\n : T extends VInt64<infer Type, OptionalProperty>\n ? VInt64<Type | undefined, \"optional\">\n : T extends VBoolean<infer Type, OptionalProperty>\n ? VBoolean<Type | undefined, \"optional\">\n : T extends VNull<infer Type, OptionalProperty>\n ? VNull<Type | undefined, \"optional\">\n : T extends VAny<infer Type, OptionalProperty>\n ? VAny<Type | undefined, \"optional\">\n : T extends VLiteral<infer Type, OptionalProperty>\n ? VLiteral<Type | undefined, \"optional\">\n : T extends VBytes<infer Type, OptionalProperty>\n ? VBytes<Type | undefined, \"optional\">\n : T extends VObject< infer Type, infer Fields, OptionalProperty, infer FieldPaths>\n ? VObject<Type | undefined, Fields, \"optional\", FieldPaths>\n : T extends VArray<infer Type, infer Element, OptionalProperty>\n ? VArray<Type | undefined, Element, \"optional\">\n : T extends VRecord< infer Type, infer Key, infer Value, OptionalProperty, infer FieldPaths>\n ? VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>\n : T extends VUnion<infer Type, infer Members, OptionalProperty, infer FieldPaths>\n ? VUnion<Type | undefined, Members, \"optional\", FieldPaths>\n : never\n\n/**\n * Type representing whether a property in an object is optional or required.\n *\n * @public\n */\nexport type OptionalProperty = \"optional\" | \"required\";\n\n/**\n * A validator for a Convex value.\n *\n * This should be constructed using the validator builder, {@link v}.\n *\n * A validator encapsulates:\n * - The TypeScript type of this value.\n * - Whether this field should be optional if it's included in an object.\n * - The TypeScript type for the set of index field paths that can be used to\n * build indexes on this value.\n * - A JSON representation of the validator.\n *\n * Specific types of validators contain additional information: for example\n * an `ArrayValidator` contains an `element` property with the validator\n * used to validate each element of the list. Use the shared 'kind' property\n * to identity the type of validator.\n *\n * More validators can be added in future releases so an exhaustive\n * switch statement on validator `kind` should be expected to break\n * in future releases of Convex.\n *\n * @public\n */\nexport type Validator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> =\n | VId<Type, IsOptional>\n | VString<Type, IsOptional>\n | VFloat64<Type, IsOptional>\n | VInt64<Type, IsOptional>\n | VBoolean<Type, IsOptional>\n | VNull<Type, IsOptional>\n | VAny<Type, IsOptional>\n | VLiteral<Type, IsOptional>\n | VBytes<Type, IsOptional>\n | VObject<\n Type,\n Record<string, Validator<any, OptionalProperty, any>>,\n IsOptional,\n FieldPaths\n >\n | VArray<Type, Validator<any, \"required\", any>, IsOptional>\n | VRecord<\n Type,\n Validator<string, \"required\", any>,\n Validator<any, \"required\", any>,\n IsOptional,\n FieldPaths\n >\n | VUnion<Type, Validator<any, \"required\", any>[], IsOptional, FieldPaths>;\n\n/**\n * Join together two index field paths.\n *\n * This is used within the validator builder, {@link v}.\n * @public\n */\nexport type JoinFieldPaths<\n Start extends string,\n End extends string,\n> = `${Start}.${End}`;\n\nexport type ObjectFieldType = { fieldType: ValidatorJSON; optional: boolean };\n\nexport type ValidatorJSON =\n | { type: \"null\" }\n | { type: \"number\" }\n | { type: \"bigint\" }\n | { type: \"boolean\" }\n | { type: \"string\" }\n | { type: \"bytes\" }\n | { type: \"any\" }\n | { type: \"literal\"; value: JSONValue }\n | { type: \"id\"; tableName: string }\n | { type: \"array\"; value: ValidatorJSON }\n | {\n type: \"record\";\n keys: RecordKeyValidatorJSON;\n values: RecordValueValidatorJSON;\n }\n | { type: \"object\"; value: Record<string, ObjectFieldType> }\n | { type: \"union\"; value: ValidatorJSON[] };\n\nexport type RecordKeyValidatorJSON =\n | { type: \"string\" }\n | { type: \"id\"; tableName: string }\n | { type: \"union\"; value: RecordKeyValidatorJSON[] };\n\nexport type RecordValueValidatorJSON = ObjectFieldType & { optional: false };\n","import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport {\n OptionalProperty,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n Validator,\n} from \"./validators.js\";\n\n/**\n * The type that all validators must extend.\n *\n * @public\n */\nexport type GenericValidator = Validator<any, any, any>;\n\nexport function isValidator(v: any): v is GenericValidator {\n return !!v.isConvexValidator;\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport function asObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n>(\n obj: V,\n): V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never {\n if (isValidator(obj)) {\n return obj as any;\n } else {\n return v.object(obj as PropertyValidators) as any;\n }\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport type AsObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n> =\n V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never;\n\n/**\n * The validator builder.\n *\n * This builder allows you to build validators for Convex values.\n *\n * Validators can be used in [schema definitions](https://docs.convex.dev/database/schemas)\n * and as input validators for Convex functions.\n *\n * @public\n */\nexport const v = {\n /**\n * Validates that the value corresponds to an ID of a document in given table.\n * @param tableName The name of the table.\n */\n id: <TableName extends string>(tableName: TableName) => {\n return new VId<GenericId<TableName>>({\n isOptional: \"required\",\n tableName,\n });\n },\n\n /**\n * Validates that the value is of type Null.\n */\n null: () => {\n return new VNull({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Float64 (Number in JS).\n *\n * Alias for `v.float64()`\n */\n number: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Float64 (Number in JS).\n */\n float64: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * @deprecated Use `v.int64()` instead\n */\n bigint: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Int64 (BigInt in JS).\n */\n int64: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of type Boolean.\n */\n boolean: () => {\n return new VBoolean({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of type String.\n */\n string: () => {\n return new VString({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is of Convex type Bytes (constructed in JS via `ArrayBuffer`).\n */\n bytes: () => {\n return new VBytes({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is equal to the given literal value.\n * @param literal The literal value to compare against.\n */\n literal: <T extends string | number | bigint | boolean>(literal: T) => {\n return new VLiteral<T>({ isOptional: \"required\", value: literal });\n },\n\n /**\n * Validates that the value is an Array of the given element type.\n * @param element The validator for the elements of the array.\n */\n array: <T extends Validator<any, \"required\", any>>(element: T) => {\n return new VArray<T[\"type\"][], T>({ isOptional: \"required\", element });\n },\n\n /**\n * Validates that the value is an Object with the given properties.\n * @param fields An object specifying the validator for each property.\n */\n object: <T extends PropertyValidators>(fields: T) => {\n return new VObject<ObjectType<T>, T>({ isOptional: \"required\", fields });\n },\n\n /**\n * Validates that the value is a Record with keys and values that match the given types.\n * @param keys The validator for the keys of the record. This cannot contain string literals.\n * @param values The validator for the values of the record.\n */\n record: <\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n >(\n keys: Key,\n values: Value,\n ) => {\n return new VRecord<Record<Infer<Key>, Value[\"type\"]>, Key, Value>({\n isOptional: \"required\",\n key: keys,\n value: values,\n });\n },\n\n /**\n * Validates that the value matches one of the given validators.\n * @param members The validators to match against.\n */\n union: <T extends Validator<any, \"required\", any>[]>(...members: T) => {\n return new VUnion<T[number][\"type\"], T>({\n isOptional: \"required\",\n members,\n });\n },\n\n /**\n * Does not validate the value.\n */\n any: () => {\n return new VAny({ isOptional: \"required\" });\n },\n\n /**\n * Allows not specifying a value for a property in an Object.\n * @param value The property value validator to make optional.\n *\n * ```typescript\n * const objectWithOptionalFields = v.object({\n * requiredField: v.string(),\n * optionalField: v.optional(v.string()),\n * });\n * ```\n */\n optional: <T extends GenericValidator>(value: T) => {\n return value.asOptional() as VOptional<T>;\n },\n};\n\n/**\n * Validators for each property of an object.\n *\n * This is represented as an object mapping the property name to its\n * {@link Validator}.\n *\n * @public\n */\nexport type PropertyValidators = Record<\n string,\n Validator<any, OptionalProperty, any>\n>;\n\n/**\n * Compute the type of an object from {@link PropertyValidators}.\n *\n * @public\n */\nexport type ObjectType<Fields extends PropertyValidators> = Expand<\n // Map each key to the corresponding property validator's type making\n // the optional ones optional.\n {\n // This `Exclude<..., undefined>` does nothing unless\n // the tsconfig.json option `\"exactOptionalPropertyTypes\": true,`\n // is used. When it is it results in a more accurate type.\n // When it is not the `Exclude` removes `undefined` but it is\n // added again by the optional property.\n [Property in OptionalKeys<Fields>]?: Exclude<\n Infer<Fields[Property]>,\n undefined\n >;\n } & {\n [Property in RequiredKeys<Fields>]: Infer<Fields[Property]>;\n }\n>;\n\ntype OptionalKeys<PropertyValidators extends Record<string, GenericValidator>> =\n {\n [Property in keyof PropertyValidators]: PropertyValidators[Property][\"isOptional\"] extends \"optional\"\n ? Property\n : never;\n }[keyof PropertyValidators];\n\ntype RequiredKeys<PropertyValidators extends Record<string, GenericValidator>> =\n Exclude<keyof PropertyValidators, OptionalKeys<PropertyValidators>>;\n\n/**\n * Extract a TypeScript type from a validator.\n *\n * Example usage:\n * ```ts\n * const objectSchema = v.object({\n * property: v.string(),\n * });\n * type MyObject = Infer<typeof objectSchema>; // { property: string }\n * ```\n * @typeParam V - The type of a {@link Validator} constructed with {@link v}.\n *\n * @public\n */\nexport type Infer<T extends Validator<any, OptionalProperty, any>> = T[\"type\"];\n","import { Value, stringifyValueForError } from \"./value.js\";\n\nconst IDENTIFYING_FIELD = Symbol.for(\"ConvexError\");\n\nexport class ConvexError<TData extends Value> extends Error {\n name = \"ConvexError\";\n data: TData;\n [IDENTIFYING_FIELD] = true;\n\n constructor(data: TData) {\n super(typeof data === \"string\" ? data : stringifyValueForError(data));\n this.data = data;\n }\n}\n","/**\n * Taken from https://github.com/rocicorp/compare-utf8/blob/main/LICENSE\n * (Apache Version 2.0, January 2004)\n */\n\n/**\n * This is copied here instead of added as a dependency to avoid bundling issues.\n */\n\n/**\n * Compares two JavaScript strings as if they were UTF-8 encoded byte arrays.\n * @param {string} a\n * @param {string} b\n * @returns {number}\n */\nexport function compareUTF8(a: string, b: string): number {\n const aLength = a.length;\n const bLength = b.length;\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; ) {\n const aCodePoint = a.codePointAt(i)!;\n const bCodePoint = b.codePointAt(i)!;\n if (aCodePoint !== bCodePoint) {\n // Code points below 0x80 are represented the same way in UTF-8 as in\n // UTF-16.\n if (aCodePoint < 0x80 && bCodePoint < 0x80) {\n return aCodePoint - bCodePoint;\n }\n\n // get the UTF-8 bytes for the code points\n const aLength = utf8Bytes(aCodePoint, aBytes);\n const bLength = utf8Bytes(bCodePoint, bBytes);\n return compareArrays(aBytes, aLength, bBytes, bLength);\n }\n\n i += utf16LengthForCodePoint(aCodePoint);\n }\n\n return aLength - bLength;\n}\n\n/**\n * @param {number[]} a\n * @param {number} aLength\n * @param {number[]} b\n * @param {number} bLength\n * @returns {number}\n */\nfunction compareArrays(\n a: number[],\n aLength: number,\n b: number[],\n bLength: number,\n) {\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; i++) {\n const aValue = a[i];\n const bValue = b[i];\n if (aValue !== bValue) {\n return aValue - bValue;\n }\n }\n return aLength - bLength;\n}\n\n/**\n * @param {number} aCodePoint\n * @returns {number}\n */\nexport function utf16LengthForCodePoint(aCodePoint: number) {\n return aCodePoint > 0xffff ? 2 : 1;\n}\n\n// 2 preallocated arrays for utf8Bytes.\nconst arr = () => Array.from({ length: 4 }, () => 0);\nconst aBytes = arr();\nconst bBytes = arr();\n\n/**\n * @param {number} codePoint\n * @param {number[]} bytes\n * @returns {number}\n */\nfunction utf8Bytes(codePoint: number, bytes: number[]) {\n if (codePoint < 0x80) {\n bytes[0] = codePoint;\n return 1;\n }\n\n let count;\n let offset;\n\n if (codePoint <= 0x07ff) {\n count = 1;\n offset = 0xc0;\n } else if (codePoint <= 0xffff) {\n count = 2;\n offset = 0xe0;\n } else if (codePoint <= 0x10ffff) {\n count = 3;\n offset = 0xf0;\n } else {\n throw new Error(\"Invalid code point\");\n }\n\n bytes[0] = (codePoint >> (6 * count)) + offset;\n let i = 1;\n for (; count > 0; count--) {\n const temp = codePoint >> (6 * (count - 1));\n bytes[i++] = 0x80 | (temp & 0x3f);\n }\n return i;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThan(a: string, b: string) {\n return compareUTF8(a, b) > 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThanEq(a: string, b: string) {\n return compareUTF8(a, b) >= 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThan(a: string, b: string) {\n return compareUTF8(a, b) < 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThanEq(a: string, b: string) {\n return compareUTF8(a, b) <= 0;\n}\n","/* eslint-disable no-console */ // This is the one file where we can `console.log` for the default logger implementation.\nimport { ConvexError, Value } from \"../values/index.js\";\nimport { FunctionFailure } from \"./sync/function_result.js\";\n\n// This is blue #9 from https://www.radix-ui.com/docs/colors/palette-composition/the-scales\n// It must look good in both light and dark mode.\nconst INFO_COLOR = \"color:rgb(0, 145, 255)\";\n\nexport type UdfType = \"query\" | \"mutation\" | \"action\" | \"any\";\n\nfunction prefix_for_source(source: UdfType) {\n switch (source) {\n case \"query\":\n return \"Q\";\n case \"mutation\":\n return \"M\";\n case \"action\":\n return \"A\";\n case \"any\":\n return \"?\";\n }\n}\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * A logger that can be used to log messages. By default, this is a wrapper\n * around `console`, but can be configured to not log at all or to log somewhere\n * else.\n */\nexport type Logger = {\n logVerbose(...args: any[]): void;\n log(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\n\nexport class DefaultLogger implements Logger {\n private _onLogLineFuncs: Record<\n string,\n (level: LogLevel, ...args: any[]) => void\n >;\n private _verbose: boolean;\n\n constructor(options: { verbose: boolean }) {\n this._onLogLineFuncs = {};\n this._verbose = options.verbose;\n }\n\n addLogLineListener(\n func: (level: LogLevel, ...args: any[]) => void,\n ): () => void {\n let id = Math.random().toString(36).substring(2, 15);\n for (let i = 0; i < 10; i++) {\n if (this._onLogLineFuncs[id] === undefined) {\n break;\n }\n id = Math.random().toString(36).substring(2, 15);\n }\n this._onLogLineFuncs[id] = func;\n return () => {\n delete this._onLogLineFuncs[id];\n };\n }\n\n logVerbose(...args: any[]) {\n if (this._verbose) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"debug\", `${new Date().toISOString()}`, ...args);\n }\n }\n }\n\n log(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"info\", ...args);\n }\n }\n\n warn(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"warn\", ...args);\n }\n }\n\n error(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"error\", ...args);\n }\n }\n}\n\nexport function instantiateDefaultLogger(options: {\n verbose: boolean;\n}): Logger {\n const logger = new DefaultLogger(options);\n logger.addLogLineListener((level, ...args) => {\n switch (level) {\n case \"debug\":\n console.debug(...args);\n break;\n case \"info\":\n console.log(...args);\n break;\n case \"warn\":\n console.warn(...args);\n break;\n case \"error\":\n console.error(...args);\n break;\n default: {\n level satisfies never;\n console.log(...args);\n }\n }\n });\n return logger;\n}\n\nexport function instantiateNoopLogger(options: { verbose: boolean }): Logger {\n return new DefaultLogger(options);\n}\n\nexport function logForFunction(\n logger: Logger,\n type: \"info\" | \"error\",\n source: UdfType,\n udfPath: string,\n message: string | { errorData: Value },\n) {\n const prefix = prefix_for_source(source);\n\n if (typeof message === \"object\") {\n message = `ConvexError ${JSON.stringify(message.errorData, null, 2)}`;\n }\n if (type === \"info\") {\n const match = message.match(/^\\[.*?\\] /);\n if (match === null) {\n logger.error(\n `[CONVEX ${prefix}(${udfPath})] Could not parse console.log`,\n );\n return;\n }\n const level = message.slice(1, match[0].length - 2);\n const args = message.slice(match[0].length);\n\n logger.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`, INFO_COLOR, args);\n } else {\n logger.error(`[CONVEX ${prefix}(${udfPath})] ${message}`);\n }\n}\n\nexport function logFatalError(logger: Logger, message: string): Error {\n const errorMessage = `[CONVEX FATAL ERROR] ${message}`;\n logger.error(errorMessage);\n return new Error(errorMessage);\n}\n\nexport function createHybridErrorStacktrace(\n source: UdfType,\n udfPath: string,\n result: FunctionFailure,\n): string {\n const prefix = prefix_for_source(source);\n return `[CONVEX ${prefix}(${udfPath})] ${result.errorMessage}\\n Called by client`;\n}\n\nexport function forwardData(\n result: FunctionFailure,\n error: ConvexError<string>,\n) {\n (error as ConvexError<any>).data = result.errorData;\n return error;\n}\n","/**\n * A symbol for accessing the name of a {@link FunctionReference} at runtime.\n */\nexport const functionName = Symbol.for(\"functionName\");\n","import { functionName } from \"../functionName.js\";\n\nexport const toReferencePath = Symbol.for(\"toReferencePath\");\n\n// Multiple instances of the same Symbol.for() are equal at runtime but not\n// at type-time, so `[toReferencePath]` properties aren't used in types.\n// Use this function to set the property invisibly.\nexport function setReferencePath<T>(obj: T, value: string) {\n (obj as any)[toReferencePath] = value;\n}\n\nexport function extractReferencePath(reference: any): string | null {\n return reference[toReferencePath] ?? null;\n}\n\nexport function isFunctionHandle(s: string): boolean {\n return s.startsWith(\"function://\");\n}\n\nexport function getFunctionAddress(functionReference: any) {\n // The `run*` syscalls expect either a UDF path at \"name\" or a serialized\n // reference at \"reference\". Dispatch on `functionReference` to coerce\n // it to one or the other.\n let functionAddress;\n\n // Legacy path for passing in UDF paths directly as function references.\n if (typeof functionReference === \"string\") {\n if (isFunctionHandle(functionReference)) {\n functionAddress = { functionHandle: functionReference };\n } else {\n functionAddress = { name: functionReference };\n }\n }\n // Path for passing in a `FunctionReference`, either from `api` or directly\n // created from a UDF path with `makeFunctionReference`.\n else if (functionReference[functionName]) {\n functionAddress = { name: functionReference[functionName] };\n }\n // Reference to a component's function derived from `app` or `component`.\n else {\n const referencePath = extractReferencePath(functionReference);\n if (!referencePath) {\n throw new Error(`${functionReference} is not a functionReference`);\n }\n functionAddress = { reference: referencePath };\n }\n return functionAddress;\n}\n","import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _args: Args;\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference: AnyFunctionReference,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as API[mod] extends Predicate\n ? mod\n : API[mod] extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API[mod], Predicate> extends Record<string, never>\n ? never\n : mod]: API[mod] extends Predicate\n ? API[mod]\n : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * This is represented as an object mapping argument names to values.\n * @public\n */\nexport type FunctionArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FuncRef[\"_args\"]];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends AnyFunctionReference,\n Options,\n> = FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FuncRef[\"_args\"], options?: Options];\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n","// Implements an unsigned long.\n// This is a subset of https://github.com/dcodeIO/Long.js,\n// vendored to decrease bundle size.\n// Copyright Daniel Wirtz <dcode@dcode.io>\n// License: Apache Version 2.0\n/*\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright 2023 Daniel Wirtz <dcode@dcode.io>\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// This works... but don't try to compare one to a real Long.js Long!\n// For internal use only.\n// `| 0` assures the runtime that we are using integer arithmetic\nexport class Long {\n low: number;\n high: number;\n __isUnsignedLong__: boolean;\n\n static isLong(obj: Long) {\n return (obj && obj.__isUnsignedLong__) === true;\n }\n\n constructor(low: number, high: number) {\n this.low = low | 0;\n this.high = high | 0;\n this.__isUnsignedLong__ = true;\n }\n\n // prettier-ignore\n static fromBytesLE(bytes: number[]): Long {\n return new Long(\n bytes[0] |\n bytes[1] << 8 |\n bytes[2] << 16 |\n bytes[3] << 24,\n bytes[4] |\n bytes[5] << 8 |\n bytes[6] << 16 |\n bytes[7] << 24,\n );\n }\n\n // prettier-ignore\n toBytesLE() {\n const hi = this.high;\n const lo = this.low;\n return [\n lo & 0xff,\n lo >>> 8 & 0xff,\n lo >>> 16 & 0xff,\n lo >>> 24,\n hi & 0xff,\n hi >>> 8 & 0xff,\n hi >>> 16 & 0xff,\n hi >>> 24\n ];\n }\n\n static fromNumber(value: number) {\n if (isNaN(value)) return UZERO;\n if (value < 0) return UZERO;\n if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;\n return new Long(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0);\n }\n\n toString() {\n return (\n BigInt(this.high) * BigInt(TWO_PWR_32_DBL) +\n BigInt(this.low)\n ).toString();\n }\n\n equals(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;\n return this.high === other.high && this.low === other.low;\n }\n\n notEquals(other: Long) {\n return !this.equals(other);\n }\n\n comp(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.equals(other)) return 0;\n return other.high >>> 0 > this.high >>> 0 ||\n (other.high === this.high && other.low >>> 0 > this.low >>> 0)\n ? -1\n : 1;\n }\n\n lessThanOrEqual(other: Long) {\n return this.comp(/* validates */ other) <= 0;\n }\n\n static fromValue(val: any) {\n if (typeof val === \"number\") return Long.fromNumber(val);\n // Throws for non-objects, converts non-instanceof Long:\n return new Long(val.low, val.high);\n }\n}\n\nconst UZERO = new Long(0, 0);\nconst TWO_PWR_16_DBL = 1 << 16;\nconst TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\nconst TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\nconst MAX_UNSIGNED_VALUE = new Long(0xffffffff | 0, 0xffffffff | 0);\n","export class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {\n let code = p.charCodeAt(0).toString(16).toUpperCase();\n if (code.length < 2) {\n code = \"0\" + code;\n }\n return \"%\" + code;\n }));\n}\nfunction base64UrlDecode(str) {\n let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n switch (output.length % 4) {\n case 0:\n break;\n case 2:\n output += \"==\";\n break;\n case 3:\n output += \"=\";\n break;\n default:\n throw new Error(\"base64 string is not of the correct length\");\n }\n try {\n return b64DecodeUnicode(output);\n }\n catch (err) {\n return atob(output);\n }\n}\nexport function jwtDecode(token, options) {\n if (typeof token !== \"string\") {\n throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n }\n options || (options = {});\n const pos = options.header === true ? 0 : 1;\n const part = token.split(\".\")[pos];\n if (typeof part !== \"string\") {\n throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);\n }\n let decoded;\n try {\n decoded = base64UrlDecode(part);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);\n }\n try {\n return JSON.parse(decoded);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);\n }\n}\n","import { Logger } from \"../logging.js\";\nimport { LocalSyncState } from \"./local_state.js\";\nimport { AuthError, IdentityVersion, Transition } from \"./protocol.js\";\nimport { jwtDecode } from \"jwt-decode\";\n\n// setTimout uses 32 bit integer, so it can only\n// schedule about 24 days in the future.\nconst MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1000; // 20 days\n\nconst MAX_TOKEN_CONFIRMATION_ATTEMPTS = 2;\n\n/**\n * An async function returning a JWT. Depending on the auth providers\n * configured in convex/auth.config.ts, this may be a JWT-encoded OpenID\n * Connect Identity Token or a traditional JWT.\n *\n * `forceRefreshToken` is `true` if the server rejected a previously\n * returned token or the token is anticipated to expiring soon\n * based on its `exp` time.\n *\n * See {@link ConvexReactClient.setAuth}.\n *\n * @public\n */\nexport type AuthTokenFetcher = (args: {\n forceRefreshToken: boolean;\n}) => Promise<string | null | undefined>;\n\n/**\n * What is provided to the client.\n */\ntype AuthConfig = {\n fetchToken: AuthTokenFetcher;\n onAuthChange: (isAuthenticated: boolean) => void;\n};\n\n/**\n * In general we take 3 steps:\n * 1. Fetch a possibly cached token\n * 2. Immediately fetch a fresh token without using a cache\n * 3. Repeat step 2 before the end of the fresh token's lifetime\n *\n * When we fetch without using a cache we know when the token\n * will expire, and can schedule refetching it.\n *\n * If we get an error before a scheduled refetch, we go back\n * to step 2.\n */\ntype AuthState =\n | { state: \"noAuth\" }\n | {\n state: \"waitingForServerConfirmationOfCachedToken\";\n config: AuthConfig;\n hasRetried: boolean;\n }\n | {\n state: \"initialRefetch\";\n config: AuthConfig;\n }\n | {\n state: \"waitingForServerConfirmationOfFreshToken\";\n config: AuthConfig;\n hadAuth: boolean;\n token: string;\n }\n | {\n state: \"waitingForScheduledRefetch\";\n config: AuthConfig;\n refetchTokenTimeoutId: ReturnType<typeof setTimeout>;\n }\n // Special/weird state when we got a valid token\n // but could not fetch a new one.\n | {\n state: \"notRefetching\";\n config: AuthConfig;\n };\n\n/**\n * Handles the state transitions for auth. The server is the source\n * of truth.\n */\nexport class AuthenticationManager {\n private authState: AuthState = { state: \"noAuth\" };\n // Used to detect races involving `setConfig` calls\n // while a token is being fetched.\n private configVersion = 0;\n // Shared by the BaseClient so that the auth manager can easily inspect it\n private readonly syncState: LocalSyncState;\n // Passed down by BaseClient, sends a message to the server\n private readonly authenticate: (token: string) => IdentityVersion;\n private readonly stopSocket: () => Promise<void>;\n private readonly tryRestartSocket: () => void;\n private readonly pauseSocket: () => void;\n private readonly resumeSocket: () => void;\n // Passed down by BaseClient, sends a message to the server\n private readonly clearAuth: () => void;\n private readonly logger: Logger;\n private readonly refreshTokenLeewaySeconds: number;\n // Number of times we have attempted to confirm the latest token. We retry up\n // to `MAX_TOKEN_CONFIRMATION_ATTEMPTS` times.\n private tokenConfirmationAttempts = 0;\n constructor(\n syncState: LocalSyncState,\n callbacks: {\n authenticate: (token: string) => IdentityVersion;\n stopSocket: () => Promise<void>;\n tryRestartSocket: () => void;\n pauseSocket: () => void;\n resumeSocket: () => void;\n clearAuth: () => void;\n },\n config: {\n refreshTokenLeewaySeconds: number;\n logger: Logger;\n },\n ) {\n this.syncState = syncState;\n this.authenticate = callbacks.authenticate;\n this.stopSocket = callbacks.stopSocket;\n this.tryRestartSocket = callbacks.tryRestartSocket;\n this.pauseSocket = callbacks.pauseSocket;\n this.resumeSocket = callbacks.resumeSocket;\n this.clearAuth = callbacks.clearAuth;\n this.logger = config.logger;\n this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;\n }\n\n async setConfig(\n fetchToken: AuthTokenFetcher,\n onChange: (isAuthenticated: boolean) => void,\n ) {\n this.resetAuthState();\n this._logVerbose(\"pausing WS for auth token fetch\");\n this.pauseSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {\n forceRefreshToken: false,\n });\n if (token.isFromOutdatedConfig) {\n return;\n }\n if (token.value) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfCachedToken\",\n config: { fetchToken, onAuthChange: onChange },\n hasRetried: false,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"initialRefetch\",\n config: { fetchToken, onAuthChange: onChange },\n });\n // Try again with `forceRefreshToken: true`\n await this.refetchToken();\n }\n this._logVerbose(\"resuming WS after auth token fetch\");\n this.resumeSocket();\n }\n\n onTransition(serverMessage: Transition) {\n if (\n !this.syncState.isCurrentOrNewerAuthVersion(\n serverMessage.endVersion.identity,\n )\n ) {\n // This is a stale transition - client has moved on to\n // a newer auth version.\n return;\n }\n if (\n serverMessage.endVersion.identity <= serverMessage.startVersion.identity\n ) {\n // This transition did not change auth - it is not a response to Authenticate.\n return;\n }\n\n if (this.authState.state === \"waitingForServerConfirmationOfCachedToken\") {\n this._logVerbose(\"server confirmed auth token is valid\");\n void this.refetchToken();\n this.authState.config.onAuthChange(true);\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this._logVerbose(\"server confirmed new auth token is valid\");\n this.scheduleTokenRefetch(this.authState.token);\n this.tokenConfirmationAttempts = 0;\n if (!this.authState.hadAuth) {\n this.authState.config.onAuthChange(true);\n }\n }\n }\n\n onAuthError(serverMessage: AuthError) {\n // If the AuthError is not due to updating the token, and we're currently\n // waiting on the result of a token update, ignore.\n if (\n serverMessage.authUpdateAttempted === false &&\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" ||\n this.authState.state === \"waitingForServerConfirmationOfCachedToken\")\n ) {\n this._logVerbose(\"ignoring non-auth token expired error\");\n return;\n }\n const { baseVersion } = serverMessage;\n // Versioned AuthErrors are ignored if the client advanced to\n // a newer auth identity\n // Error are reporting the previous version, since the server\n // didn't advance, hence `+ 1`.\n if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {\n this._logVerbose(\"ignoring auth error for previous auth attempt\");\n return;\n }\n void this.tryToReauthenticate(serverMessage);\n return;\n }\n\n // This is similar to `refetchToken` defined below, in fact we\n // don't represent them as different states, but it is different\n // in that we pause the WebSocket so that mutations\n // don't retry with bad auth.\n private async tryToReauthenticate(serverMessage: AuthError) {\n this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);\n if (\n // No way to fetch another token, kaboom\n this.authState.state === \"noAuth\" ||\n // We failed on a fresh token. After a small number of retries, we give up\n // and clear the auth state to avoid infinite retries.\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" &&\n this.tokenConfirmationAttempts >= MAX_TOKEN_CONFIRMATION_ATTEMPTS)\n ) {\n this.logger.error(\n `Failed to authenticate: \"${serverMessage.error}\", check your server auth config`,\n );\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n if (this.authState.state !== \"noAuth\") {\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this.tokenConfirmationAttempts++;\n this._logVerbose(\n `retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS - this.tokenConfirmationAttempts} attempts remaining`,\n );\n }\n\n await this.stopSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value && this.syncState.isNewAuth(token.value)) {\n this.authenticate(token.value);\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n config: this.authState.config,\n token: token.value,\n hadAuth:\n this.authState.state === \"notRefetching\" ||\n this.authState.state === \"waitingForScheduledRefetch\",\n });\n } else {\n this._logVerbose(\"reauthentication failed, could not fetch a new token\");\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n this.tryRestartSocket();\n }\n\n // Force refetch the token and schedule another refetch\n // before the token expires - an active client should never\n // need to reauthenticate.\n private async refetchToken() {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n this._logVerbose(\"refetching auth token\");\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value) {\n if (this.syncState.isNewAuth(token.value)) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n hadAuth: this.syncState.hasAuth(),\n token: token.value,\n config: this.authState.config,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"notRefetching\",\n config: this.authState.config,\n });\n }\n } else {\n this._logVerbose(\"refetching token failed\");\n if (this.syncState.hasAuth()) {\n this.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n // Restart in case this refetch was triggered via schedule during\n // a reauthentication attempt.\n this._logVerbose(\n \"restarting WS after auth token fetch (if currently stopped)\",\n );\n this.tryRestartSocket();\n }\n\n private scheduleTokenRefetch(token: string) {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n const decodedToken = this.decodeToken(token);\n if (!decodedToken) {\n // This is no longer really possible, because\n // we wait on server response before scheduling token refetch,\n // and the server currently requires JWT tokens.\n this.logger.error(\n \"Auth token is not a valid JWT, cannot refetch the token\",\n );\n return;\n }\n // iat: issued at time, UTC seconds timestamp at which the JWT was issued\n // exp: expiration time, UTC seconds timestamp at which the JWT will expire\n const { iat, exp } = decodedToken as { iat?: number; exp?: number };\n if (!iat || !exp) {\n this.logger.error(\n \"Auth token does not have required fields, cannot refetch the token\",\n );\n return;\n }\n // Because the client and server clocks may be out of sync,\n // we only know that the token will expire after `exp - iat`,\n // and since we just fetched a fresh one we know when that\n // will happen.\n const tokenValiditySeconds = exp - iat;\n if (tokenValiditySeconds <= 2) {\n this.logger.error(\n \"Auth token does not live long enough, cannot refetch the token\",\n );\n return;\n }\n // Attempt to refresh the token `refreshTokenLeewaySeconds` before it expires,\n // or immediately if the token is already expiring soon.\n let delay = Math.min(\n MAXIMUM_REFRESH_DELAY,\n (tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1000,\n );\n if (delay <= 0) {\n // Refetch immediately, but this might be due to configuring a `refreshTokenLeewaySeconds`\n // that is too large compared to the token's actual lifetime.\n this.logger.warn(\n `Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`,\n );\n delay = 0;\n }\n const refetchTokenTimeoutId = setTimeout(() => {\n this._logVerbose(\"running scheduled token refetch\");\n void this.refetchToken();\n }, delay);\n this.setAuthState({\n state: \"waitingForScheduledRefetch\",\n refetchTokenTimeoutId,\n config: this.authState.config,\n });\n this._logVerbose(\n `scheduled preemptive auth token refetching in ${delay}ms`,\n );\n }\n\n // Protects against simultaneous calls to `setConfig`\n // while we're fetching a token\n private async fetchTokenAndGuardAgainstRace(\n fetchToken: AuthTokenFetcher,\n fetchArgs: {\n forceRefreshToken: boolean;\n },\n ) {\n const originalConfigVersion = ++this.configVersion;\n this._logVerbose(\n `fetching token with config version ${originalConfigVersion}`,\n );\n const token = await fetchToken(fetchArgs);\n if (this.configVersion !== originalConfigVersion) {\n // This is a stale config\n this._logVerbose(\n `stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`,\n );\n return { isFromOutdatedConfig: true };\n }\n return { isFromOutdatedConfig: false, value: token };\n }\n\n stop() {\n this.resetAuthState();\n // Bump this in case we are mid-token-fetch when we get stopped\n this.configVersion++;\n this._logVerbose(`config version bumped to ${this.configVersion}`);\n }\n\n private setAndReportAuthFailed(\n onAuthChange: (authenticated: boolean) => void,\n ) {\n onAuthChange(false);\n this.resetAuthState();\n }\n\n private resetAuthState() {\n this.setAuthState({ state: \"noAuth\" });\n }\n\n private setAuthState(newAuth: AuthState) {\n const authStateForLog =\n newAuth.state === \"waitingForServerConfirmationOfFreshToken\"\n ? {\n hadAuth: newAuth.hadAuth,\n state: newAuth.state,\n token: `...${newAuth.token.slice(-7)}`,\n }\n : { state: newAuth.state };\n this._logVerbose(\n `setting auth state to ${JSON.stringify(authStateForLog)}`,\n );\n switch (newAuth.state) {\n case \"waitingForScheduledRefetch\":\n case \"notRefetching\":\n case \"noAuth\":\n this.tokenConfirmationAttempts = 0;\n break;\n case \"waitingForServerConfirmationOfFreshToken\":\n case \"waitingForServerConfirmationOfCachedToken\":\n case \"initialRefetch\":\n break;\n default: {\n newAuth satisfies never;\n }\n }\n if (this.authState.state === \"waitingForScheduledRefetch\") {\n clearTimeout(this.authState.refetchTokenTimeoutId);\n\n // The waitingForScheduledRefetch state is the most quiesced authed state.\n // Let the syncState know that auth is in a good state, so it can reset failure backoffs\n this.syncState.markAuthCompletion();\n }\n this.authState = newAuth;\n }\n\n private decodeToken(token: string) {\n try {\n return jwtDecode(token);\n } catch (e) {\n this._logVerbose(\n `Error decoding token: ${e instanceof Error ? e.message : \"Unknown error\"}`,\n );\n return null;\n }\n }\n\n private _logVerbose(message: string) {\n this.logger.logVerbose(`${message} [v${this.configVersion}]`);\n }\n}\n","import {\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n ConvexError,\n JSONValue,\n convexToJson,\n jsonToConvex,\n} from \"../values/index.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logForFunction,\n Logger,\n} from \"./logging.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n UserIdentityAttributes,\n} from \"../server/index.js\";\n\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\n// Special custom 5xx HTTP status code to mean that the UDF returned an error.\n//\n// Must match the constant of the same name in the backend.\nexport const STATUS_CODE_UDF_FAILED = 560;\n\n// Allow fetch to be shimmed in for Node.js < 18\nlet specifiedFetch: typeof globalThis.fetch | undefined = undefined;\nexport function setFetch(f: typeof globalThis.fetch) {\n specifiedFetch = f;\n}\n\nexport type HttpMutationOptions = {\n /**\n * Skip the default queue of mutations and run this immediately.\n *\n * This allows the same HttpConvexClient to be used to request multiple\n * mutations in parallel, something not possible with WebSocket-based clients.\n */\n skipQueue: boolean;\n};\n\n/**\n * A Convex client that runs queries and mutations over HTTP.\n *\n * This client is stateful (it has user credentials and queues mutations)\n * so take care to avoid sharing it between requests in a server.\n *\n * This is appropriate for server-side code (like Netlify Lambdas) or non-reactive\n * webapps.\n *\n * @public\n */\nexport class ConvexHttpClient {\n private readonly address: string;\n private auth?: string;\n private adminAuth?: string;\n private encodedTsPromise?: Promise<string>;\n private debug: boolean;\n private fetchOptions?: FetchOptions;\n private logger: Logger;\n private mutationQueue: Array<{\n mutation: FunctionReference<\"mutation\">;\n args: FunctionArgs<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }> = [];\n private isProcessingQueue: boolean = false;\n\n /**\n * Create a new {@link ConvexHttpClient}.\n *\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - An object of options.\n * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n * Convex backend that uses a different URL.\n * - `logger` - A logger or a boolean. If not provided, logs to the console.\n * You can construct your own logger to customize logging to log elsewhere\n * or not log at all, or use `false` as a shorthand for a no-op logger.\n * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n * These methods can receive multiple arguments of any types, like console.log().\n * - `auth` - A JWT containing identity claims accessible in Convex functions.\n * This identity may expire so it may be necessary to call `setAuth()` later,\n * but for short-lived clients it's convenient to specify this value here.\n */\n constructor(\n address: string,\n options?: {\n skipConvexDeploymentUrlCheck?: boolean;\n logger?: Logger | boolean;\n auth?: string;\n },\n ) {\n if (typeof options === \"boolean\") {\n throw new Error(\n \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\",\n );\n }\n const opts = options ?? {};\n if (opts.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n this.logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: false });\n this.address = address;\n this.debug = true;\n if (options?.auth) {\n this.setAuth(options.auth);\n }\n }\n\n /**\n * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n * @deprecated Use url, which returns the url without /api at the end.\n *\n * @returns The URL to the Convex backend, including the client's API version.\n */\n backendUrl(): string {\n return `${this.address}/api`;\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n *\n * Should be called whenever the token changes (i.e. due to expiration and refresh).\n *\n * @param value - JWT-encoded OpenID Connect identity token.\n */\n setAuth(value: string) {\n this.clearAuth();\n this.auth = value;\n }\n\n /**\n * Set admin auth token to allow calling internal queries, mutations, and actions\n * and acting as an identity.\n *\n * @internal\n */\n setAdminAuth(token: string, actingAsIdentity?: UserIdentityAttributes) {\n this.clearAuth();\n if (actingAsIdentity !== undefined) {\n // Encode the identity to a base64 string\n const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n } else {\n this.adminAuth = token;\n }\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.auth = undefined;\n this.adminAuth = undefined;\n }\n\n /**\n * Sets whether the result log lines should be printed on the console or not.\n *\n * @internal\n */\n setDebug(debug: boolean) {\n this.debug = debug;\n }\n\n /**\n * Used to customize the fetch behavior in some runtimes.\n *\n * @internal\n */\n setFetchOptions(fetchOptions: FetchOptions) {\n this.fetchOptions = fetchOptions;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Execute a Convex query function at the same timestamp as every other\n * consistent query execution run by this HTTP client.\n *\n * This doesn't make sense for long-lived ConvexHttpClients as Convex\n * backends can read a limited amount into the past: beyond 30 seconds\n * in the past may not be available.\n *\n * Create a new client to use a consistent time.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n *\n * @deprecated This API is experimental: it may change or disappear.\n */\n async consistentQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n\n const timestampPromise = this.getTimestamp();\n return await this.queryInner(query, queryArgs, { timestampPromise });\n }\n\n private async getTimestamp() {\n if (this.encodedTsPromise) {\n return this.encodedTsPromise;\n }\n return (this.encodedTsPromise = this.getTimestampInner());\n }\n\n private async getTimestampInner() {\n const localFetch = specifiedFetch || fetch;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n const response = await localFetch(`${this.address}/api/query_ts`, {\n ...this.fetchOptions,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok) {\n throw new Error(await response.text());\n }\n const { ts } = (await response.json()) as { ts: string };\n return ts;\n }\n\n /**\n * Execute a Convex query function.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n return await this.queryInner(query, queryArgs, {});\n }\n\n private async queryInner<Query extends FunctionReference<\"query\">>(\n query: Query,\n queryArgs: FunctionArgs<Query>,\n options: { timestampPromise?: Promise<string> },\n ): Promise<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n const args = [convexToJson(queryArgs)];\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n\n const timestamp = options.timestampPromise\n ? await options.timestampPromise\n : undefined;\n\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args,\n ...(timestamp ? { ts: timestamp } : {}),\n });\n const endpoint = timestamp\n ? `${this.address}/api/query_at_ts`\n : `${this.address}/api/query`;\n\n const response = await localFetch(endpoint, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"query\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async mutationInner<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n mutationArgs: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n const name = getFunctionName(mutation);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(mutationArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/mutation`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"mutation\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async processMutationQueue() {\n if (this.isProcessingQueue) {\n return;\n }\n\n this.isProcessingQueue = true;\n while (this.mutationQueue.length > 0) {\n const { mutation, args, resolve, reject } = this.mutationQueue.shift()!;\n try {\n const result = await this.mutationInner(mutation, args);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n }\n this.isProcessingQueue = false;\n }\n\n private enqueueMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n return new Promise((resolve, reject) => {\n this.mutationQueue.push({ mutation, args, resolve, reject });\n void this.processMutationQueue();\n });\n }\n\n /**\n * Execute a Convex mutation function. Mutations are queued by default.\n *\n * @param name - The name of the mutation.\n * @param args - The arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - An optional object containing\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, HttpMutationOptions>\n ): Promise<FunctionReturnType<Mutation>> {\n const [fnArgs, options] = args;\n const mutationArgs = parseArgs(fnArgs);\n const queued = !options?.skipQueue;\n\n if (queued) {\n return await this.enqueueMutation(mutation, mutationArgs);\n } else {\n return await this.mutationInner(mutation, mutationArgs);\n }\n }\n\n /**\n * Execute a Convex action function. Actions are not queued.\n *\n * @param name - The name of the action.\n * @param args - The arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const actionArgs = parseArgs(args[0]);\n const name = getFunctionName(action);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(actionArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/action`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"action\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n /**\n * Execute a Convex function of an unknown type. These function calls are not queued.\n *\n * @param name - The name of the function.\n * @param args - The arguments object for the function. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the function's result.\n *\n * @internal\n */\n async function<\n AnyFunction extends FunctionReference<\"query\" | \"mutation\" | \"action\">,\n >(\n anyFunction: AnyFunction | string,\n componentPath?: string,\n ...args: OptionalRestArgs<AnyFunction>\n ): Promise<FunctionReturnType<AnyFunction>> {\n const functionArgs = parseArgs(args[0]);\n const name =\n typeof anyFunction === \"string\"\n ? anyFunction\n : getFunctionName(anyFunction);\n const body = JSON.stringify({\n componentPath: componentPath,\n path: name,\n format: \"convex_encoded_json\",\n args: convexToJson(functionArgs),\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/function`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"any\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n}\n\nfunction forwardErrorData(errorData: JSONValue, error: ConvexError<string>) {\n (error as ConvexError<any>).data = jsonToConvex(errorData);\n return error;\n}\n\n/**\n * @internal\n */\ntype FetchOptions = { cache: \"force-cache\" | \"no-store\" };\n","import { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n BaseConvexClient,\n BaseConvexClientOptions,\n MutationOptions,\n QueryToken,\n UserIdentityAttributes,\n} from \"./index.js\";\nimport {\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n} from \"../server/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { AuthTokenFetcher } from \"./sync/authentication_manager.js\";\nimport { ConnectionState } from \"./sync/client.js\";\n\n// In Node.js builds this points to a bundled WebSocket implementation. If no\n// WebSocket implementation is manually specified or globally available,\n// this one is used.\nlet defaultWebSocketConstructor: typeof WebSocket | undefined;\n\n/** internal */\nexport function setDefaultWebSocketConstructor(ws: typeof WebSocket) {\n defaultWebSocketConstructor = ws;\n}\n\nexport type ConvexClientOptions = BaseConvexClientOptions & {\n /**\n * `disabled` makes onUpdate callback registration a no-op and actions,\n * mutations and one-shot queries throw. Setting disabled to true may be\n * useful for server-side rendering, where subscriptions don't make sense.\n */\n disabled?: boolean;\n /**\n * Whether to prompt users in browsers about queued or in-flight mutations.\n * This only works in environments where `window.onbeforeunload` is available.\n *\n * Defaults to true when `window` is defined, otherwise false.\n */\n unsavedChangesWarning?: boolean;\n};\n\n/**\n * Stops callbacks from running.\n *\n * @public\n */\nexport type Unsubscribe<T> = {\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n (): void;\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n unsubscribe(): void;\n /** Get the last known value, possibly with local optimistic updates applied. */\n getCurrentValue(): T | undefined;\n /** @internal */\n getQueryLogs(): string[] | undefined;\n};\n\n/**\n * Subscribes to Convex query functions and executes mutations and actions over a WebSocket.\n *\n * Optimistic updates for mutations are not provided for this client.\n * Third party clients may choose to wrap {@link browser.BaseConvexClient} for additional control.\n *\n * ```ts\n * const client = new ConvexClient(\"https://happy-otter-123.convex.cloud\");\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages[0].body);\n * });\n * ```\n *\n * @public\n */\nexport class ConvexClient {\n private listeners: Set<QueryInfo>;\n private _client: BaseConvexClient | undefined;\n // A synthetic server event to run callbacks the first time\n private callNewListenersWithCurrentValuesTimer:\n | ReturnType<typeof setTimeout>\n | undefined;\n private _closed: boolean;\n private _disabled: boolean;\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed(): boolean {\n return this._closed;\n }\n get client(): BaseConvexClient {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled(): boolean {\n return this._disabled;\n }\n\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address: string, options: ConvexClientOptions = {}) {\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (\n defaultWebSocketConstructor &&\n !(\"webSocketConstructor\" in baseOptions) &&\n typeof WebSocket === \"undefined\"\n ) {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (\n typeof window === \"undefined\" &&\n !(\"unsavedChangesWarning\" in baseOptions)\n ) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n (updatedQueries) => this._transition(updatedQueries),\n baseOptions,\n );\n }\n this.listeners = new Set();\n }\n\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: FunctionArgs<Query>,\n callback: (result: FunctionReturnType<Query>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<Query[\"_returnType\"]> {\n if (this.disabled) {\n const disabledUnsubscribe = (() => {}) as Unsubscribe<\n Query[\"_returnType\"]\n >;\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<Query[\"_returnType\"]>\n > = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => undefined,\n getQueryLogs: () => undefined,\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n\n // BaseConvexClient takes care of deduplicating queries subscriptions...\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args,\n );\n\n // ...but we still need to bookkeep callbacks to actually call them.\n const queryInfo: QueryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n this.queryResultReady(queryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<Query[\"_returnType\"]>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken),\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n Query[\"_returnType\"]\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n private callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = undefined;\n this._transition([], true);\n }\n\n private queryResultReady(queryToken: QueryToken): boolean {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n\n async close() {\n if (this.disabled) return;\n // prevent pending updates\n this.listeners.clear();\n this._closed = true;\n return this.client.close();\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n\n /**\n * @internal\n */\n _transition(updatedQueries: QueryToken[], callNewListeners = false) {\n // Deduping subscriptions happens in the BaseConvexClient, so not much to do here.\n\n // Call all callbacks in the order they were registered\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n if (\n updatedQueries.includes(queryToken) ||\n (callNewListeners &&\n !hasEverRun &&\n this.client.hasLocalQueryResultByToken(queryToken))\n ) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n newValue = this.client.localQueryResultByToken(queryToken);\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\",\n );\n } else {\n // Make some noise without unsubscribing or failing to call other callbacks.\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\",\n );\n }\n }\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n options?: MutationOptions,\n ): Promise<Awaited<FunctionReturnType<Mutation>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n args: FunctionArgs<Action>,\n ): Promise<Awaited<FunctionReturnType<Action>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n ): Promise<Awaited<Query[\"_returnType\"]>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args) as\n | Awaited<Query[\"_returnType\"]>\n | undefined;\n if (value !== undefined) return Promise.resolve(value);\n\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value) => {\n unsubscribe();\n resolve(value);\n },\n (e: Error) => {\n unsubscribe();\n reject(e);\n },\n );\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n if (this.disabled) return () => {};\n return this.client.subscribeToConnectionState(cb);\n }\n}\n\n// internal information tracked about each registered callback\ntype QueryInfo = {\n callback: (result: any, meta: unknown) => unknown;\n onError: ((e: Error, meta: unknown) => unknown) | undefined;\n unsubscribe: () => void;\n queryToken: QueryToken;\n hasEverRun: boolean;\n // query and args are just here for debugging, the queryToken is authoritative\n query: FunctionReference<\"query\">;\n args: any;\n};\n\ntype RemoveCallSignature<T> = Omit<T, never>;\n","'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/<platform>-<arch>\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import {\n ConvexClient,\n setDefaultWebSocketConstructor,\n} from \"./simple_client.js\";\n\n// This file is compiled with `bundle: true` with an exception for\n// `./simple_client.js` so this \"ws\" import will be inlined.\nimport ws from \"ws\";\nconst nodeWebSocket = ws as unknown as typeof WebSocket;\n\nsetDefaultWebSocketConstructor(nodeWebSocket);\n\nexport { ConvexClient };\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","import { ConvexHttpClient } from \"convex/browser\";\n\nexport const dbClient = () => {\n const convexUrl = process.env.CONVEX_URL;\n if (!convexUrl) {\n throw new Error(\"CONVEX_URL is not set\");\n }\n return new ConvexHttpClient(convexUrl);\n};\n","import { v } from \"../values/validator.js\";\n\n/**\n * An opaque identifier used for paginating a database query.\n *\n * Cursors are returned from {@link OrderedQuery.paginate} and represent the\n * point of the query where the page of results ended.\n *\n * To continue paginating, pass the cursor back into\n * {@link OrderedQuery.paginate} in the {@link PaginationOptions} object to\n * fetch another page of results.\n *\n * Note: Cursors can only be passed to _exactly_ the same database query that\n * they were generated from. You may not reuse a cursor between different\n * database queries.\n *\n * @public\n */\nexport type Cursor = string;\n\n/**\n * The result of paginating using {@link OrderedQuery.paginate}.\n *\n * @public\n */\nexport interface PaginationResult<T> {\n /**\n * The page of results.\n */\n page: T[];\n\n /**\n * Have we reached the end of the results?\n */\n isDone: boolean;\n\n /**\n * A {@link Cursor} to continue loading more results.\n */\n continueCursor: Cursor;\n\n /**\n * A {@link Cursor} to split the page into two, so the page from\n * (cursor, continueCursor] can be replaced by two pages (cursor, splitCursor]\n * and (splitCursor, continueCursor].\n */\n splitCursor?: Cursor | null;\n\n /**\n * When a query reads too much data, it may return 'SplitRecommended' to\n * indicate that the page should be split into two with `splitCursor`.\n * When a query reads so much data that `page` might be incomplete, its status\n * becomes 'SplitRequired'.\n */\n pageStatus?: \"SplitRecommended\" | \"SplitRequired\" | null;\n}\n\n/**\n * The options passed to {@link OrderedQuery.paginate}.\n *\n * To use this type in [argument validation](https://docs.convex.dev/functions/validation),\n * use the {@link paginationOptsValidator}.\n *\n * @public\n */\nexport interface PaginationOptions {\n /**\n * Number of items to load in this page of results.\n *\n * Note: This is only an initial value!\n *\n * If you are running this paginated query in a reactive query function, you\n * may receive more or less items than this if items were added to or removed\n * from the query range.\n */\n numItems: number;\n\n /**\n * A {@link Cursor} representing the start of this page or `null` to start\n * at the beginning of the query results.\n */\n cursor: Cursor | null;\n\n /**\n * A {@link Cursor} representing the end of this page or `null | undefined` to\n * use `numItems` instead.\n *\n * @internal\n */\n endCursor?: Cursor | null;\n\n /**\n * The maximum number of rows that should be read from the database.\n *\n * This option is different from `numItems` in that it controls the number of rows entering a query's\n * pipeline, where `numItems` controls the number of rows coming out. For example, a `filter`\n * may disqualify most of the rows coming in, so setting a low `numItems` would not help\n * bound its execution time. Instead, set a low `maximumRowsRead` to efficiently paginate\n * through the filter.\n *\n * Currently this is not enforced for search queries.\n *\n * @internal\n */\n maximumRowsRead?: number;\n\n /**\n * The maximum number of bytes that should be read from the database.\n *\n * As with {@link PaginationOptions.maximumRowsRead}, this affects the number\n * of rows entering a query's pipeline.\n *\n * Once a paginated query hits its bytes read budget, an incomplete page\n * will be returned.\n *\n * Currently this is not enforced for search queries.\n *\n * @internal\n */\n maximumBytesRead?: number;\n}\n\n/**\n * A {@link values.Validator} for {@link PaginationOptions}.\n *\n * This includes the standard {@link PaginationOptions} properties along with\n * an optional cache-busting `id` property used by {@link react.usePaginatedQuery}.\n *\n * @public\n */\nexport const paginationOptsValidator = v.object({\n numItems: v.number(),\n cursor: v.union(v.string(), v.null()),\n endCursor: v.optional(v.union(v.string(), v.null())),\n id: v.optional(v.number()),\n maximumRowsRead: v.optional(v.number()),\n maximumBytesRead: v.optional(v.number()),\n});\n","/**\n * Utilities for defining the schema of your Convex project.\n *\n * ## Usage\n *\n * Schemas should be placed in a `schema.ts` file in your `convex/` directory.\n *\n * Schema definitions should be built using {@link defineSchema},\n * {@link defineTable}, and {@link values.v}. Make sure to export the schema as the\n * default export.\n *\n * ```ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * messages: defineTable({\n * body: v.string(),\n * user: v.id(\"users\"),\n * }),\n * users: defineTable({\n * name: v.string(),\n * }),\n * });\n * ```\n *\n * To learn more about schemas, see [Defining a Schema](https://docs.convex.dev/using/schemas).\n * @module\n */\nimport {\n AnyDataModel,\n GenericDataModel,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n TableNamesInDataModel,\n} from \"../server/data_model.js\";\nimport {\n IdField,\n IndexTiebreakerField,\n SystemFields,\n SystemIndexes,\n} from \"../server/system_fields.js\";\nimport { Expand } from \"../type_utils.js\";\nimport {\n GenericValidator,\n ObjectType,\n isValidator,\n v,\n} from \"../values/validator.js\";\nimport { VObject, Validator } from \"../values/validators.js\";\n\n/**\n * Extract all of the index field paths within a {@link Validator}.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof SystemFields;\n\n/**\n * Extract the {@link GenericDocument} within a {@link Validator} and\n * add on the system fields.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractDocument<T extends Validator<any, any, any>> =\n // Add the system fields to `Value` (except `_id` because it depends on\n //the table name) and trick TypeScript into expanding them.\n Expand<SystemFields & T[\"type\"]>;\n\nexport interface DbIndexConfig<\n FirstFieldPath extends string,\n RestFieldPaths extends string[],\n> {\n /**\n * The fields to index, in order. Must specify at least one field.\n */\n fields: [FirstFieldPath, ...RestFieldPaths];\n}\n\n/**\n * The configuration for a full text search index.\n *\n * @public\n */\nexport interface SearchIndexConfig<\n SearchField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for full text search.\n *\n * This must be a field of type `string`.\n */\n searchField: SearchField;\n\n /**\n * Additional fields to index for fast filtering when running search queries.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * The configuration for a vector index.\n *\n * @public\n */\nexport interface VectorIndexConfig<\n VectorField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for vector search.\n *\n * This must be a field of type `v.array(v.float64())` (or a union)\n */\n vectorField: VectorField;\n /**\n * The length of the vectors indexed. This must be between 2 and 2048 inclusive.\n */\n dimensions: number;\n /**\n * Additional fields to index for fast filtering when running vector searches.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * @internal\n */\nexport type VectorIndex = {\n indexDescriptor: string;\n vectorField: string;\n dimensions: number;\n filterFields: string[];\n};\n\n/**\n * @internal\n */\nexport type Index = {\n indexDescriptor: string;\n fields: string[];\n};\n\n/**\n * @internal\n */\nexport type SearchIndex = {\n indexDescriptor: string;\n searchField: string;\n filterFields: string[];\n};\n\n/**\n * Options for defining an index.\n *\n * @public\n */\nexport interface IndexOptions {\n /**\n * Whether the index should be staged.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n */\n staged?: boolean;\n}\n\n/**\n * The definition of a table within a schema.\n *\n * This should be produced by using {@link defineTable}.\n * @public\n */\nexport class TableDefinition<\n DocumentType extends Validator<any, any, any> = Validator<any, any, any>,\n Indexes extends GenericTableIndexes = {},\n SearchIndexes extends GenericTableSearchIndexes = {},\n VectorIndexes extends GenericTableVectorIndexes = {},\n> {\n private indexes: Index[];\n private stagedDbIndexes: Index[];\n private searchIndexes: SearchIndex[];\n private stagedSearchIndexes: SearchIndex[];\n private vectorIndexes: VectorIndex[];\n private stagedVectorIndexes: VectorIndex[];\n // The type of documents stored in this table.\n validator: DocumentType;\n\n /**\n * @internal\n */\n constructor(documentType: DocumentType) {\n this.indexes = [];\n this.stagedDbIndexes = [];\n this.searchIndexes = [];\n this.stagedSearchIndexes = [];\n this.vectorIndexes = [];\n this.stagedVectorIndexes = [];\n this.validator = documentType;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Returns indexes defined on this table.\n * Intended for the advanced use cases of dynamically deciding which index to use for a query.\n * If you think you need this, please chime in on ths issue in the Convex JS GitHub repo.\n * https://github.com/get-convex/convex-js/issues/49\n */\n \" indexes\"(): { indexDescriptor: string; fields: string[] }[] {\n return this.indexes;\n }\n\n /**\n * Define an index on this table.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define an index on this table.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param fields - The fields to index, in order. Must specify at least one\n * field.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define a staged index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig:\n | Expand<DbIndexConfig<FirstFieldPath, RestFieldPaths> & IndexOptions>\n | [FirstFieldPath, ...RestFieldPaths],\n ) {\n if (Array.isArray(indexConfig)) {\n // indexConfig is [FirstFieldPath, ...RestFieldPaths]\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig,\n });\n } else if (indexConfig.staged) {\n // indexConfig is object with fields and staged: true\n this.stagedDbIndexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n } else {\n // indexConfig is object with fields (and maybe staged: false/undefined)\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n }\n return this;\n }\n\n /**\n * Define a search index on this table.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n // Update `SearchIndexes` to include the new index and use `Expand` to make\n // the types look pretty in editors.\n Expand<\n SearchIndexes &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes\n >;\n\n /**\n * Define a staged search index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedSearchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.searchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Define a vector index on this table.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n Expand<\n VectorIndexes &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n\n /**\n * Define a staged vector index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedVectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.vectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Work around for https://github.com/microsoft/TypeScript/issues/57035\n */\n protected self(): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n VectorIndexes\n > {\n return this;\n }\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export() {\n const documentType = this.validator.json;\n if (typeof documentType !== \"object\") {\n throw new Error(\n \"Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n\n return {\n indexes: this.indexes,\n stagedDbIndexes: this.stagedDbIndexes,\n searchIndexes: this.searchIndexes,\n stagedSearchIndexes: this.stagedSearchIndexes,\n vectorIndexes: this.vectorIndexes,\n stagedVectorIndexes: this.stagedVectorIndexes,\n documentType,\n };\n }\n}\n\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Validator<Record<string, any>, \"required\", any>,\n>(documentSchema: DocumentSchema): TableDefinition<DocumentSchema>;\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Record<string, GenericValidator>,\n>(\n documentSchema: DocumentSchema,\n): TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>;\nexport function defineTable<\n DocumentSchema extends\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n>(documentSchema: DocumentSchema): TableDefinition<any, any, any> {\n if (isValidator(documentSchema)) {\n return new TableDefinition(documentSchema);\n } else {\n return new TableDefinition(v.object(documentSchema));\n }\n}\n\n/**\n * A type describing the schema of a Convex project.\n *\n * This should be constructed using {@link defineSchema}, {@link defineTable},\n * and {@link v}.\n * @public\n */\nexport type GenericSchema = Record<string, TableDefinition>;\n\n/**\n *\n * The definition of a Convex project schema.\n *\n * This should be produced by using {@link defineSchema}.\n * @public\n */\nexport class SchemaDefinition<\n Schema extends GenericSchema,\n StrictTableTypes extends boolean,\n> {\n public tables: Schema;\n public strictTableNameTypes!: StrictTableTypes;\n public readonly schemaValidation: boolean;\n\n /**\n * @internal\n */\n constructor(tables: Schema, options?: DefineSchemaOptions<StrictTableTypes>) {\n this.tables = tables;\n this.schemaValidation =\n options?.schemaValidation === undefined ? true : options.schemaValidation;\n }\n\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export(): string {\n return JSON.stringify({\n tables: Object.entries(this.tables).map(([tableName, definition]) => {\n const {\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n } = definition.export();\n return {\n tableName,\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n };\n }),\n schemaValidation: this.schemaValidation,\n });\n }\n}\n\n/**\n * Options for {@link defineSchema}.\n *\n * @public\n */\nexport interface DefineSchemaOptions<StrictTableNameTypes extends boolean> {\n /**\n * Whether Convex should validate at runtime that all documents match\n * your schema.\n *\n * If `schemaValidation` is `true`, Convex will:\n * 1. Check that all existing documents match your schema when your schema\n * is pushed.\n * 2. Check that all insertions and updates match your schema during mutations.\n *\n * If `schemaValidation` is `false`, Convex will not validate that new or\n * existing documents match your schema. You'll still get schema-specific\n * TypeScript types, but there will be no validation at runtime that your\n * documents match those types.\n *\n * By default, `schemaValidation` is `true`.\n */\n schemaValidation?: boolean;\n\n /**\n * Whether the TypeScript types should allow accessing tables not in the schema.\n *\n * If `strictTableNameTypes` is `true`, using tables not listed in the schema\n * will generate a TypeScript compilation error.\n *\n * If `strictTableNameTypes` is `false`, you'll be able to access tables not\n * listed in the schema and their document type will be `any`.\n *\n * `strictTableNameTypes: false` is useful for rapid prototyping.\n *\n * Regardless of the value of `strictTableNameTypes`, your schema will only\n * validate documents in the tables listed in the schema. You can still create\n * and modify other tables on the dashboard or in JavaScript mutations.\n *\n * By default, `strictTableNameTypes` is `true`.\n */\n strictTableNameTypes?: StrictTableNameTypes;\n}\n\n/**\n * Define the schema of this Convex project.\n *\n * This should be exported from a `schema.ts` file in your `convex/` directory\n * like:\n *\n * ```ts\n * export default defineSchema({\n * ...\n * });\n * ```\n *\n * @param schema - A map from table name to {@link TableDefinition} for all of\n * the tables in this project.\n * @param options - Optional configuration. See {@link DefineSchemaOptions} for\n * a full description.\n * @returns The schema.\n *\n * @public\n */\nexport function defineSchema<\n Schema extends GenericSchema,\n StrictTableNameTypes extends boolean = true,\n>(\n schema: Schema,\n options?: DefineSchemaOptions<StrictTableNameTypes>,\n): SchemaDefinition<Schema, StrictTableNameTypes> {\n return new SchemaDefinition(schema, options);\n}\n\n/**\n * Internal type used in Convex code generation!\n *\n * Convert a {@link SchemaDefinition} into a {@link server.GenericDataModel}.\n *\n * @public\n */\nexport type DataModelFromSchemaDefinition<\n SchemaDef extends SchemaDefinition<any, boolean>,\n> = MaybeMakeLooseDataModel<\n {\n [TableName in keyof SchemaDef[\"tables\"] &\n string]: SchemaDef[\"tables\"][TableName] extends TableDefinition<\n infer DocumentType,\n infer Indexes,\n infer SearchIndexes,\n infer VectorIndexes\n >\n ? {\n // We've already added all of the system fields except for `_id`.\n // Add that here.\n document: Expand<IdField<TableName> & ExtractDocument<DocumentType>>;\n fieldPaths:\n | keyof IdField<TableName>\n | ExtractFieldPaths<DocumentType>;\n indexes: Expand<Indexes & SystemIndexes>;\n searchIndexes: SearchIndexes;\n vectorIndexes: VectorIndexes;\n }\n : never;\n },\n SchemaDef[\"strictTableNameTypes\"]\n>;\n\ntype MaybeMakeLooseDataModel<\n DataModel extends GenericDataModel,\n StrictTableNameTypes extends boolean,\n> = StrictTableNameTypes extends true\n ? DataModel\n : Expand<DataModel & AnyDataModel>;\n\nconst _systemSchema = defineSchema({\n _scheduled_functions: defineTable({\n name: v.string(),\n args: v.array(v.any()),\n scheduledTime: v.float64(),\n completedTime: v.optional(v.float64()),\n state: v.union(\n v.object({ kind: v.literal(\"pending\") }),\n v.object({ kind: v.literal(\"inProgress\") }),\n v.object({ kind: v.literal(\"success\") }),\n v.object({ kind: v.literal(\"failed\"), error: v.string() }),\n v.object({ kind: v.literal(\"canceled\") }),\n ),\n }),\n _storage: defineTable({\n sha256: v.string(),\n size: v.float64(),\n contentType: v.optional(v.string()),\n }),\n});\n\nexport interface SystemDataModel\n extends DataModelFromSchemaDefinition<typeof _systemSchema> {}\n\nexport type SystemTableNames = TableNamesInDataModel<SystemDataModel>;\n","/* eslint-disable */\n/**\n * Generated `api` utility.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport { anyApi } from \"convex/server\";\n\n/**\n * A utility for referencing Convex functions in your app's API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = api.myModule.myFunction;\n * ```\n */\nexport const api = anyApi;\nexport const internal = anyApi;\n","import { dbClient } from \".\";\nimport { api } from \"../../_generated/api\";\n\nexport const getUserIdFromApiKeyOrNull = async (apiKey: string) => {\n const db = dbClient();\n const user = await db.mutation(\n api.apiKeys.validateApiKeyAndReturnUserIdOrNull,\n { apiKey },\n );\n if (!user) {\n throw new Error(\"Invalid API key\");\n }\n return user;\n};\n","import { z, ZodTypeAny } from \"zod\";\nimport type {\n LogHandler,\n MastraMCPServerDefinition,\n MCPClientOptions,\n} from \"@mastra/mcp\";\nimport { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { ClientCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\nimport { tool, type Tool as VercelTool, type ToolCallOptions } from \"ai\";\n\nexport const AdvancedConfigSchema = z\n .object({\n system: z.string().optional(),\n temperature: z.number().optional(),\n toolChoice: z.string().optional(),\n })\n .passthrough(); // Allow additional fields\n\nexport const TestCaseSchema = z.object({\n title: z.string(),\n query: z.string(),\n runs: z.number().int(),\n model: z.string(),\n provider: z.string(),\n expectedToolCalls: z.array(z.string()),\n judgeRequirement: z.string().optional(),\n advancedConfig: AdvancedConfigSchema.optional(),\n});\n\nexport type TestCase = z.infer<typeof TestCaseSchema>;\n\nexport function validateTestCase(value: unknown): TestCase[] {\n try {\n const result = z.array(TestCaseSchema).parse(value);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(error.message);\n }\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n\nconst BaseServerOptionsSchema = z.object({\n logger: z.custom<LogHandler>().optional(),\n timeout: z.number().optional(),\n capabilities: z.custom<ClientCapabilities>().optional(),\n enableServerLogs: z.boolean().optional(),\n});\n\nconst StdioServerDefinitionSchema = BaseServerOptionsSchema.extend({\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict();\n\nconst HttpServerDefinitionSchema = BaseServerOptionsSchema.extend({\n // Accept either a URL object or a string URL, but we'll normalize to string\n url: z.union([z.string().url(), z.instanceof(URL)]),\n requestInit: z\n .custom<StreamableHTTPClientTransportOptions[\"requestInit\"]>()\n .optional(),\n eventSourceInit: z\n .custom<SSEClientTransportOptions[\"eventSourceInit\"]>()\n .optional(),\n authProvider: z\n .custom<StreamableHTTPClientTransportOptions[\"authProvider\"]>()\n .optional(),\n reconnectionOptions: z\n .custom<StreamableHTTPClientTransportOptions[\"reconnectionOptions\"]>()\n .optional(),\n sessionId: z\n .custom<StreamableHTTPClientTransportOptions[\"sessionId\"]>()\n .optional(),\n}).strict();\n\nexport const MCPClientOptionsSchema = z.custom<MCPClientOptions>();\nexport const MastraMCPServerDefinitionSchema = z.union([\n StdioServerDefinitionSchema,\n HttpServerDefinitionSchema,\n]);\n\nexport function validateAndNormalizeMCPClientConfiguration(\n value: unknown,\n): MCPClientOptions {\n try {\n const envParsed = MCPClientOptionsSchema.parse(value);\n\n const normalizedServers: Record<string, MastraMCPServerDefinition> = {};\n\n for (const [name, server] of Object.entries(envParsed.servers)) {\n try {\n if (server && typeof server === \"object\" && \"url\" in server) {\n MastraMCPServerDefinitionSchema.parse(server);\n const urlValue = (server as any).url;\n const normalizedUrl =\n typeof urlValue === \"string\"\n ? new URL(urlValue)\n : (urlValue as URL);\n const normalizedServer = {\n ...(server as Record<string, any>),\n url: normalizedUrl,\n } as Record<string, any>;\n normalizedServers[name] =\n normalizedServer as MastraMCPServerDefinition;\n } else {\n MastraMCPServerDefinitionSchema.parse(server);\n normalizedServers[name] = server;\n }\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Invalid server configuration for '${name}': ${error.message}`,\n );\n }\n throw new Error(`Invalid server configuration for '${name}': ${error}`);\n }\n }\n\n return {\n ...envParsed,\n servers: normalizedServers,\n };\n } catch (error) {\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n\ntype MastraToolExecuteArgs = {\n context?: unknown;\n runtimeContext?: unknown;\n};\n\ntype MastraToolInstance = {\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n execute?: (\n args: MastraToolExecuteArgs,\n options?: ToolCallOptions,\n ) => Promise<unknown> | unknown;\n};\n\nconst fallbackInputSchema = z.object({}).passthrough();\n\nfunction isZodSchema(value: unknown): value is ZodTypeAny {\n return Boolean(\n value && typeof value === \"object\" && \"safeParse\" in (value as ZodTypeAny),\n );\n}\n\nfunction ensureInputSchema(schema: unknown): ZodTypeAny {\n if (isZodSchema(schema)) {\n return schema;\n }\n\n return fallbackInputSchema;\n}\n\nfunction ensureOutputSchema(schema: unknown): ZodTypeAny | undefined {\n if (isZodSchema(schema)) {\n return schema;\n }\n\n return undefined;\n}\n\nfunction extractPureToolName(toolKey: string): string {\n const separatorIndex = toolKey.indexOf(\"_\");\n\n if (separatorIndex === -1 || separatorIndex === toolKey.length - 1) {\n return toolKey;\n }\n\n return toolKey.slice(separatorIndex + 1);\n}\n\nexport function convertMastraToolToVercelTool(\n toolName: string,\n mastraTool: MastraToolInstance,\n options?: { originalName?: string },\n): VercelTool {\n const inputSchema = ensureInputSchema(mastraTool.inputSchema);\n const outputSchema = ensureOutputSchema(mastraTool.outputSchema);\n const displayName = options?.originalName ?? toolName;\n\n const vercelToolConfig: {\n type: \"dynamic\";\n description?: string;\n inputSchema: ZodTypeAny;\n outputSchema?: ZodTypeAny;\n execute?: (input: unknown, options: ToolCallOptions) => Promise<unknown>;\n } = {\n type: \"dynamic\",\n description: mastraTool.description,\n inputSchema,\n };\n\n if (outputSchema) {\n vercelToolConfig.outputSchema = outputSchema;\n }\n\n if (typeof mastraTool.execute === \"function\") {\n vercelToolConfig.execute = async (input, options) => {\n const executionArgs: MastraToolExecuteArgs = { context: input };\n\n if (options) {\n executionArgs.runtimeContext = options;\n }\n\n const result = await mastraTool.execute?.(executionArgs, options);\n\n if (outputSchema) {\n const parsed = outputSchema.safeParse(result);\n\n if (!parsed.success) {\n throw new Error(\n `Mastra tool '${displayName}' returned invalid output: ${parsed.error.message}`,\n );\n }\n\n return parsed.data;\n }\n\n return result;\n };\n }\n\n return tool(vercelToolConfig);\n}\n\nexport function convertMastraToolsToVercelTools(\n mastraTools: Record<string, MastraToolInstance>,\n): Record<string, VercelTool> {\n return Object.fromEntries(\n Object.entries(mastraTools).map(([name, mastraTool]) => {\n const pureToolName = extractPureToolName(name);\n\n return [\n pureToolName,\n convertMastraToolToVercelTool(pureToolName, mastraTool, {\n originalName: name,\n }),\n ];\n }),\n );\n}\n\nexport const LlmsConfigSchema = z\n .object({\n anthropic: z.string().optional(),\n openai: z.string().optional(),\n openrouter: z.string().optional(),\n })\n .passthrough(); // Allow additional LLM providers\n\nexport type LlmsConfig = z.infer<typeof LlmsConfigSchema>;\n\nexport function validateLlms(value: unknown): LlmsConfig {\n try {\n const result = LlmsConfigSchema.parse(value);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Invalid LLMs configuration: ${error.message}`);\n }\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n","import { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { LlmsConfig } from \"./validators\";\nimport { LanguageModel, ToolSet, TypedToolCall } from \"ai\";\n\nexport const createLlmModel = (\n provider: string,\n model: string,\n llmsConfig: LlmsConfig,\n): LanguageModel => {\n if (!llmsConfig[provider]) {\n throw new Error(`LLM API key not found for provider: ${provider}`);\n }\n switch (provider) {\n case \"anthropic\":\n return createAnthropic({ apiKey: llmsConfig.anthropic })(model);\n case \"openai\":\n return createOpenAI({ apiKey: llmsConfig.openai })(model);\n case \"openrouter\":\n return createOpenRouter({ apiKey: llmsConfig.openrouter })(model);\n default:\n throw new Error(`Unsupported provider: ${provider}`);\n }\n};\n\nexport const extractToolNamesAsArray = (\n toolCalls: TypedToolCall<ToolSet>[],\n) => {\n return toolCalls.map((toolCall) => toolCall.toolName);\n};\n","export type EvaluationResult = {\n expectedToolCalls: string[];\n toolsCalled: string[];\n missing: string[];\n unexpected: string[];\n passed: boolean;\n};\n\nexport const evaluateResults = (\n expectedToolCalls: string[],\n toolsCalled: string[],\n) => {\n return {\n expectedToolCalls,\n toolsCalled,\n missing: expectedToolCalls.filter((tool) => !toolsCalled.includes(tool)),\n unexpected: toolsCalled.filter((tool) => !expectedToolCalls.includes(tool)),\n passed:\n expectedToolCalls.length === toolsCalled.length &&\n expectedToolCalls.every((tool) => toolsCalled.includes(tool)),\n };\n};\n","{\n \"name\": \"@mcpjam/cli\",\n \"version\": \"1.1.2\",\n \"type\": \"module\",\n \"description\": \"MCPJam CLI for programmatic MCP testing and evals\",\n \"license\": \"Apache-2.0\",\n \"author\": \"MCPJam (https://mcpjam.com)\",\n \"homepage\": \"https://mcpjam.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/MCPJam/inspector.git\",\n \"directory\": \"cli\"\n },\n \"main\": \"dist/index.js\",\n \"bin\": {\n \"mcpjam\": \"bin/mcpjam.js\"\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"package.json\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"build-and-test\": \"npm run build && npm run test\",\n \"test\": \"node bin/mcpjam.js evals run -t examples/test-servers.json -e examples/mcp-environment.json -l examples/llms.json\",\n \"start\": \"node bin/mcpjam.js\"\n },\n \"dependencies\": {\n \"@ai-sdk/anthropic\": \"^2.0.17\",\n \"@ai-sdk/openai\": \"^2.0.32\",\n \"@hono/node-server\": \"^1.13.7\",\n \"@mastra/core\": \"^0.13.2\",\n \"@mastra/mcp\": \"^0.10.12\",\n \"@modelcontextprotocol/sdk\": \"^1.17.3\",\n \"@openrouter/ai-sdk-provider\": \"^1.2.0\",\n \"ai\": \"^5.0.11\",\n \"chalk\": \"^5.6.0\",\n \"cli-table3\": \"^0.6.5\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^17.2.2\",\n \"hono\": \"^4.6.11\",\n \"ollama-ai-provider\": \"^1.2.0\",\n \"update-notifier\": \"^7.3.1\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20\",\n \"@types/update-notifier\": \"^6.0.8\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5\"\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,WAAAA,gBAAe;AACxB,SAAS,iBAAAC,sBAAqB;;;ACF9B,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB,SAAS,eAAe;;;ACFxB,OAAO,WAAW;AA6ClB,IAAM,qBAAqB;AAEpB,IAAM,SAAN,MAAa;AAAA,EAClB,OAAe,eAEJ;AAAA,EAEX,OAAe,oBAA0B;AACvC,QAAI,KAAK,cAAc;AACrB,cAAQ,OAAO,MAAM,IAAI;AACzB,WAAK,eAAe;AAAA,IACtB;AAAA,EACF;AAAA,EAEA,OAAe,YACb,MACA,aACM;AACN,SAAK,kBAAkB;AACvB,UAAM,SAAS,KAAK,OAAO,WAAW,IAAI,KAAK,UAAU,IAAI,IAAI;AACjE,YAAQ,OAAO,MAAM,MAAM;AAC3B,SAAK,eAAe,EAAE,MAAM,YAAY;AAAA,EAC1C;AAAA,EAEA,OAAe,eAAe,MAAoB;AAChD,QAAI,CAAC,KAAK,cAAc;AACtB,WAAK,YAAY,aAAa,CAAC;AAAA,IACjC;A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icField","__publicField","name","__publicField","__publicField","name","resolve","createWebSocketStream","err","name","resolve","dir","arr","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","code","Receiver","Sender","v","URL","WebSocket","key","protocol","WebSocketServer","version","__publicField","name","name","options","tool","require","createRequire","version","Command"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/evals/index.ts","../src/utils/logger.ts","../src/evals/runner.ts","../../node_modules/convex/src/index.ts","../../node_modules/convex/src/values/base64.ts","../../node_modules/convex/src/common/index.ts","../../node_modules/convex/src/values/value.ts","../../node_modules/convex/src/values/errors.ts","../../node_modules/convex/src/values/compare_utf8.ts","../../node_modules/convex/src/browser/logging.ts","../../node_modules/convex/src/server/functionName.ts","../../node_modules/convex/src/server/components/paths.ts","../../node_modules/convex/src/server/api.ts","../../node_modules/convex/src/browser/long.ts","../../node_modules/jwt-decode/build/esm/index.js","../../node_modules/convex/src/browser/sync/authentication_manager.ts","../../node_modules/convex/src/browser/http_client.ts","../../node_modules/convex/src/browser/simple_client.ts","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/stream.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/constants.js","../../node_modules/common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js","../../node_modules/common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js","../../node_modules/common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js","../../node_modules/common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/buffer-util.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/limiter.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/permessage-deflate.js","../../node_modules/common/temp/node_modules/.pnpm/utf-8-validate@5.0.10/node_modules/utf-8-validate/fallback.js","../../node_modules/common/temp/node_modules/.pnpm/utf-8-validate@5.0.10/node_modules/utf-8-validate/index.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/validation.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/receiver.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/sender.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/event-target.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/extension.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/websocket.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/subprotocol.js","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/lib/websocket-server.js","../../node_modules/convex/src/browser/simple_client-node.ts","../../node_modules/common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9_utf-8-validate@5.0.10/node_modules/ws/wrapper.mjs","../src/db/index.ts","../src/db/user.ts","../src/db/tests.ts","../src/utils/validators.ts","../../shared/tools.ts","../src/utils/helpers.ts","../src/evals/evaluator.ts","../src/utils/user-id.ts","../src/utils/hog.ts","../package.json"],"sourcesContent":["import { config } from \"dotenv\";\nimport { Command } from \"commander\";\nimport { createRequire } from \"module\";\nimport { evalsCommand } from \"./evals/index\";\nimport updateNotifier from \"update-notifier\";\nimport packageJson from \"../package.json\" assert { type: \"json\" };\nconst require = createRequire(import.meta.url);\n\nupdateNotifier({ pkg: packageJson, updateCheckInterval: 0 }).notify();\n\nconst { name, version } = require(\"../package.json\") as {\n name: string;\n version: string;\n};\n\nupdateNotifier({ pkg: { name, version } }).notify();\n\n// Load environment-specific .env file\nconst envFile =\n process.env.NODE_ENV === \"production\"\n ? \".env.production\"\n : \".env.development\";\nconfig({ path: envFile });\n\nconst program = new Command();\n\nprogram\n .name(\"mcpjam\")\n .description(\"MCPJam CLI for programmatic MCP testing\")\n .version(version);\n\nprogram.addCommand(evalsCommand);\n\nprogram.parse();\n","import { Command } from \"commander\";\nimport { readFile } from \"fs/promises\";\nimport { resolve } from \"path\";\nimport { Logger } from \"../utils/logger.js\";\nimport { runEvals } from \"./runner.js\";\nimport { hogClient } from \"../utils/hog.js\";\nimport { getUserId } from \"../utils/user-id.js\";\n\n// node dist/index.js evals run -t examples/test-servers.json -e examples/mcp-environment.json\n\nexport const evalsCommand = new Command(\"evals\");\n\nevalsCommand\n .description(\"Run MCP evaluations\")\n .command(\"run\")\n .description(\"Run tests against MCP servers\")\n .requiredOption(\"-t, --tests <file>\", \"Path to tests JSON file\")\n .requiredOption(\"-e, --environment <file>\", \"Path to environment JSON file\")\n .requiredOption(\"-l, --llms <file>\", \"Path to LLMs JSON file\")\n .option(\"-a, --api-key <key>\", \"Personal access key\")\n .action(async (options) => {\n try {\n hogClient.capture({\n distinctId: getUserId(),\n event: \"evals cli ran\",\n properties: {\n environment: process.env.ENVIRONMENT,\n }\n });\n const testsContent = await readFile(resolve(options.tests), \"utf8\");\n const testsData = JSON.parse(testsContent);\n\n // Read and parse environment file\n const envContent = await readFile(resolve(options.environment), \"utf8\");\n const envData = JSON.parse(envContent);\n\n // Read and parse LLMs file\n const llmsContent = await readFile(resolve(options.llms), \"utf8\");\n const llmsData = JSON.parse(llmsContent);\n\n // Read API token (optional)\n const apiKey = options.apiKey;\n runEvals(testsData, envData, llmsData, apiKey);\n } catch (error) {\n Logger.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n });\n","import chalk from \"chalk\";\nimport type { ModelMessage } from \"ai\";\n\ntype MessageContent = string | Record<string, unknown> | MessageContent[];\n\ntype ToolSummaryOptions = {\n expected: string[];\n actual: string[];\n passed: boolean;\n missing?: string[];\n unexpected?: string[];\n};\n\ntype ConversationOptions = {\n messages: ModelMessage[];\n};\n\ntype ToolCallSummary = {\n toolName: string;\n args?: string;\n};\n\ntype RunResultOptions = {\n passed: boolean;\n durationMs: number;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n };\n};\n\ntype RunStartOptions = {\n runNumber: number;\n totalRuns: number;\n provider?: string;\n model?: string;\n temperature?: number;\n};\n\nconst MAX_CONTENT_LENGTH = 160;\n\nexport class Logger {\n private static activeStream: {\n role: ModelMessage[\"role\"];\n } | null = null;\n\n private static closeActiveStream(): void {\n if (this.activeStream) {\n process.stdout.write(\"\\n\");\n this.activeStream = null;\n }\n }\n\n private static startStream(role: ModelMessage[\"role\"]): void {\n this.closeActiveStream();\n const prefix = this.colorRole(role) + \": \";\n process.stdout.write(prefix);\n this.activeStream = { role };\n }\n\n private static appendToStream(text: string): void {\n if (!this.activeStream) {\n this.startStream(\"assistant\");\n }\n process.stdout.write(text);\n }\n\n private static logLine(text: string): void {\n this.closeActiveStream();\n console.log(text);\n }\n\n private static logMultiline(text: string): void {\n text.split(\"\\n\").forEach((line) => this.logLine(line));\n }\n\n static suiteIntro(options: { testCount: number; startedAt: Date }): void {\n const { testCount, startedAt } = options;\n this.logLine(\n chalk.bold.blue(\n `▸ Running ${testCount} test${testCount === 1 ? \"\" : \"s\"} (${startedAt.toISOString()})`,\n ),\n );\n }\n\n static suiteComplete(options: {\n durationMs: number;\n passed: number;\n failed: number;\n }): void {\n const { durationMs, passed, failed } = options;\n const total = passed + failed;\n const summary = `${passed}/${total} passed • ${this.formatDuration(durationMs)}`;\n const prefix = failed === 0 ? chalk.green(\"✔\") : chalk.red(\"✖\");\n this.logLine(`${prefix} ${summary}`);\n }\n\n static header(version: string): void {\n this.logLine(chalk.bold.blue(`MCPJAM CLI ${version}`));\n this.logLine(\"\");\n }\n\n static initiateTestMessage(\n serverCount: number,\n toolCount: number,\n serverNames: string[],\n testCount: number,\n ): void {\n this.logLine(\"\");\n this.logLine(chalk.bold.blue(\"Running tests\"));\n\n const serverLabel = serverCount === 1 ? \"server\" : \"servers\";\n const serverList = serverNames.length > 0 ? serverNames.join(\", \") : \"none\";\n this.logLine(\n `Connected to ${chalk.white.bold(serverCount)} ${serverLabel}: ${chalk.gray(serverList)}`,\n );\n\n const toolLabel = toolCount === 1 ? \"tool\" : \"tools\";\n this.logLine(`Found ${chalk.white.bold(toolCount)} total ${toolLabel}`);\n\n const testLabel = testCount === 1 ? \"test\" : \"tests\";\n this.logLine(`Running ${chalk.white.bold(testCount)} ${testLabel}`);\n\n this.logLine(\"\");\n }\n\n static logTestGroupTitle(\n testNumber: number,\n testName: string,\n modelProvider: string,\n modelId: string,\n ): void {\n this.logLine(chalk.cyan.bold(`Test ${testNumber}: ${testName}`));\n this.logLine(chalk.gray(`Using ${modelProvider}:${modelId}`));\n this.logLine(\"\");\n }\n\n static testRunStart(options: RunStartOptions): void {\n const { runNumber, totalRuns } = options;\n\n const parts = [`run ${runNumber}/${totalRuns}`];\n this.logLine(chalk.cyanBright(parts.join(\" • \")));\n }\n\n static conversation(options: ConversationOptions): void {\n const { messages } = options;\n\n this.closeActiveStream();\n\n if (!messages.length) {\n this.logLine(chalk.dim(\"(no messages)\"));\n return;\n }\n\n messages.forEach((message, index) => {\n if (index > 0) {\n this.logLine(\"\");\n }\n\n const roleLabel = this.colorRole(message.role);\n\n if (message.role === \"assistant\") {\n const summary = this.summarizeContent(\n message.content as MessageContent,\n );\n\n this.logMessageLines(roleLabel, summary.textLines);\n summary.toolCalls.forEach((toolCall) => {\n this.logToolCall(toolCall);\n });\n return;\n }\n\n const formatted = this.formatMessageContent(\n message.content as MessageContent,\n );\n const lines = formatted ? formatted.split(\"\\n\") : [];\n this.logMessageLines(roleLabel, lines);\n });\n }\n\n static toolSummary(options: ToolSummaryOptions) {\n const { expected, actual } = options;\n\n this.logLine(`Expected: [${expected.join(\", \") || \"—\"}]`);\n this.logLine(`Actual: [${actual.join(\", \") || \"—\"}]`);\n }\n\n static testRunResult(options: RunResultOptions): void {\n const { passed, durationMs, usage } = options;\n const status = passed ? chalk.green(\"PASS\") : chalk.red(\"FAIL\");\n this.logLine(`${status} (${this.formatDuration(durationMs)})`);\n if (usage) {\n const usageParts: string[] = [];\n\n if (typeof usage.inputTokens === \"number\") {\n usageParts.push(`input ${usage.inputTokens}`);\n }\n\n if (typeof usage.outputTokens === \"number\") {\n usageParts.push(`output ${usage.outputTokens}`);\n }\n\n if (typeof usage.totalTokens === \"number\") {\n usageParts.push(`total ${usage.totalTokens}`);\n }\n\n if (usageParts.length > 0) {\n this.logLine(chalk.gray(`Tokens • ${usageParts.join(\" • \")}`));\n }\n }\n this.logLine(\"\");\n this.logLine(\"\");\n }\n\n static info(message: string): void {\n this.logLine(chalk.blue(`ℹ ${message}`));\n }\n\n static success(message: string): void {\n this.logLine(chalk.green(`✓ ${message}`));\n }\n\n static error(message: string): void {\n this.logLine(\"\");\n this.logLine(chalk.red(`✕ Error: ${message}`));\n }\n\n static progress(current: number, total: number, testName: string): void {\n const progress = `[${current}/${total}]`;\n this.logLine(chalk.gray(`${progress} ${testName}...`));\n }\n\n static testStarting(testName: string): void {\n this.logLine(chalk.gray(` Running ${testName}...`));\n }\n\n static testError(testName: string, error: string): void {\n this.logLine(chalk.red(` ✕ ${testName} failed: ${error}`));\n }\n\n static connectionError(serverName: string, error: string): void {\n this.logLine(chalk.red(` ✕ Failed to connect to ${serverName}: ${error}`));\n }\n\n static apiKeyError(provider: string, error: string): void {\n this.logLine(chalk.red(` ✕ API key error for ${provider}: ${error}`));\n }\n\n static modelCreationError(\n provider: string,\n modelId: string,\n error: string,\n ): void {\n this.logLine(\n chalk.red(\n ` ✕ Failed to create ${provider} model \"${modelId}\": ${error}`,\n ),\n );\n }\n\n private static formatMessageContent(content: MessageContent): string {\n if (content === null || content === undefined) {\n return this.truncate(\"(empty)\");\n }\n\n if (typeof content === \"string\") {\n return this.truncate(content);\n }\n\n if (Array.isArray(content)) {\n const pieces = content\n .map((part) => this.formatMessageContent(part as MessageContent))\n .filter(Boolean);\n return this.truncate(pieces.join(\"\\n\"));\n }\n\n if (typeof content === \"object\") {\n const typedContent = content as Record<string, unknown> & {\n type?: string;\n };\n\n if (typeof typedContent.type === \"string\") {\n const type = typedContent.type;\n\n if (type === \"text\" && typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n\n if (type === \"tool-call\") {\n const toolName = typedContent.toolName ?? typedContent.name ?? \"tool\";\n const args =\n typedContent.args ?? typedContent.input ?? typedContent.parameters;\n const details = args ? ` args=${this.stringify(args)}` : \"\";\n return this.truncate(`${toolName}${details}`);\n }\n\n if (type === \"tool-result\") {\n const result =\n typedContent.result ?? typedContent.output ?? typedContent.data;\n return this.truncate(this.stringify(result));\n }\n\n if (type === \"reasoning\" && typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n }\n\n if (typeof typedContent.text === \"string\") {\n return this.truncate(typedContent.text);\n }\n\n return this.truncate(this.stringify(typedContent));\n }\n\n return this.truncate(String(content));\n }\n\n private static summarizeContent(content: MessageContent): {\n textLines: string[];\n toolCalls: ToolCallSummary[];\n } {\n const textLines: string[] = [];\n const toolCalls: ToolCallSummary[] = [];\n\n const visit = (value: MessageContent): void => {\n if (value === null || value === undefined) {\n return;\n }\n\n if (typeof value === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(value)));\n return;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item) => visit(item as MessageContent));\n return;\n }\n\n if (typeof value === \"object\") {\n const typedValue = value as Record<string, unknown> & {\n type?: string;\n };\n\n if (typedValue.type === \"tool-call\") {\n const toolName =\n (typedValue.toolName as string) ||\n (typedValue.name as string) ||\n \"tool\";\n const args =\n typedValue.args ?? typedValue.input ?? typedValue.parameters;\n toolCalls.push({\n toolName,\n args: args ? this.truncate(this.stringify(args)) : undefined,\n });\n return;\n }\n\n if (typedValue.type === \"text\" && typeof typedValue.text === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n if (\n typedValue.type === \"reasoning\" &&\n typeof typedValue.text === \"string\"\n ) {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n if (\n typedValue.type === \"tool-result\" ||\n typedValue.type === \"tool-error\"\n ) {\n const label =\n typedValue.type === \"tool-error\" ? \"Tool error\" : \"Tool result\";\n textLines.push(\n `${label}: ${this.truncate(this.stringify(typedValue))}`,\n );\n return;\n }\n\n if (typeof typedValue.text === \"string\") {\n textLines.push(...this.splitAndTrim(this.truncate(typedValue.text)));\n return;\n }\n\n textLines.push(this.truncate(this.stringify(typedValue)));\n return;\n }\n\n textLines.push(this.truncate(String(value)));\n };\n\n visit(content);\n\n const normalizedTextLines = textLines.length\n ? textLines\n : toolCalls.length\n ? []\n : [this.truncate(\"(no content)\")];\n\n return {\n textLines: normalizedTextLines,\n toolCalls,\n };\n }\n\n private static splitAndTrim(text: string): string[] {\n return text\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n }\n\n private static logMessageLines(roleLabel: string, lines: string[]): void {\n if (!lines.length) {\n this.logLine(`${roleLabel}:`);\n return;\n }\n\n this.logLine(`${roleLabel}: ${lines[0]}`);\n for (let i = 1; i < lines.length; i++) {\n this.logLine(lines[i] ?? \"\");\n }\n }\n\n private static logToolCall(toolCall: ToolCallSummary): void {\n const header = chalk.whiteBright(`[tool-call] ${toolCall.toolName}`);\n this.logLine(header);\n const jsonArgs = toolCall.args ? JSON.parse(toolCall.args) : null;\n if (toolCall.args) {\n this.logLine(chalk.gray(this.truncate(toolCall.args)));\n }\n }\n\n static beginStreamingMessage(role: ModelMessage[\"role\"]): void {\n this.startStream(role);\n }\n\n static appendStreamingText(text: string): void {\n if (!text) {\n return;\n }\n this.appendToStream(text);\n }\n\n static finishStreamingMessage(): void {\n this.closeActiveStream();\n }\n\n static streamToolCall(toolName: string, args: unknown): void {\n const serializedArgs =\n args === undefined ? undefined : this.truncate(this.stringify(args));\n this.closeActiveStream();\n this.logToolCall({ toolName, args: serializedArgs });\n }\n\n static streamToolResult(toolName: string, output: unknown): void {\n this.closeActiveStream();\n const header = chalk.whiteBright(`[tool-result] ${toolName}`);\n this.logLine(header);\n if (output !== undefined) {\n this.logLine(chalk.gray(this.truncate(this.stringify(output))));\n }\n }\n\n static streamToolError(toolName: string, error: unknown): void {\n this.closeActiveStream();\n const header = chalk.whiteBright(`[tool-error] ${toolName}`);\n this.logLine(header);\n this.logLine(\n chalk.red(this.truncate(this.stringify(error ?? \"Unknown error\"))),\n );\n }\n\n private static renderBox(\n lines: string[],\n options: {\n borderColor: (text: string) => string;\n statusColor: (text: string) => string;\n },\n ): void {\n if (!lines.length) {\n return;\n }\n\n const { borderColor, statusColor } = options;\n const statusIndex = lines.findIndex((line) => line.startsWith(\"Status:\"));\n const width = lines.reduce((max, line) => Math.max(max, line.length), 0);\n const horizontal = borderColor(`+${\"-\".repeat(width + 2)}+`);\n this.logLine(horizontal);\n\n lines.forEach((line, index) => {\n const padded = line.padEnd(width, \" \");\n const isStatusLine = index === statusIndex;\n const colouredContent = isStatusLine\n ? statusColor(padded)\n : chalk.white(padded);\n this.logLine(\n `${borderColor(\"| \")}${colouredContent}${borderColor(\" |\")}`,\n );\n });\n\n this.logLine(horizontal);\n }\n\n private static stringify(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n try {\n return JSON.stringify(value, null, 2);\n } catch (error) {\n return String(value);\n }\n }\n\n private static truncate(text: string): string {\n const trimmed = text.trim();\n if (trimmed.length <= MAX_CONTENT_LENGTH) {\n return trimmed;\n }\n return `${trimmed.slice(0, MAX_CONTENT_LENGTH - 3).trimEnd()}...`;\n }\n\n private static formatDuration(durationMs: number): string {\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n return \"?\";\n }\n\n if (durationMs < 1000) {\n return `${durationMs.toFixed(0)}ms`;\n }\n\n const seconds = durationMs / 1000;\n if (seconds < 60) {\n return `${seconds.toFixed(1)}s`;\n }\n\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = (seconds % 60).toFixed(0).padStart(2, \"0\");\n return `${minutes}m${remainingSeconds}s`;\n }\n\n private static colorRole(role: ModelMessage[\"role\"]): string {\n switch (role) {\n case \"user\":\n return chalk.bold.whiteBright(\"user\");\n case \"assistant\":\n return chalk.bold.whiteBright(\"assistant\");\n case \"tool\":\n return chalk.bold.whiteBright(\"tool\");\n case \"system\":\n return chalk.bold.whiteBright(\"system\");\n default:\n return chalk.cyan(role);\n }\n }\n}\n","import { MCPClient } from \"@mastra/mcp\";\nimport { streamText, Tool, ToolChoice, ModelMessage } from \"ai\";\nimport { getUserIdFromApiKeyOrNull } from \"../db/user\";\nimport {\n createPersistenceContext,\n ensureSuiteRecord,\n createTestCaseRecord,\n createIterationRecord,\n updateIterationResult,\n updateTestCaseResult,\n markSuiteFailed,\n finalizeSuiteStatus,\n type ConfigSummary,\n type PersistenceContext,\n type UsageTotals,\n} from \"../db/tests\";\nimport {\n convertMastraToolsToVercelTools,\n validateAndNormalizeMCPClientConfiguration,\n validateLlms,\n validateTestCase,\n LlmsConfig,\n TestCase,\n} from \"../utils/validators\";\nimport { createLlmModel, extractToolNamesAsArray } from \"../utils/helpers\";\nimport { Logger } from \"../utils/logger\";\nimport { evaluateResults } from \"./evaluator\";\nimport { getUserId } from \"../utils/user-id\";\nimport { hogClient } from \"../utils/hog\";\n\nconst MAX_STEPS = 20;\n\ntype ToolMap = Record<string, Tool>;\ntype EvaluationResult = ReturnType<typeof evaluateResults>;\n\nconst accumulateTokenCount = (\n current: number | undefined,\n increment: number | undefined,\n): number | undefined => {\n if (typeof increment !== \"number\" || Number.isNaN(increment)) {\n return current;\n }\n\n return (current ?? 0) + increment;\n};\n\nconst ensureApiKeyIsValid = async (apiKey?: string) => {\n if (!apiKey) {\n return;\n }\n\n await getUserIdFromApiKeyOrNull(apiKey);\n};\n\nconst prepareSuite = async (\n tests: unknown,\n environment: unknown,\n llms: unknown,\n) => {\n const mcpClientOptions =\n validateAndNormalizeMCPClientConfiguration(environment);\n const validatedTests = validateTestCase(tests);\n const validatedLlms = validateLlms(llms);\n\n const mcpClient = new MCPClient(mcpClientOptions);\n const availableTools = await mcpClient.getTools();\n const vercelTools = convertMastraToolsToVercelTools(availableTools);\n\n const serverNames = Object.keys(mcpClientOptions.servers);\n\n Logger.initiateTestMessage(\n serverNames.length,\n Object.keys(availableTools).length,\n serverNames,\n validatedTests.length,\n );\n\n return {\n validatedTests,\n validatedLlms,\n vercelTools,\n serverNames,\n };\n};\n\ntype RunIterationParams = {\n test: TestCase;\n runIndex: number;\n totalRuns: number;\n llms: LlmsConfig;\n tools: ToolMap;\n persistence: PersistenceContext;\n testCaseId?: string;\n};\n\nconst runIteration = async ({\n test,\n runIndex,\n totalRuns,\n llms,\n tools,\n persistence,\n testCaseId,\n}: RunIterationParams): Promise<EvaluationResult> => {\n const { provider, model, advancedConfig, query } = test;\n const { system, temperature, toolChoice } = advancedConfig ?? {};\n\n Logger.testRunStart({\n runNumber: runIndex + 1,\n totalRuns,\n provider,\n model,\n temperature,\n });\n\n if (system) {\n Logger.conversation({ messages: [{ role: \"system\", content: system }] });\n }\n\n const userMessage: ModelMessage = {\n role: \"user\",\n content: query,\n };\n\n Logger.conversation({ messages: [userMessage] });\n\n const messageHistory: ModelMessage[] = [userMessage];\n const toolsCalled: string[] = [];\n let inputTokensUsed: number | undefined;\n let outputTokensUsed: number | undefined;\n let totalTokensUsed: number | undefined;\n let stepCount = 0;\n\n const runStartedAt = Date.now();\n const evalTestId = await createIterationRecord(\n persistence,\n testCaseId,\n runIndex + 1,\n runStartedAt,\n );\n\n while (stepCount < MAX_STEPS) {\n let assistantStreaming = false;\n\n const streamResult = await streamText({\n model: createLlmModel(provider, model, llms),\n system,\n temperature,\n tools,\n toolChoice: toolChoice as ToolChoice<Record<string, Tool>> | undefined,\n messages: messageHistory,\n onChunk: async (chunk) => {\n switch (chunk.chunk.type) {\n case \"text-delta\":\n case \"reasoning-delta\": {\n if (!assistantStreaming) {\n Logger.beginStreamingMessage(\"assistant\");\n assistantStreaming = true;\n }\n Logger.appendStreamingText(chunk.chunk.text);\n break;\n }\n case \"tool-call\": {\n if (assistantStreaming) {\n Logger.finishStreamingMessage();\n assistantStreaming = false;\n }\n Logger.streamToolCall(chunk.chunk.toolName, chunk.chunk.input);\n break;\n }\n case \"tool-result\": {\n Logger.streamToolResult(chunk.chunk.toolName, chunk.chunk.output);\n break;\n }\n default:\n break;\n }\n },\n });\n\n await streamResult.consumeStream();\n\n if (assistantStreaming) {\n Logger.finishStreamingMessage();\n assistantStreaming = false;\n }\n\n const stepUsage = await streamResult.usage;\n const cumulativeUsage = await streamResult.totalUsage;\n\n inputTokensUsed = accumulateTokenCount(\n inputTokensUsed,\n stepUsage.inputTokens,\n );\n outputTokensUsed = accumulateTokenCount(\n outputTokensUsed,\n stepUsage.outputTokens,\n );\n\n const totalTokens = stepUsage.totalTokens ?? cumulativeUsage.totalTokens;\n totalTokensUsed = accumulateTokenCount(totalTokensUsed, totalTokens);\n\n const toolNamesForStep = extractToolNamesAsArray(\n await streamResult.toolCalls,\n );\n if (toolNamesForStep.length) {\n toolsCalled.push(...toolNamesForStep);\n }\n\n const responseMessages = ((await streamResult.response)?.messages ??\n []) as ModelMessage[];\n if (responseMessages.length) {\n messageHistory.push(...responseMessages);\n }\n\n stepCount++;\n\n const finishReason = await streamResult.finishReason;\n if (finishReason !== \"tool-calls\") {\n break;\n }\n }\n\n Logger.finishStreamingMessage();\n\n const evaluation = evaluateResults(test.expectedToolCalls, toolsCalled);\n const usage: UsageTotals = {\n inputTokens: inputTokensUsed,\n outputTokens: outputTokensUsed,\n totalTokens: totalTokensUsed,\n };\n\n Logger.toolSummary({\n expected: evaluation.expectedToolCalls,\n actual: evaluation.toolsCalled,\n missing: evaluation.missing,\n unexpected: evaluation.unexpected,\n passed: evaluation.passed,\n });\n\n Logger.testRunResult({\n passed: evaluation.passed,\n durationMs: Date.now() - runStartedAt,\n usage:\n usage.inputTokens !== undefined ||\n usage.outputTokens !== undefined ||\n usage.totalTokens !== undefined\n ? usage\n : undefined,\n });\n\n if (!evaluation.passed) {\n await markSuiteFailed(persistence);\n }\n\n await updateIterationResult(\n persistence,\n evalTestId,\n evaluation.passed,\n toolsCalled,\n usage,\n messageHistory,\n );\n\n return evaluation;\n};\n\ntype RunTestCaseParams = {\n test: TestCase;\n testIndex: number;\n llms: LlmsConfig;\n tools: ToolMap;\n persistence: PersistenceContext;\n};\n\nconst runTestCase = async ({\n test,\n testIndex,\n llms,\n tools,\n persistence,\n}: RunTestCaseParams) => {\n const { runs, model, provider } = test;\n\n Logger.logTestGroupTitle(testIndex, test.title, provider, model);\n\n let passedRuns = 0;\n let failedRuns = 0;\n\n const testCaseId = await createTestCaseRecord(persistence, test, testIndex);\n\n for (let runIndex = 0; runIndex < runs; runIndex++) {\n const evaluation = await runIteration({\n test,\n runIndex,\n totalRuns: runs,\n llms,\n tools,\n persistence,\n testCaseId,\n });\n\n if (evaluation.passed) {\n passedRuns++;\n } else {\n failedRuns++;\n }\n }\n\n await updateTestCaseResult(persistence, testCaseId, passedRuns, failedRuns);\n\n return { passedRuns, failedRuns };\n};\n\nexport const runEvals = async (\n tests: unknown,\n environment: unknown,\n llms: unknown,\n apiKey?: string,\n) => {\n await ensureApiKeyIsValid(apiKey);\n\n const { validatedTests, validatedLlms, vercelTools, serverNames } =\n await prepareSuite(tests, environment, llms);\n\n const suiteStartedAt = Date.now();\n const totalPlannedTests = validatedTests.reduce(\n (sum, current) => sum + (current?.runs ?? 0),\n 0,\n );\n\n const configSummary: ConfigSummary = {\n tests: validatedTests,\n environment: { servers: serverNames },\n llms: Object.keys(validatedLlms ?? {}),\n };\n\n const persistence = createPersistenceContext(\n apiKey,\n configSummary,\n totalPlannedTests,\n );\n await ensureSuiteRecord(persistence);\n\n let passedRuns = 0;\n let failedRuns = 0;\n\n for (let index = 0; index < validatedTests.length; index++) {\n const test = validatedTests[index];\n if (!test) {\n continue;\n }\n const { passedRuns: casePassed, failedRuns: caseFailed } =\n await runTestCase({\n test,\n testIndex: index + 1,\n llms: validatedLlms,\n tools: vercelTools,\n persistence,\n });\n passedRuns += casePassed;\n failedRuns += caseFailed;\n }\n hogClient.capture({\n distinctId: getUserId(),\n event: \"evals suite complete\",\n properties: {\n environment: process.env.ENVIRONMENT,\n },\n });\n Logger.suiteComplete({\n durationMs: Date.now() - suiteStartedAt,\n passed: passedRuns,\n failed: failedRuns,\n });\n\n await finalizeSuiteStatus(persistence, failedRuns);\n};\n","export const version = \"1.27.3\";\n","/*\nhttps://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js\nCopyright (c) 2014 Jameson Little\nThe MIT License (MIT)\n*/\n\n// Vendored because this library has no ESM build, and some environments\n// (SvelteKit) are happiest when all dependencies are ESM.\n\nvar lookup: string[] = [];\nvar revLookup: number[] = [];\nvar Arr = Uint8Array;\n\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\n\nfunction getLens(b64: string) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error(\"Invalid string. Length must be a multiple of 4\");\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf(\"=\");\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen];\n}\n\n// base64 is 4/3 + up to two characters of the original data\n/** @public */\nexport function byteLength(b64: string): number {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\nfunction _byteLength(_b64: string, validLen: number, placeHoldersLen: number) {\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\n/** @public */\nexport function toByteArray(b64: string): Uint8Array {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xff;\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n return arr;\n}\n\nfunction tripletToBase64(num: number) {\n return (\n lookup[(num >> 18) & 0x3f] +\n lookup[(num >> 12) & 0x3f] +\n lookup[(num >> 6) & 0x3f] +\n lookup[num & 0x3f]\n );\n}\n\nfunction encodeChunk(uint8: Uint8Array, start: number, end: number) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xff0000) +\n ((uint8[i + 1] << 8) & 0xff00) +\n (uint8[i + 2] & 0xff);\n output.push(tripletToBase64(tmp));\n }\n return output.join(\"\");\n}\n\n/** @public */\nexport function fromByteArray(uint8: Uint8Array): string {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength,\n ),\n );\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + \"==\");\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3f] +\n lookup[(tmp << 2) & 0x3f] +\n \"=\",\n );\n }\n\n return parts.join(\"\");\n}\n\nexport function fromByteArrayUrlSafeNoPadding(uint8: Uint8Array): string {\n return fromByteArray(uint8)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n","import type { Value } from \"../values/value.js\";\n\n/**\n * Validate that the arguments to a Convex function are an object, defaulting\n * `undefined` to `{}`.\n */\nexport function parseArgs(\n args: Record<string, Value> | undefined,\n): Record<string, Value> {\n if (args === undefined) {\n return {};\n }\n if (!isSimpleObject(args)) {\n throw new Error(\n `The arguments to a Convex function must be an object. Received: ${\n args as any\n }`,\n );\n }\n return args;\n}\n\nexport function validateDeploymentUrl(deploymentUrl: string) {\n // Don't use things like `new URL(deploymentUrl).hostname` since these aren't\n // supported by React Native's JS environment\n if (typeof deploymentUrl === \"undefined\") {\n throw new Error(\n `Client created with undefined deployment address. If you used an environment variable, check that it's set.`,\n );\n }\n if (typeof deploymentUrl !== \"string\") {\n throw new Error(\n `Invalid deployment address: found ${deploymentUrl as any}\".`,\n );\n }\n if (\n !(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))\n ) {\n throw new Error(\n `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`,\n );\n }\n\n // Most clients should connect to \".convex.cloud\". But we also support localhost and\n // custom custom. We validate the deployment url is a valid url, which is the most\n // common failure pattern.\n try {\n new URL(deploymentUrl);\n } catch {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n\n // If a user uses .convex.site, this is very likely incorrect.\n if (deploymentUrl.endsWith(\".convex.site\")) {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n}\n\n/**\n * Check whether a value is a plain old JavaScript object.\n */\nexport function isSimpleObject(value: unknown) {\n const isObject = typeof value === \"object\";\n const prototype = Object.getPrototypeOf(value);\n const isSimple =\n prototype === null ||\n prototype === Object.prototype ||\n // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n return isObject && isSimple;\n}\n","/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nconst MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nexport function stringifyValueForError(value: any) {\n return JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // By default `JSON.stringify` converts undefined, functions, symbols,\n // Infinity, and NaN to null which produces a confusing error message.\n // We deal with `undefined` specifically because it's the most common.\n // Ideally we'd use a pretty-printing library that prints `undefined`\n // (no quotes), but it might not be worth the bundle size cost.\n return \"undefined\";\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n","import { Value, stringifyValueForError } from \"./value.js\";\n\nconst IDENTIFYING_FIELD = Symbol.for(\"ConvexError\");\n\nexport class ConvexError<TData extends Value> extends Error {\n name = \"ConvexError\";\n data: TData;\n [IDENTIFYING_FIELD] = true;\n\n constructor(data: TData) {\n super(typeof data === \"string\" ? data : stringifyValueForError(data));\n this.data = data;\n }\n}\n","/**\n * Taken from https://github.com/rocicorp/compare-utf8/blob/main/LICENSE\n * (Apache Version 2.0, January 2004)\n */\n\n/**\n * This is copied here instead of added as a dependency to avoid bundling issues.\n */\n\n/**\n * Compares two JavaScript strings as if they were UTF-8 encoded byte arrays.\n * @param {string} a\n * @param {string} b\n * @returns {number}\n */\nexport function compareUTF8(a: string, b: string): number {\n const aLength = a.length;\n const bLength = b.length;\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; ) {\n const aCodePoint = a.codePointAt(i)!;\n const bCodePoint = b.codePointAt(i)!;\n if (aCodePoint !== bCodePoint) {\n // Code points below 0x80 are represented the same way in UTF-8 as in\n // UTF-16.\n if (aCodePoint < 0x80 && bCodePoint < 0x80) {\n return aCodePoint - bCodePoint;\n }\n\n // get the UTF-8 bytes for the code points\n const aLength = utf8Bytes(aCodePoint, aBytes);\n const bLength = utf8Bytes(bCodePoint, bBytes);\n return compareArrays(aBytes, aLength, bBytes, bLength);\n }\n\n i += utf16LengthForCodePoint(aCodePoint);\n }\n\n return aLength - bLength;\n}\n\n/**\n * @param {number[]} a\n * @param {number} aLength\n * @param {number[]} b\n * @param {number} bLength\n * @returns {number}\n */\nfunction compareArrays(\n a: number[],\n aLength: number,\n b: number[],\n bLength: number,\n) {\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; i++) {\n const aValue = a[i];\n const bValue = b[i];\n if (aValue !== bValue) {\n return aValue - bValue;\n }\n }\n return aLength - bLength;\n}\n\n/**\n * @param {number} aCodePoint\n * @returns {number}\n */\nexport function utf16LengthForCodePoint(aCodePoint: number) {\n return aCodePoint > 0xffff ? 2 : 1;\n}\n\n// 2 preallocated arrays for utf8Bytes.\nconst arr = () => Array.from({ length: 4 }, () => 0);\nconst aBytes = arr();\nconst bBytes = arr();\n\n/**\n * @param {number} codePoint\n * @param {number[]} bytes\n * @returns {number}\n */\nfunction utf8Bytes(codePoint: number, bytes: number[]) {\n if (codePoint < 0x80) {\n bytes[0] = codePoint;\n return 1;\n }\n\n let count;\n let offset;\n\n if (codePoint <= 0x07ff) {\n count = 1;\n offset = 0xc0;\n } else if (codePoint <= 0xffff) {\n count = 2;\n offset = 0xe0;\n } else if (codePoint <= 0x10ffff) {\n count = 3;\n offset = 0xf0;\n } else {\n throw new Error(\"Invalid code point\");\n }\n\n bytes[0] = (codePoint >> (6 * count)) + offset;\n let i = 1;\n for (; count > 0; count--) {\n const temp = codePoint >> (6 * (count - 1));\n bytes[i++] = 0x80 | (temp & 0x3f);\n }\n return i;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThan(a: string, b: string) {\n return compareUTF8(a, b) > 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThanEq(a: string, b: string) {\n return compareUTF8(a, b) >= 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThan(a: string, b: string) {\n return compareUTF8(a, b) < 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThanEq(a: string, b: string) {\n return compareUTF8(a, b) <= 0;\n}\n","/* eslint-disable no-console */ // This is the one file where we can `console.log` for the default logger implementation.\nimport { ConvexError, Value } from \"../values/index.js\";\nimport { FunctionFailure } from \"./sync/function_result.js\";\n\n// This is blue #9 from https://www.radix-ui.com/docs/colors/palette-composition/the-scales\n// It must look good in both light and dark mode.\nconst INFO_COLOR = \"color:rgb(0, 145, 255)\";\n\nexport type UdfType = \"query\" | \"mutation\" | \"action\" | \"any\";\n\nfunction prefix_for_source(source: UdfType) {\n switch (source) {\n case \"query\":\n return \"Q\";\n case \"mutation\":\n return \"M\";\n case \"action\":\n return \"A\";\n case \"any\":\n return \"?\";\n }\n}\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * A logger that can be used to log messages. By default, this is a wrapper\n * around `console`, but can be configured to not log at all or to log somewhere\n * else.\n */\nexport type Logger = {\n logVerbose(...args: any[]): void;\n log(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\n\nexport class DefaultLogger implements Logger {\n private _onLogLineFuncs: Record<\n string,\n (level: LogLevel, ...args: any[]) => void\n >;\n private _verbose: boolean;\n\n constructor(options: { verbose: boolean }) {\n this._onLogLineFuncs = {};\n this._verbose = options.verbose;\n }\n\n addLogLineListener(\n func: (level: LogLevel, ...args: any[]) => void,\n ): () => void {\n let id = Math.random().toString(36).substring(2, 15);\n for (let i = 0; i < 10; i++) {\n if (this._onLogLineFuncs[id] === undefined) {\n break;\n }\n id = Math.random().toString(36).substring(2, 15);\n }\n this._onLogLineFuncs[id] = func;\n return () => {\n delete this._onLogLineFuncs[id];\n };\n }\n\n logVerbose(...args: any[]) {\n if (this._verbose) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"debug\", `${new Date().toISOString()}`, ...args);\n }\n }\n }\n\n log(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"info\", ...args);\n }\n }\n\n warn(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"warn\", ...args);\n }\n }\n\n error(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"error\", ...args);\n }\n }\n}\n\nexport function instantiateDefaultLogger(options: {\n verbose: boolean;\n}): Logger {\n const logger = new DefaultLogger(options);\n logger.addLogLineListener((level, ...args) => {\n switch (level) {\n case \"debug\":\n console.debug(...args);\n break;\n case \"info\":\n console.log(...args);\n break;\n case \"warn\":\n console.warn(...args);\n break;\n case \"error\":\n console.error(...args);\n break;\n default: {\n level satisfies never;\n console.log(...args);\n }\n }\n });\n return logger;\n}\n\nexport function instantiateNoopLogger(options: { verbose: boolean }): Logger {\n return new DefaultLogger(options);\n}\n\nexport function logForFunction(\n logger: Logger,\n type: \"info\" | \"error\",\n source: UdfType,\n udfPath: string,\n message: string | { errorData: Value },\n) {\n const prefix = prefix_for_source(source);\n\n if (typeof message === \"object\") {\n message = `ConvexError ${JSON.stringify(message.errorData, null, 2)}`;\n }\n if (type === \"info\") {\n const match = message.match(/^\\[.*?\\] /);\n if (match === null) {\n logger.error(\n `[CONVEX ${prefix}(${udfPath})] Could not parse console.log`,\n );\n return;\n }\n const level = message.slice(1, match[0].length - 2);\n const args = message.slice(match[0].length);\n\n logger.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`, INFO_COLOR, args);\n } else {\n logger.error(`[CONVEX ${prefix}(${udfPath})] ${message}`);\n }\n}\n\nexport function logFatalError(logger: Logger, message: string): Error {\n const errorMessage = `[CONVEX FATAL ERROR] ${message}`;\n logger.error(errorMessage);\n return new Error(errorMessage);\n}\n\nexport function createHybridErrorStacktrace(\n source: UdfType,\n udfPath: string,\n result: FunctionFailure,\n): string {\n const prefix = prefix_for_source(source);\n return `[CONVEX ${prefix}(${udfPath})] ${result.errorMessage}\\n Called by client`;\n}\n\nexport function forwardData(\n result: FunctionFailure,\n error: ConvexError<string>,\n) {\n (error as ConvexError<any>).data = result.errorData;\n return error;\n}\n","/**\n * A symbol for accessing the name of a {@link FunctionReference} at runtime.\n */\nexport const functionName = Symbol.for(\"functionName\");\n","import { functionName } from \"../functionName.js\";\n\nexport const toReferencePath = Symbol.for(\"toReferencePath\");\n\n// Multiple instances of the same Symbol.for() are equal at runtime but not\n// at type-time, so `[toReferencePath]` properties aren't used in types.\n// Use this function to set the property invisibly.\nexport function setReferencePath<T>(obj: T, value: string) {\n (obj as any)[toReferencePath] = value;\n}\n\nexport function extractReferencePath(reference: any): string | null {\n return reference[toReferencePath] ?? null;\n}\n\nexport function isFunctionHandle(s: string): boolean {\n return s.startsWith(\"function://\");\n}\n\nexport function getFunctionAddress(functionReference: any) {\n // The `run*` syscalls expect either a UDF path at \"name\" or a serialized\n // reference at \"reference\". Dispatch on `functionReference` to coerce\n // it to one or the other.\n let functionAddress;\n\n // Legacy path for passing in UDF paths directly as function references.\n if (typeof functionReference === \"string\") {\n if (isFunctionHandle(functionReference)) {\n functionAddress = { functionHandle: functionReference };\n } else {\n functionAddress = { name: functionReference };\n }\n }\n // Path for passing in a `FunctionReference`, either from `api` or directly\n // created from a UDF path with `makeFunctionReference`.\n else if (functionReference[functionName]) {\n functionAddress = { name: functionReference[functionName] };\n }\n // Reference to a component's function derived from `app` or `component`.\n else {\n const referencePath = extractReferencePath(functionReference);\n if (!referencePath) {\n throw new Error(`${functionReference} is not a functionReference`);\n }\n functionAddress = { reference: referencePath };\n }\n return functionAddress;\n}\n","import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _args: Args;\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference: AnyFunctionReference,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as API[mod] extends Predicate\n ? mod\n : API[mod] extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API[mod], Predicate> extends Record<string, never>\n ? never\n : mod]: API[mod] extends Predicate\n ? API[mod]\n : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * This is represented as an object mapping argument names to values.\n * @public\n */\nexport type FunctionArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FuncRef[\"_args\"]];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends AnyFunctionReference,\n Options,\n> = FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FuncRef[\"_args\"], options?: Options];\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n","// Implements an unsigned long.\n// This is a subset of https://github.com/dcodeIO/Long.js,\n// vendored to decrease bundle size.\n// Copyright Daniel Wirtz <dcode@dcode.io>\n// License: Apache Version 2.0\n/*\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright 2023 Daniel Wirtz <dcode@dcode.io>\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// This works... but don't try to compare one to a real Long.js Long!\n// For internal use only.\n// `| 0` assures the runtime that we are using integer arithmetic\nexport class Long {\n low: number;\n high: number;\n __isUnsignedLong__: boolean;\n\n static isLong(obj: Long) {\n return (obj && obj.__isUnsignedLong__) === true;\n }\n\n constructor(low: number, high: number) {\n this.low = low | 0;\n this.high = high | 0;\n this.__isUnsignedLong__ = true;\n }\n\n // prettier-ignore\n static fromBytesLE(bytes: number[]): Long {\n return new Long(\n bytes[0] |\n bytes[1] << 8 |\n bytes[2] << 16 |\n bytes[3] << 24,\n bytes[4] |\n bytes[5] << 8 |\n bytes[6] << 16 |\n bytes[7] << 24,\n );\n }\n\n // prettier-ignore\n toBytesLE() {\n const hi = this.high;\n const lo = this.low;\n return [\n lo & 0xff,\n lo >>> 8 & 0xff,\n lo >>> 16 & 0xff,\n lo >>> 24,\n hi & 0xff,\n hi >>> 8 & 0xff,\n hi >>> 16 & 0xff,\n hi >>> 24\n ];\n }\n\n static fromNumber(value: number) {\n if (isNaN(value)) return UZERO;\n if (value < 0) return UZERO;\n if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;\n return new Long(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0);\n }\n\n toString() {\n return (\n BigInt(this.high) * BigInt(TWO_PWR_32_DBL) +\n BigInt(this.low)\n ).toString();\n }\n\n equals(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;\n return this.high === other.high && this.low === other.low;\n }\n\n notEquals(other: Long) {\n return !this.equals(other);\n }\n\n comp(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.equals(other)) return 0;\n return other.high >>> 0 > this.high >>> 0 ||\n (other.high === this.high && other.low >>> 0 > this.low >>> 0)\n ? -1\n : 1;\n }\n\n lessThanOrEqual(other: Long) {\n return this.comp(/* validates */ other) <= 0;\n }\n\n static fromValue(val: any) {\n if (typeof val === \"number\") return Long.fromNumber(val);\n // Throws for non-objects, converts non-instanceof Long:\n return new Long(val.low, val.high);\n }\n}\n\nconst UZERO = new Long(0, 0);\nconst TWO_PWR_16_DBL = 1 << 16;\nconst TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\nconst TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\nconst MAX_UNSIGNED_VALUE = new Long(0xffffffff | 0, 0xffffffff | 0);\n","export class InvalidTokenError extends Error {\n}\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\nfunction b64DecodeUnicode(str) {\n return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {\n let code = p.charCodeAt(0).toString(16).toUpperCase();\n if (code.length < 2) {\n code = \"0\" + code;\n }\n return \"%\" + code;\n }));\n}\nfunction base64UrlDecode(str) {\n let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n switch (output.length % 4) {\n case 0:\n break;\n case 2:\n output += \"==\";\n break;\n case 3:\n output += \"=\";\n break;\n default:\n throw new Error(\"base64 string is not of the correct length\");\n }\n try {\n return b64DecodeUnicode(output);\n }\n catch (err) {\n return atob(output);\n }\n}\nexport function jwtDecode(token, options) {\n if (typeof token !== \"string\") {\n throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n }\n options || (options = {});\n const pos = options.header === true ? 0 : 1;\n const part = token.split(\".\")[pos];\n if (typeof part !== \"string\") {\n throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);\n }\n let decoded;\n try {\n decoded = base64UrlDecode(part);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);\n }\n try {\n return JSON.parse(decoded);\n }\n catch (e) {\n throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);\n }\n}\n","import { Logger } from \"../logging.js\";\nimport { LocalSyncState } from \"./local_state.js\";\nimport { AuthError, IdentityVersion, Transition } from \"./protocol.js\";\nimport { jwtDecode } from \"jwt-decode\";\n\n// setTimout uses 32 bit integer, so it can only\n// schedule about 24 days in the future.\nconst MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1000; // 20 days\n\nconst MAX_TOKEN_CONFIRMATION_ATTEMPTS = 2;\n\n/**\n * An async function returning a JWT. Depending on the auth providers\n * configured in convex/auth.config.ts, this may be a JWT-encoded OpenID\n * Connect Identity Token or a traditional JWT.\n *\n * `forceRefreshToken` is `true` if the server rejected a previously\n * returned token or the token is anticipated to expiring soon\n * based on its `exp` time.\n *\n * See {@link ConvexReactClient.setAuth}.\n *\n * @public\n */\nexport type AuthTokenFetcher = (args: {\n forceRefreshToken: boolean;\n}) => Promise<string | null | undefined>;\n\n/**\n * What is provided to the client.\n */\ntype AuthConfig = {\n fetchToken: AuthTokenFetcher;\n onAuthChange: (isAuthenticated: boolean) => void;\n};\n\n/**\n * In general we take 3 steps:\n * 1. Fetch a possibly cached token\n * 2. Immediately fetch a fresh token without using a cache\n * 3. Repeat step 2 before the end of the fresh token's lifetime\n *\n * When we fetch without using a cache we know when the token\n * will expire, and can schedule refetching it.\n *\n * If we get an error before a scheduled refetch, we go back\n * to step 2.\n */\ntype AuthState =\n | { state: \"noAuth\" }\n | {\n state: \"waitingForServerConfirmationOfCachedToken\";\n config: AuthConfig;\n hasRetried: boolean;\n }\n | {\n state: \"initialRefetch\";\n config: AuthConfig;\n }\n | {\n state: \"waitingForServerConfirmationOfFreshToken\";\n config: AuthConfig;\n hadAuth: boolean;\n token: string;\n }\n | {\n state: \"waitingForScheduledRefetch\";\n config: AuthConfig;\n refetchTokenTimeoutId: ReturnType<typeof setTimeout>;\n }\n // Special/weird state when we got a valid token\n // but could not fetch a new one.\n | {\n state: \"notRefetching\";\n config: AuthConfig;\n };\n\n/**\n * Handles the state transitions for auth. The server is the source\n * of truth.\n */\nexport class AuthenticationManager {\n private authState: AuthState = { state: \"noAuth\" };\n // Used to detect races involving `setConfig` calls\n // while a token is being fetched.\n private configVersion = 0;\n // Shared by the BaseClient so that the auth manager can easily inspect it\n private readonly syncState: LocalSyncState;\n // Passed down by BaseClient, sends a message to the server\n private readonly authenticate: (token: string) => IdentityVersion;\n private readonly stopSocket: () => Promise<void>;\n private readonly tryRestartSocket: () => void;\n private readonly pauseSocket: () => void;\n private readonly resumeSocket: () => void;\n // Passed down by BaseClient, sends a message to the server\n private readonly clearAuth: () => void;\n private readonly logger: Logger;\n private readonly refreshTokenLeewaySeconds: number;\n // Number of times we have attempted to confirm the latest token. We retry up\n // to `MAX_TOKEN_CONFIRMATION_ATTEMPTS` times.\n private tokenConfirmationAttempts = 0;\n constructor(\n syncState: LocalSyncState,\n callbacks: {\n authenticate: (token: string) => IdentityVersion;\n stopSocket: () => Promise<void>;\n tryRestartSocket: () => void;\n pauseSocket: () => void;\n resumeSocket: () => void;\n clearAuth: () => void;\n },\n config: {\n refreshTokenLeewaySeconds: number;\n logger: Logger;\n },\n ) {\n this.syncState = syncState;\n this.authenticate = callbacks.authenticate;\n this.stopSocket = callbacks.stopSocket;\n this.tryRestartSocket = callbacks.tryRestartSocket;\n this.pauseSocket = callbacks.pauseSocket;\n this.resumeSocket = callbacks.resumeSocket;\n this.clearAuth = callbacks.clearAuth;\n this.logger = config.logger;\n this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;\n }\n\n async setConfig(\n fetchToken: AuthTokenFetcher,\n onChange: (isAuthenticated: boolean) => void,\n ) {\n this.resetAuthState();\n this._logVerbose(\"pausing WS for auth token fetch\");\n this.pauseSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {\n forceRefreshToken: false,\n });\n if (token.isFromOutdatedConfig) {\n return;\n }\n if (token.value) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfCachedToken\",\n config: { fetchToken, onAuthChange: onChange },\n hasRetried: false,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"initialRefetch\",\n config: { fetchToken, onAuthChange: onChange },\n });\n // Try again with `forceRefreshToken: true`\n await this.refetchToken();\n }\n this._logVerbose(\"resuming WS after auth token fetch\");\n this.resumeSocket();\n }\n\n onTransition(serverMessage: Transition) {\n if (\n !this.syncState.isCurrentOrNewerAuthVersion(\n serverMessage.endVersion.identity,\n )\n ) {\n // This is a stale transition - client has moved on to\n // a newer auth version.\n return;\n }\n if (\n serverMessage.endVersion.identity <= serverMessage.startVersion.identity\n ) {\n // This transition did not change auth - it is not a response to Authenticate.\n return;\n }\n\n if (this.authState.state === \"waitingForServerConfirmationOfCachedToken\") {\n this._logVerbose(\"server confirmed auth token is valid\");\n void this.refetchToken();\n this.authState.config.onAuthChange(true);\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this._logVerbose(\"server confirmed new auth token is valid\");\n this.scheduleTokenRefetch(this.authState.token);\n this.tokenConfirmationAttempts = 0;\n if (!this.authState.hadAuth) {\n this.authState.config.onAuthChange(true);\n }\n }\n }\n\n onAuthError(serverMessage: AuthError) {\n // If the AuthError is not due to updating the token, and we're currently\n // waiting on the result of a token update, ignore.\n if (\n serverMessage.authUpdateAttempted === false &&\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" ||\n this.authState.state === \"waitingForServerConfirmationOfCachedToken\")\n ) {\n this._logVerbose(\"ignoring non-auth token expired error\");\n return;\n }\n const { baseVersion } = serverMessage;\n // Versioned AuthErrors are ignored if the client advanced to\n // a newer auth identity\n // Error are reporting the previous version, since the server\n // didn't advance, hence `+ 1`.\n if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {\n this._logVerbose(\"ignoring auth error for previous auth attempt\");\n return;\n }\n void this.tryToReauthenticate(serverMessage);\n return;\n }\n\n // This is similar to `refetchToken` defined below, in fact we\n // don't represent them as different states, but it is different\n // in that we pause the WebSocket so that mutations\n // don't retry with bad auth.\n private async tryToReauthenticate(serverMessage: AuthError) {\n this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);\n if (\n // No way to fetch another token, kaboom\n this.authState.state === \"noAuth\" ||\n // We failed on a fresh token. After a small number of retries, we give up\n // and clear the auth state to avoid infinite retries.\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" &&\n this.tokenConfirmationAttempts >= MAX_TOKEN_CONFIRMATION_ATTEMPTS)\n ) {\n this.logger.error(\n `Failed to authenticate: \"${serverMessage.error}\", check your server auth config`,\n );\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n if (this.authState.state !== \"noAuth\") {\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this.tokenConfirmationAttempts++;\n this._logVerbose(\n `retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS - this.tokenConfirmationAttempts} attempts remaining`,\n );\n }\n\n await this.stopSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value && this.syncState.isNewAuth(token.value)) {\n this.authenticate(token.value);\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n config: this.authState.config,\n token: token.value,\n hadAuth:\n this.authState.state === \"notRefetching\" ||\n this.authState.state === \"waitingForScheduledRefetch\",\n });\n } else {\n this._logVerbose(\"reauthentication failed, could not fetch a new token\");\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n this.tryRestartSocket();\n }\n\n // Force refetch the token and schedule another refetch\n // before the token expires - an active client should never\n // need to reauthenticate.\n private async refetchToken() {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n this._logVerbose(\"refetching auth token\");\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value) {\n if (this.syncState.isNewAuth(token.value)) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n hadAuth: this.syncState.hasAuth(),\n token: token.value,\n config: this.authState.config,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"notRefetching\",\n config: this.authState.config,\n });\n }\n } else {\n this._logVerbose(\"refetching token failed\");\n if (this.syncState.hasAuth()) {\n this.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n // Restart in case this refetch was triggered via schedule during\n // a reauthentication attempt.\n this._logVerbose(\n \"restarting WS after auth token fetch (if currently stopped)\",\n );\n this.tryRestartSocket();\n }\n\n private scheduleTokenRefetch(token: string) {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n const decodedToken = this.decodeToken(token);\n if (!decodedToken) {\n // This is no longer really possible, because\n // we wait on server response before scheduling token refetch,\n // and the server currently requires JWT tokens.\n this.logger.error(\n \"Auth token is not a valid JWT, cannot refetch the token\",\n );\n return;\n }\n // iat: issued at time, UTC seconds timestamp at which the JWT was issued\n // exp: expiration time, UTC seconds timestamp at which the JWT will expire\n const { iat, exp } = decodedToken as { iat?: number; exp?: number };\n if (!iat || !exp) {\n this.logger.error(\n \"Auth token does not have required fields, cannot refetch the token\",\n );\n return;\n }\n // Because the client and server clocks may be out of sync,\n // we only know that the token will expire after `exp - iat`,\n // and since we just fetched a fresh one we know when that\n // will happen.\n const tokenValiditySeconds = exp - iat;\n if (tokenValiditySeconds <= 2) {\n this.logger.error(\n \"Auth token does not live long enough, cannot refetch the token\",\n );\n return;\n }\n // Attempt to refresh the token `refreshTokenLeewaySeconds` before it expires,\n // or immediately if the token is already expiring soon.\n let delay = Math.min(\n MAXIMUM_REFRESH_DELAY,\n (tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1000,\n );\n if (delay <= 0) {\n // Refetch immediately, but this might be due to configuring a `refreshTokenLeewaySeconds`\n // that is too large compared to the token's actual lifetime.\n this.logger.warn(\n `Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`,\n );\n delay = 0;\n }\n const refetchTokenTimeoutId = setTimeout(() => {\n this._logVerbose(\"running scheduled token refetch\");\n void this.refetchToken();\n }, delay);\n this.setAuthState({\n state: \"waitingForScheduledRefetch\",\n refetchTokenTimeoutId,\n config: this.authState.config,\n });\n this._logVerbose(\n `scheduled preemptive auth token refetching in ${delay}ms`,\n );\n }\n\n // Protects against simultaneous calls to `setConfig`\n // while we're fetching a token\n private async fetchTokenAndGuardAgainstRace(\n fetchToken: AuthTokenFetcher,\n fetchArgs: {\n forceRefreshToken: boolean;\n },\n ) {\n const originalConfigVersion = ++this.configVersion;\n this._logVerbose(\n `fetching token with config version ${originalConfigVersion}`,\n );\n const token = await fetchToken(fetchArgs);\n if (this.configVersion !== originalConfigVersion) {\n // This is a stale config\n this._logVerbose(\n `stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`,\n );\n return { isFromOutdatedConfig: true };\n }\n return { isFromOutdatedConfig: false, value: token };\n }\n\n stop() {\n this.resetAuthState();\n // Bump this in case we are mid-token-fetch when we get stopped\n this.configVersion++;\n this._logVerbose(`config version bumped to ${this.configVersion}`);\n }\n\n private setAndReportAuthFailed(\n onAuthChange: (authenticated: boolean) => void,\n ) {\n onAuthChange(false);\n this.resetAuthState();\n }\n\n private resetAuthState() {\n this.setAuthState({ state: \"noAuth\" });\n }\n\n private setAuthState(newAuth: AuthState) {\n const authStateForLog =\n newAuth.state === \"waitingForServerConfirmationOfFreshToken\"\n ? {\n hadAuth: newAuth.hadAuth,\n state: newAuth.state,\n token: `...${newAuth.token.slice(-7)}`,\n }\n : { state: newAuth.state };\n this._logVerbose(\n `setting auth state to ${JSON.stringify(authStateForLog)}`,\n );\n switch (newAuth.state) {\n case \"waitingForScheduledRefetch\":\n case \"notRefetching\":\n case \"noAuth\":\n this.tokenConfirmationAttempts = 0;\n break;\n case \"waitingForServerConfirmationOfFreshToken\":\n case \"waitingForServerConfirmationOfCachedToken\":\n case \"initialRefetch\":\n break;\n default: {\n newAuth satisfies never;\n }\n }\n if (this.authState.state === \"waitingForScheduledRefetch\") {\n clearTimeout(this.authState.refetchTokenTimeoutId);\n\n // The waitingForScheduledRefetch state is the most quiesced authed state.\n // Let the syncState know that auth is in a good state, so it can reset failure backoffs\n this.syncState.markAuthCompletion();\n }\n this.authState = newAuth;\n }\n\n private decodeToken(token: string) {\n try {\n return jwtDecode(token);\n } catch (e) {\n this._logVerbose(\n `Error decoding token: ${e instanceof Error ? e.message : \"Unknown error\"}`,\n );\n return null;\n }\n }\n\n private _logVerbose(message: string) {\n this.logger.logVerbose(`${message} [v${this.configVersion}]`);\n }\n}\n","import {\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n ConvexError,\n JSONValue,\n convexToJson,\n jsonToConvex,\n} from \"../values/index.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logForFunction,\n Logger,\n} from \"./logging.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n UserIdentityAttributes,\n} from \"../server/index.js\";\n\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\n// Special custom 5xx HTTP status code to mean that the UDF returned an error.\n//\n// Must match the constant of the same name in the backend.\nexport const STATUS_CODE_UDF_FAILED = 560;\n\n// Allow fetch to be shimmed in for Node.js < 18\nlet specifiedFetch: typeof globalThis.fetch | undefined = undefined;\nexport function setFetch(f: typeof globalThis.fetch) {\n specifiedFetch = f;\n}\n\nexport type HttpMutationOptions = {\n /**\n * Skip the default queue of mutations and run this immediately.\n *\n * This allows the same HttpConvexClient to be used to request multiple\n * mutations in parallel, something not possible with WebSocket-based clients.\n */\n skipQueue: boolean;\n};\n\n/**\n * A Convex client that runs queries and mutations over HTTP.\n *\n * This client is stateful (it has user credentials and queues mutations)\n * so take care to avoid sharing it between requests in a server.\n *\n * This is appropriate for server-side code (like Netlify Lambdas) or non-reactive\n * webapps.\n *\n * @public\n */\nexport class ConvexHttpClient {\n private readonly address: string;\n private auth: string | undefined;\n private adminAuth: string | undefined;\n private encodedTsPromise?: Promise<string>;\n private debug: boolean;\n private fetchOptions?: FetchOptions;\n private logger: Logger;\n private mutationQueue: Array<{\n mutation: FunctionReference<\"mutation\">;\n args: FunctionArgs<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }> = [];\n private isProcessingQueue: boolean = false;\n\n /**\n * Create a new {@link ConvexHttpClient}.\n *\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - An object of options.\n * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n * Convex backend that uses a different URL.\n * - `logger` - A logger or a boolean. If not provided, logs to the console.\n * You can construct your own logger to customize logging to log elsewhere\n * or not log at all, or use `false` as a shorthand for a no-op logger.\n * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n * These methods can receive multiple arguments of any types, like console.log().\n * - `auth` - A JWT containing identity claims accessible in Convex functions.\n * This identity may expire so it may be necessary to call `setAuth()` later,\n * but for short-lived clients it's convenient to specify this value here.\n */\n constructor(\n address: string,\n options?: {\n skipConvexDeploymentUrlCheck?: boolean;\n logger?: Logger | boolean;\n auth?: string;\n },\n ) {\n if (typeof options === \"boolean\") {\n throw new Error(\n \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\",\n );\n }\n const opts = options ?? {};\n if (opts.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n this.logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: false });\n this.address = address;\n this.debug = true;\n this.auth = undefined;\n this.adminAuth = undefined;\n if (options?.auth) {\n this.setAuth(options.auth);\n }\n }\n\n /**\n * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n * @deprecated Use url, which returns the url without /api at the end.\n *\n * @returns The URL to the Convex backend, including the client's API version.\n */\n backendUrl(): string {\n return `${this.address}/api`;\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n *\n * Should be called whenever the token changes (i.e. due to expiration and refresh).\n *\n * @param value - JWT-encoded OpenID Connect identity token.\n */\n setAuth(value: string) {\n this.clearAuth();\n this.auth = value;\n }\n\n /**\n * Set admin auth token to allow calling internal queries, mutations, and actions\n * and acting as an identity.\n *\n * @internal\n */\n setAdminAuth(token: string, actingAsIdentity?: UserIdentityAttributes) {\n this.clearAuth();\n if (actingAsIdentity !== undefined) {\n // Encode the identity to a base64 string\n const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n } else {\n this.adminAuth = token;\n }\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.auth = undefined;\n this.adminAuth = undefined;\n }\n\n /**\n * Sets whether the result log lines should be printed on the console or not.\n *\n * @internal\n */\n setDebug(debug: boolean) {\n this.debug = debug;\n }\n\n /**\n * Used to customize the fetch behavior in some runtimes.\n *\n * @internal\n */\n setFetchOptions(fetchOptions: FetchOptions) {\n this.fetchOptions = fetchOptions;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Execute a Convex query function at the same timestamp as every other\n * consistent query execution run by this HTTP client.\n *\n * This doesn't make sense for long-lived ConvexHttpClients as Convex\n * backends can read a limited amount into the past: beyond 30 seconds\n * in the past may not be available.\n *\n * Create a new client to use a consistent time.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n *\n * @deprecated This API is experimental: it may change or disappear.\n */\n async consistentQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n\n const timestampPromise = this.getTimestamp();\n return await this.queryInner(query, queryArgs, { timestampPromise });\n }\n\n private async getTimestamp() {\n if (this.encodedTsPromise) {\n return this.encodedTsPromise;\n }\n return (this.encodedTsPromise = this.getTimestampInner());\n }\n\n private async getTimestampInner() {\n const localFetch = specifiedFetch || fetch;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n const response = await localFetch(`${this.address}/api/query_ts`, {\n ...this.fetchOptions,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok) {\n throw new Error(await response.text());\n }\n const { ts } = (await response.json()) as { ts: string };\n return ts;\n }\n\n /**\n * Execute a Convex query function.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n return await this.queryInner(query, queryArgs, {});\n }\n\n private async queryInner<Query extends FunctionReference<\"query\">>(\n query: Query,\n queryArgs: FunctionArgs<Query>,\n options: { timestampPromise?: Promise<string> },\n ): Promise<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n const args = [convexToJson(queryArgs)];\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n\n const timestamp = options.timestampPromise\n ? await options.timestampPromise\n : undefined;\n\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args,\n ...(timestamp ? { ts: timestamp } : {}),\n });\n const endpoint = timestamp\n ? `${this.address}/api/query_at_ts`\n : `${this.address}/api/query`;\n\n const response = await localFetch(endpoint, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"query\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async mutationInner<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n mutationArgs: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n const name = getFunctionName(mutation);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(mutationArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/mutation`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"mutation\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async processMutationQueue() {\n if (this.isProcessingQueue) {\n return;\n }\n\n this.isProcessingQueue = true;\n while (this.mutationQueue.length > 0) {\n const { mutation, args, resolve, reject } = this.mutationQueue.shift()!;\n try {\n const result = await this.mutationInner(mutation, args);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n }\n this.isProcessingQueue = false;\n }\n\n private enqueueMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n return new Promise((resolve, reject) => {\n this.mutationQueue.push({ mutation, args, resolve, reject });\n void this.processMutationQueue();\n });\n }\n\n /**\n * Execute a Convex mutation function. Mutations are queued by default.\n *\n * @param name - The name of the mutation.\n * @param args - The arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - An optional object containing\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, HttpMutationOptions>\n ): Promise<FunctionReturnType<Mutation>> {\n const [fnArgs, options] = args;\n const mutationArgs = parseArgs(fnArgs);\n const queued = !options?.skipQueue;\n\n if (queued) {\n return await this.enqueueMutation(mutation, mutationArgs);\n } else {\n return await this.mutationInner(mutation, mutationArgs);\n }\n }\n\n /**\n * Execute a Convex action function. Actions are not queued.\n *\n * @param name - The name of the action.\n * @param args - The arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const actionArgs = parseArgs(args[0]);\n const name = getFunctionName(action);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(actionArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/action`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"action\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n /**\n * Execute a Convex function of an unknown type. These function calls are not queued.\n *\n * @param name - The name of the function.\n * @param args - The arguments object for the function. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the function's result.\n *\n * @internal\n */\n async function<\n AnyFunction extends FunctionReference<\"query\" | \"mutation\" | \"action\">,\n >(\n anyFunction: AnyFunction | string,\n componentPath?: string,\n ...args: OptionalRestArgs<AnyFunction>\n ): Promise<FunctionReturnType<AnyFunction>> {\n const functionArgs = parseArgs(args[0]);\n const name =\n typeof anyFunction === \"string\"\n ? anyFunction\n : getFunctionName(anyFunction);\n const body = JSON.stringify({\n componentPath: componentPath,\n path: name,\n format: \"convex_encoded_json\",\n args: convexToJson(functionArgs),\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/function`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"any\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n}\n\nfunction forwardErrorData(errorData: JSONValue, error: ConvexError<string>) {\n (error as ConvexError<any>).data = jsonToConvex(errorData);\n return error;\n}\n\n/**\n * @internal\n */\ntype FetchOptions = { cache: \"force-cache\" | \"no-store\" };\n","import { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n BaseConvexClient,\n BaseConvexClientOptions,\n MutationOptions,\n QueryToken,\n UserIdentityAttributes,\n} from \"./index.js\";\nimport {\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n} from \"../server/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { AuthTokenFetcher } from \"./sync/authentication_manager.js\";\nimport { ConnectionState } from \"./sync/client.js\";\n\n// In Node.js builds this points to a bundled WebSocket implementation. If no\n// WebSocket implementation is manually specified or globally available,\n// this one is used.\nlet defaultWebSocketConstructor: typeof WebSocket | undefined;\n\n/** internal */\nexport function setDefaultWebSocketConstructor(ws: typeof WebSocket) {\n defaultWebSocketConstructor = ws;\n}\n\nexport type ConvexClientOptions = BaseConvexClientOptions & {\n /**\n * `disabled` makes onUpdate callback registration a no-op and actions,\n * mutations and one-shot queries throw. Setting disabled to true may be\n * useful for server-side rendering, where subscriptions don't make sense.\n */\n disabled?: boolean;\n /**\n * Whether to prompt users in browsers about queued or in-flight mutations.\n * This only works in environments where `window.onbeforeunload` is available.\n *\n * Defaults to true when `window` is defined, otherwise false.\n */\n unsavedChangesWarning?: boolean;\n};\n\n/**\n * Stops callbacks from running.\n *\n * @public\n */\nexport type Unsubscribe<T> = {\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n (): void;\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n unsubscribe(): void;\n /** Get the last known value, possibly with local optimistic updates applied. */\n getCurrentValue(): T | undefined;\n /** @internal */\n getQueryLogs(): string[] | undefined;\n};\n\n/**\n * Subscribes to Convex query functions and executes mutations and actions over a WebSocket.\n *\n * Optimistic updates for mutations are not provided for this client.\n * Third party clients may choose to wrap {@link browser.BaseConvexClient} for additional control.\n *\n * ```ts\n * const client = new ConvexClient(\"https://happy-otter-123.convex.cloud\");\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages[0].body);\n * });\n * ```\n *\n * @public\n */\nexport class ConvexClient {\n private listeners: Set<QueryInfo>;\n private _client: BaseConvexClient | undefined;\n // A synthetic server event to run callbacks the first time\n private callNewListenersWithCurrentValuesTimer:\n | ReturnType<typeof setTimeout>\n | undefined;\n private _closed: boolean;\n private _disabled: boolean;\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed(): boolean {\n return this._closed;\n }\n get client(): BaseConvexClient {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled(): boolean {\n return this._disabled;\n }\n\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address: string, options: ConvexClientOptions = {}) {\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (\n defaultWebSocketConstructor &&\n !(\"webSocketConstructor\" in baseOptions) &&\n typeof WebSocket === \"undefined\"\n ) {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (\n typeof window === \"undefined\" &&\n !(\"unsavedChangesWarning\" in baseOptions)\n ) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n (updatedQueries) => this._transition(updatedQueries),\n baseOptions,\n );\n }\n this.listeners = new Set();\n }\n\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: FunctionArgs<Query>,\n callback: (result: FunctionReturnType<Query>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<Query[\"_returnType\"]> {\n if (this.disabled) {\n const disabledUnsubscribe = (() => {}) as Unsubscribe<\n Query[\"_returnType\"]\n >;\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<Query[\"_returnType\"]>\n > = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => undefined,\n getQueryLogs: () => undefined,\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n\n // BaseConvexClient takes care of deduplicating queries subscriptions...\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args,\n );\n\n // ...but we still need to bookkeep callbacks to actually call them.\n const queryInfo: QueryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n this.queryResultReady(queryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<Query[\"_returnType\"]>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken),\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n Query[\"_returnType\"]\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n private callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = undefined;\n this._transition([], true);\n }\n\n private queryResultReady(queryToken: QueryToken): boolean {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n\n async close() {\n if (this.disabled) return;\n // prevent pending updates\n this.listeners.clear();\n this._closed = true;\n return this.client.close();\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n\n /**\n * @internal\n */\n _transition(updatedQueries: QueryToken[], callNewListeners = false) {\n // Deduping subscriptions happens in the BaseConvexClient, so not much to do here.\n\n // Call all callbacks in the order they were registered\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n if (\n updatedQueries.includes(queryToken) ||\n (callNewListeners &&\n !hasEverRun &&\n this.client.hasLocalQueryResultByToken(queryToken))\n ) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n newValue = this.client.localQueryResultByToken(queryToken);\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\",\n );\n } else {\n // Make some noise without unsubscribing or failing to call other callbacks.\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\",\n );\n }\n }\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n options?: MutationOptions,\n ): Promise<Awaited<FunctionReturnType<Mutation>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n args: FunctionArgs<Action>,\n ): Promise<Awaited<FunctionReturnType<Action>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n ): Promise<Awaited<Query[\"_returnType\"]>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args) as\n | Awaited<Query[\"_returnType\"]>\n | undefined;\n if (value !== undefined) return Promise.resolve(value);\n\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value) => {\n unsubscribe();\n resolve(value);\n },\n (e: Error) => {\n unsubscribe();\n reject(e);\n },\n );\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n if (this.disabled) return () => {};\n return this.client.subscribeToConnectionState(cb);\n }\n}\n\n// internal information tracked about each registered callback\ntype QueryInfo = {\n callback: (result: any, meta: unknown) => unknown;\n onError: ((e: Error, meta: unknown) => unknown) | undefined;\n unsubscribe: () => void;\n queryToken: QueryToken;\n hasEverRun: boolean;\n // query and args are just here for debugging, the queryToken is authoritative\n query: FunctionReference<\"query\">;\n args: any;\n};\n\ntype RemoveCallSignature<T> = Omit<T, never>;\n","'use strict';\n\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/<platform>-<arch>\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n","const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n","'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0x00) { // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) { // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) { // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80 || // overlong\n buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0 // surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80 || // overlong\n buf[i] === 0xf4 && buf[i + 1] > 0x8f || buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = isValidUTF8;\n","'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {Buffer[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 8 && version !== 13) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message);\n }\n}\n","import {\n ConvexClient,\n setDefaultWebSocketConstructor,\n} from \"./simple_client.js\";\n\n// This file is compiled with `bundle: true` with an exception for\n// `./simple_client.js` so this \"ws\" import will be inlined.\nimport ws from \"ws\";\nconst nodeWebSocket = ws as unknown as typeof WebSocket;\n\nsetDefaultWebSocketConstructor(nodeWebSocket);\n\nexport { ConvexClient };\n","import createWebSocketStream from './lib/stream.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer };\nexport default WebSocket;\n","import { ConvexHttpClient } from \"convex/browser\";\n\nexport const dbClient = () => {\n const convexUrl = process.env.CONVEX_URL;\n if (!convexUrl) {\n throw new Error(\"CONVEX_URL is not set\");\n }\n return new ConvexHttpClient(convexUrl);\n};\n","import { dbClient } from \".\";\n\nexport const getUserIdFromApiKeyOrNull = async (apiKey: string) => {\n const db = dbClient();\n const user = await db.mutation(\n \"apiKeys:validateApiKeyAndReturnUserIdOrNull\" as any,\n { apiKey },\n );\n if (!user) {\n throw new Error(\"Invalid API key\");\n }\n return user;\n};\n","import { ModelMessage } from \"ai\";\n\nimport { dbClient } from \"../db\";\nimport type { TestCase } from \"../utils/validators\";\n\nexport type ConfigSummary = {\n tests: TestCase[];\n environment: { servers: string[] };\n llms: string[];\n};\n\nexport type UsageTotals = {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n};\n\ntype DbClientInstance = ReturnType<typeof dbClient> | null;\n\nexport type PersistenceContext = {\n enabled: boolean;\n apiKey?: string;\n db: DbClientInstance;\n testRunId?: string;\n configSummary: ConfigSummary;\n totalPlannedTests: number;\n};\n\ntype DbPayload = Record<string, unknown>;\n\nconst runDbAction = async <T>(\n persistence: PersistenceContext,\n action: string,\n payload: DbPayload,\n): Promise<T | undefined> => {\n if (!persistence.enabled || !persistence.db) {\n return undefined;\n }\n\n try {\n return await (persistence.db as any).action(action, payload);\n } catch {\n return undefined;\n }\n};\n\nexport const createPersistenceContext = (\n apiKey: string | undefined,\n configSummary: ConfigSummary,\n totalPlannedTests: number,\n): PersistenceContext => ({\n enabled: Boolean(apiKey),\n apiKey,\n db: apiKey ? dbClient() : null,\n configSummary,\n totalPlannedTests,\n});\n\nexport const ensureSuiteRecord = async (persistence: PersistenceContext) => {\n if (!persistence.enabled || !persistence.apiKey || persistence.testRunId) {\n return;\n }\n\n const createdId = await runDbAction<string>(\n persistence,\n \"evals:createEvalTestSuiteWithApiKey\",\n {\n apiKey: persistence.apiKey,\n name: undefined,\n config: persistence.configSummary,\n totalTests: persistence.totalPlannedTests,\n },\n );\n\n if (createdId) {\n persistence.testRunId = createdId;\n }\n};\n\nexport const createTestCaseRecord = async (\n persistence: PersistenceContext,\n test: TestCase,\n testNumber: number,\n) => {\n if (!persistence.enabled || !persistence.apiKey) {\n return undefined;\n }\n\n const testCaseId = await runDbAction<string>(\n persistence,\n \"evals:createEvalTestCaseWithApiKey\",\n {\n apiKey: persistence.apiKey,\n title: String(test.title ?? `Group ${testNumber}`),\n query: String(test.query ?? \"\"),\n provider: String(test.provider ?? \"\"),\n model: String(test.model ?? \"\"),\n runs: Number(test.runs ?? 1),\n },\n );\n\n if (!persistence.testRunId) {\n await ensureSuiteRecord(persistence);\n }\n\n return testCaseId;\n};\n\nexport const createIterationRecord = async (\n persistence: PersistenceContext,\n testCaseId: string | undefined,\n iterationNumber: number,\n startedAt: number,\n) => {\n if (!persistence.enabled || !persistence.apiKey || !testCaseId) {\n return undefined;\n }\n\n return await runDbAction<string>(\n persistence,\n \"evals:createEvalTestIterationWithApiKey\",\n {\n apiKey: persistence.apiKey,\n testCaseId,\n startedAt,\n iterationNumber,\n blob: undefined,\n actualToolCalls: [],\n tokensUsed: 0,\n },\n );\n};\n\nexport const updateIterationResult = async (\n persistence: PersistenceContext,\n evalTestId: string | undefined,\n passed: boolean,\n toolsCalled: string[],\n tokensUsed: UsageTotals,\n messages: ModelMessage[],\n) => {\n if (!persistence.enabled || !persistence.apiKey || !evalTestId) {\n return;\n }\n\n await runDbAction(\n persistence,\n \"evals:updateEvalTestIterationResultWithApiKey\",\n {\n apiKey: persistence.apiKey,\n testId: evalTestId,\n status: \"completed\",\n result: passed ? \"passed\" : \"failed\",\n actualToolCalls: toolsCalled,\n tokensUsed: tokensUsed.totalTokens ?? 0,\n blob: undefined,\n blobContent: { messages },\n },\n );\n};\n\nexport const updateTestCaseResult = async (\n persistence: PersistenceContext,\n testCaseId: string | undefined,\n passedRuns: number,\n failedRuns: number,\n) => {\n if (!persistence.enabled || !persistence.apiKey || !testCaseId) {\n return;\n }\n\n const result = failedRuns > 0 ? \"failed\" : \"passed\";\n\n await runDbAction(persistence, \"evals:updateEvalTestCaseResultWithApiKey\", {\n apiKey: persistence.apiKey,\n testCaseId,\n result,\n });\n};\n\nexport const markSuiteFailed = async (persistence: PersistenceContext) => {\n if (!persistence.enabled || !persistence.apiKey || !persistence.testRunId) {\n return;\n }\n\n await runDbAction(persistence, \"evals:updateEvalTestSuiteStatusWithApiKey\", {\n apiKey: persistence.apiKey,\n testRunId: persistence.testRunId,\n status: \"running\",\n result: \"failed\",\n });\n};\n\nexport const finalizeSuiteStatus = async (\n persistence: PersistenceContext,\n failedRuns: number,\n) => {\n if (!persistence.enabled || !persistence.apiKey || !persistence.testRunId) {\n return;\n }\n\n await runDbAction(persistence, \"evals:updateEvalTestSuiteStatusWithApiKey\", {\n apiKey: persistence.apiKey,\n testRunId: persistence.testRunId,\n status: \"completed\",\n result: failedRuns > 0 ? \"failed\" : \"passed\",\n finishedAt: Date.now(),\n });\n};\n","import { z, ZodTypeAny } from \"zod\";\nimport type {\n LogHandler,\n MastraMCPServerDefinition,\n MCPClientOptions,\n} from \"@mastra/mcp\";\nimport { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransportOptions } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { ClientCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\nimport { type Tool as VercelTool } from \"ai\";\nimport { convertMastraToolsToVercelTools } from \"../../../shared/tools\";\n\nexport const AdvancedConfigSchema = z\n .object({\n system: z.string().optional(),\n temperature: z.number().optional(),\n toolChoice: z.string().optional(),\n })\n .passthrough(); // Allow additional fields\n\nexport const TestCaseSchema = z.object({\n title: z.string(),\n query: z.string(),\n runs: z.number().int(),\n model: z.string(),\n provider: z.string(),\n expectedToolCalls: z.array(z.string()),\n judgeRequirement: z.string().optional(),\n advancedConfig: AdvancedConfigSchema.optional(),\n});\n\nexport type TestCase = z.infer<typeof TestCaseSchema>;\n\nexport function validateTestCase(value: unknown): TestCase[] {\n try {\n const result = z.array(TestCaseSchema).parse(value);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(error.message);\n }\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n\nconst BaseServerOptionsSchema = z.object({\n logger: z.custom<LogHandler>().optional(),\n timeout: z.number().optional(),\n capabilities: z.custom<ClientCapabilities>().optional(),\n enableServerLogs: z.boolean().optional(),\n});\n\nconst StdioServerDefinitionSchema = BaseServerOptionsSchema.extend({\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n}).strict();\n\nconst HttpServerDefinitionSchema = BaseServerOptionsSchema.extend({\n // Accept either a URL object or a string URL, but we'll normalize to string\n url: z.union([z.string().url(), z.instanceof(URL)]),\n requestInit: z\n .custom<StreamableHTTPClientTransportOptions[\"requestInit\"]>()\n .optional(),\n eventSourceInit: z\n .custom<SSEClientTransportOptions[\"eventSourceInit\"]>()\n .optional(),\n authProvider: z\n .custom<StreamableHTTPClientTransportOptions[\"authProvider\"]>()\n .optional(),\n reconnectionOptions: z\n .custom<StreamableHTTPClientTransportOptions[\"reconnectionOptions\"]>()\n .optional(),\n sessionId: z\n .custom<StreamableHTTPClientTransportOptions[\"sessionId\"]>()\n .optional(),\n}).strict();\n\nexport const MCPClientOptionsSchema = z.custom<MCPClientOptions>();\nexport const MastraMCPServerDefinitionSchema = z.union([\n StdioServerDefinitionSchema,\n HttpServerDefinitionSchema,\n]);\n\nexport function validateAndNormalizeMCPClientConfiguration(\n value: unknown,\n): MCPClientOptions {\n try {\n const envParsed = MCPClientOptionsSchema.parse(value);\n\n const normalizedServers: Record<string, MastraMCPServerDefinition> = {};\n\n for (const [name, server] of Object.entries(envParsed.servers)) {\n try {\n if (server && typeof server === \"object\" && \"url\" in server) {\n MastraMCPServerDefinitionSchema.parse(server);\n server.enableServerLogs = false;\n const urlValue = (server as any).url;\n const normalizedUrl =\n typeof urlValue === \"string\"\n ? new URL(urlValue)\n : (urlValue as URL);\n const normalizedServer = {\n ...(server as Record<string, any>),\n url: normalizedUrl,\n } as Record<string, any>;\n normalizedServers[name] =\n normalizedServer as MastraMCPServerDefinition;\n } else {\n MastraMCPServerDefinitionSchema.parse(server);\n server.enableServerLogs = false;\n normalizedServers[name] = server;\n }\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(\n `Invalid server configuration for '${name}': ${error.message}`,\n );\n }\n throw new Error(`Invalid server configuration for '${name}': ${error}`);\n }\n }\n\n return {\n ...envParsed,\n servers: normalizedServers,\n };\n } catch (error) {\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n\nexport { convertMastraToolsToVercelTools };\n\nexport const LlmsConfigSchema = z\n .object({\n anthropic: z.string().optional(),\n openai: z.string().optional(),\n openrouter: z.string().optional(),\n })\n .passthrough(); // Allow additional LLM providers\n\nexport type LlmsConfig = z.infer<typeof LlmsConfigSchema>;\n\nexport function validateLlms(value: unknown): LlmsConfig {\n try {\n const result = LlmsConfigSchema.parse(value);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new Error(`Invalid LLMs configuration: ${error.message}`);\n }\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n}\n","import { z, ZodTypeAny } from \"zod\";\nimport { tool, type Tool as VercelTool, type ToolCallOptions } from \"ai\";\n\ntype MastraToolExecuteArgs = {\n context?: unknown;\n runtimeContext?: unknown;\n};\n\ntype MastraToolInstance = {\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n execute?: (\n args: MastraToolExecuteArgs,\n options?: ToolCallOptions,\n ) => Promise<unknown> | unknown;\n};\n\nconst fallbackInputSchema = z.object({}).passthrough();\n\nfunction isZodSchema(value: unknown): value is ZodTypeAny {\n return Boolean(\n value && typeof value === \"object\" && \"safeParse\" in (value as ZodTypeAny),\n );\n}\n\nfunction ensureInputSchema(schema: unknown): ZodTypeAny {\n if (isZodSchema(schema)) {\n return schema;\n }\n\n return fallbackInputSchema;\n}\n\nfunction ensureOutputSchema(schema: unknown): ZodTypeAny | undefined {\n if (isZodSchema(schema)) {\n return schema;\n }\n\n return undefined;\n}\n\nfunction extractPureToolName(toolKey: string): string {\n const separatorIndex = toolKey.indexOf(\"_\");\n\n if (separatorIndex === -1 || separatorIndex === toolKey.length - 1) {\n return toolKey;\n }\n\n return toolKey.slice(separatorIndex + 1);\n}\n\nexport function convertMastraToolToVercelTool(\n toolName: string,\n mastraTool: MastraToolInstance,\n options?: { originalName?: string },\n): VercelTool {\n const inputSchema = ensureInputSchema(mastraTool.inputSchema);\n const outputSchema = ensureOutputSchema(mastraTool.outputSchema);\n const displayName = options?.originalName ?? toolName;\n\n const vercelToolConfig: {\n type: \"dynamic\";\n description?: string;\n inputSchema: ZodTypeAny;\n outputSchema?: ZodTypeAny;\n execute?: (input: unknown, options: ToolCallOptions) => Promise<unknown>;\n } = {\n type: \"dynamic\",\n description: mastraTool.description,\n inputSchema,\n };\n\n if (outputSchema) {\n vercelToolConfig.outputSchema = outputSchema;\n }\n\n if (typeof mastraTool.execute === \"function\") {\n vercelToolConfig.execute = async (input, options) => {\n const executionArgs: MastraToolExecuteArgs = { context: input };\n\n if (options) {\n executionArgs.runtimeContext = options;\n }\n\n const result = await mastraTool.execute?.(executionArgs, options);\n\n if (outputSchema) {\n const parsed = outputSchema.safeParse(result);\n\n if (!parsed.success) {\n throw new Error(\n `Mastra tool '${displayName}' returned invalid output: ${parsed.error.message}`,\n );\n }\n\n return parsed.data;\n }\n\n return result;\n };\n }\n\n return tool(vercelToolConfig);\n}\n\nexport function convertMastraToolsToVercelTools(\n mastraTools: Record<string, MastraToolInstance>,\n): Record<string, VercelTool> {\n return Object.fromEntries(\n Object.entries(mastraTools).map(([name, mastraTool]) => {\n const pureToolName = extractPureToolName(name);\n\n return [\n pureToolName,\n convertMastraToolToVercelTool(pureToolName, mastraTool, {\n originalName: name,\n }),\n ];\n }),\n );\n}\n","import { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport { createOpenAI } from \"@ai-sdk/openai\";\nimport { createAnthropic } from \"@ai-sdk/anthropic\";\nimport { LlmsConfig } from \"./validators\";\nimport { LanguageModel, ToolSet, TypedToolCall } from \"ai\";\n\nexport const createLlmModel = (\n provider: string,\n model: string,\n llmsConfig: LlmsConfig,\n): LanguageModel => {\n if (!llmsConfig[provider]) {\n throw new Error(`LLM API key not found for provider: ${provider}`);\n }\n switch (provider) {\n case \"anthropic\":\n return createAnthropic({ apiKey: llmsConfig.anthropic })(model);\n case \"openai\":\n return createOpenAI({ apiKey: llmsConfig.openai })(model);\n case \"openrouter\":\n return createOpenRouter({ apiKey: llmsConfig.openrouter })(model);\n default:\n throw new Error(`Unsupported provider: ${provider}`);\n }\n};\n\nexport const extractToolNamesAsArray = (\n toolCalls: TypedToolCall<ToolSet>[],\n) => {\n return toolCalls.map((toolCall) => toolCall.toolName);\n};\n","export type EvaluationResult = {\n expectedToolCalls: string[];\n toolsCalled: string[];\n missing: string[];\n unexpected: string[];\n passed: boolean;\n};\n\nexport const evaluateResults = (\n expectedToolCalls: string[],\n toolsCalled: string[],\n) => {\n return {\n expectedToolCalls,\n toolsCalled,\n missing: expectedToolCalls.filter((tool) => !toolsCalled.includes(tool)),\n unexpected: toolsCalled.filter((tool) => !expectedToolCalls.includes(tool)),\n passed:\n expectedToolCalls.length === toolsCalled.length &&\n expectedToolCalls.every((tool) => toolsCalled.includes(tool)),\n };\n};\n","import { randomUUID } from \"crypto\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { readFileSync, writeFileSync, existsSync, mkdirSync } from \"fs\";\n\nconst CONFIG_DIR = join(homedir(), \".mcpjam\");\nconst USER_ID_FILE = join(CONFIG_DIR, \"user-id.json\");\n\ninterface UserConfig {\n userId: string;\n createdAt: string;\n}\n\n/**\n * Gets or creates a unique user ID stored locally\n * @returns A persistent unique identifier for this user\n */\nexport function getUserId(): string {\n try {\n // Ensure config directory exists\n if (!existsSync(CONFIG_DIR)) {\n mkdirSync(CONFIG_DIR, { recursive: true });\n }\n\n // Check if user ID file exists\n if (existsSync(USER_ID_FILE)) {\n const configData = readFileSync(USER_ID_FILE, \"utf8\");\n const config: UserConfig = JSON.parse(configData);\n\n // Validate that we have a valid userId\n if (config.userId && typeof config.userId === \"string\") {\n return config.userId;\n }\n }\n\n // Generate new user ID\n const newUserId = randomUUID();\n const newConfig: UserConfig = {\n userId: newUserId,\n createdAt: new Date().toISOString(),\n };\n\n // Save to file\n writeFileSync(USER_ID_FILE, JSON.stringify(newConfig, null, 2));\n\n return newUserId;\n } catch (error) {\n // Fallback to session-based UUID if file operations fail\n console.warn(\"Failed to persist user ID, using session-based ID:\", error);\n return randomUUID();\n }\n}\n","import { PostHog } from \"posthog-node\";\n\nexport const hogClient = new PostHog(\n \"phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9\",\n { host: \"https://us.i.posthog.com\" },\n);\n","{\n \"name\": \"@mcpjam/cli\",\n \"version\": \"1.1.3\",\n \"type\": \"module\",\n \"description\": \"MCPJam CLI for programmatic MCP testing and evals\",\n \"license\": \"Apache-2.0\",\n \"author\": \"MCPJam (https://mcpjam.com)\",\n \"homepage\": \"https://mcpjam.com\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/MCPJam/inspector.git\",\n \"directory\": \"cli\"\n },\n \"main\": \"dist/index.js\",\n \"bin\": {\n \"mcpjam\": \"bin/mcpjam.js\"\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"package.json\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"build-and-test\": \"npm run build && npm run test\",\n \"test\": \"node bin/mcpjam.js evals run -t local-examples/tests.json -e local-examples/environment.json -l local-examples/llms.json\",\n \"start\": \"node bin/mcpjam.js\"\n },\n \"dependencies\": {\n \"@ai-sdk/anthropic\": \"^2.0.17\",\n \"@ai-sdk/openai\": \"^2.0.32\",\n \"@hono/node-server\": \"^1.13.7\",\n \"@mastra/core\": \"^0.18.0\",\n \"@mastra/mcp\": \"^0.13.1\",\n \"@modelcontextprotocol/sdk\": \"^1.17.3\",\n \"@openrouter/ai-sdk-provider\": \"^1.2.0\",\n \"ai\": \"^5.0.11\",\n \"chalk\": \"^5.6.0\",\n \"cli-table3\": \"^0.6.5\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^17.2.2\",\n \"hono\": \"^4.6.11\",\n \"ollama-ai-provider-v2\": \"^1.3.1\",\n \"posthog-node\": \"^5.9.1\",\n \"update-notifier\": \"^7.3.1\",\n \"zod\": \"^4.0.16\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20\",\n \"@types/update-notifier\": \"^6.0.8\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5\"\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,WAAAA,gBAAe;AACxB,SAAS,iBAAAC,sBAAqB;;;ACF9B,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB,SAAS,eAAe;;;ACFxB,OAAO,WAAW;AAwClB,IAAM,qBAAqB;AAEpB,IA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arr","value","v","__publicField","name","__publicField","__publicField","name","resolve","createWebSocketStream","err","name","resolve","dir","arr","platform","arch","runtime","abi","require_node_gyp_build","mask","data","require_fallback","code","Receiver","Sender","v","URL","WebSocket","key","protocol","WebSocketServer","version","z","options","name","z","name","z","tool","config","require","createRequire","version","Command"]}